Answer the question
In order to leave comments, you need to log in
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. 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
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;
}
}
${currentUser}
(current authorized user) <div class="comments" th:each="comment : ${comments}">
<input th:if="${comment.author} eq ${currentUser}" type="button" value="Отредактировать комментарий"/>
</div>
@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 questionAsk a Question
731 491 924 answers to any question