A
A
Andrew2020-05-07 09:48:49
Java
Andrew, 2020-05-07 09:48:49

How to allow a user to edit only their own comments?

Hello!
I started setting up spring security in my Spring Boot project.
How to allow a user to edit only their own comments? annotation

@PreAuthorize("(hasAuthority('USER') and principal.id == #userId)")
doesn't fit because the userId is missing in the method signature.

How can I check that an authorized user is the author of a comment?

Service code:
public CommentReadDTO patchComment(UUID articleId, UUID commentId, CommentPatchDTO patchDTO) {
        Comment comment = getCommentRequired(targetObjectId, id);

        translationService.map(patchDTO, comment);
        comment = commentRepository.save(comment);

        return translationService.translate(comment, CommentReadDTO.class);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2020-05-07
Hasanly @azerphoenix

I have several ideas for solving this problem. Which of them is correct I will not say, but nevertheless it will solve your problems.
So,
first let's create a controllerAdvice

@RequiredArgsConstructor
@ControllerAdvice
public class GlobalControllerAdvice {
private final UserServiceImpl userServiceImpl;

@ModelAttribute("currentUser")
    public User getUserProfile(
            @AuthenticationPrincipal UserDetails currentUser
    ) {
        if (currentUser != null)
            return (User) userServiceImpl.findUserByEmail(currentUser.getUsername());
        return null;
    }

}

Now, we have access to a variable ${currentUser}(current authorized user)
Next, let's say that we want to display an edit icon on the client by clicking on which the user will be able to edit the comment.
When you cycle through a list of comments in html (in a template engine), simply compare the current authorized user and the author of each comment. If equals(), then show the edit icon, and if not, then don't show it.
For example, for thymeleaf
<div class="comments" th:each="comment : ${comments}"> 
<input th:if="${comment.author} eq ${currentUser}" type="button" value="Отредактировать комментарий"/>
</div>

Or, instead of comparing objects, you can compare their id, etc.
And if you need to check the author in the controller method, then we get the current user:
@GetMapping("/edit/{commentId}")
public String editComment(
@PathVariable("commentId") Long commentId,
@AuthenticationPrincipal UserDetails currentUser,
) {
User user = (User) userServiceImpl.findUserByEmail(currentUser.getUsername());
/*
Далее находим комментарий по его id. находим его автора и сравниваем с user.
*/

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question