Skip to content

Commit

Permalink
поддержка заморозки анонимуса
Browse files Browse the repository at this point in the history
  • Loading branch information
maxcom committed Nov 11, 2023
1 parent 128e257 commit 6708290
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 64 deletions.
20 changes: 9 additions & 11 deletions src/main/java/ru/org/linux/comment/CommentCreateService.java
Original file line number Diff line number Diff line change
Expand Up @@ -241,21 +241,19 @@ public Comment getComment(
* @param errors обработчик ошибок ввода для формы
* @return объект пользователя
*/
public User getCommentUser(CommentRequest commentRequest, Errors errors) {
User currentUser = AuthUtil.getCurrentUser();

public User getCommentUser(@Nullable User currentUser, CommentRequest commentRequest, Errors errors) {
if (currentUser!=null) {
return currentUser;
}
} else {
if (commentRequest.getNick() != null) {
if (commentRequest.getPassword() == null) {
errors.reject(null, "Требуется авторизация");
}

if (commentRequest.getNick() != null) {
if (commentRequest.getPassword() == null) {
errors.reject(null, "Требуется авторизация");
return commentRequest.getNick();
} else {
return userService.getAnonymous();
}

return commentRequest.getNick();
} else {
return userService.getAnonymous();
}
}

Expand Down
57 changes: 31 additions & 26 deletions src/main/java/ru/org/linux/topic/TopicPermissionService.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import ru.org.linux.spring.SiteConfig;
import ru.org.linux.spring.dao.DeleteInfoDao;
import ru.org.linux.user.User;
import ru.org.linux.user.UserService;
import scala.Option;
import scala.Some;

Expand Down Expand Up @@ -64,13 +65,15 @@ public class TopicPermissionService {
private final GroupDao groupDao;

private final DeleteInfoDao deleteInfoDao;
private final UserService userService;

public TopicPermissionService(CommentReadService commentService, SiteConfig siteConfig, GroupDao groupDao,
DeleteInfoDao deleteInfoDao) {
DeleteInfoDao deleteInfoDao, UserService userService) {
this.commentService = commentService;
this.siteConfig = siteConfig;
this.groupDao = groupDao;
this.deleteInfoDao = deleteInfoDao;
this.userService = userService;
}

public static String getPostScoreInfo(int postscore) {
Expand Down Expand Up @@ -192,7 +195,7 @@ public void checkView(
}
}

public void checkCommentsAllowed(Topic topic, User user, Errors errors) {
public void checkCommentsAllowed(Topic topic, Optional<User> user, Errors errors) {
if (topic.isDeleted()) {
errors.reject(null, "Нельзя добавлять комментарии к удаленному сообщению");
return;
Expand Down Expand Up @@ -253,12 +256,14 @@ public int getPostscore(Topic topic) {
return getPostscore(group, topic);
}

public boolean isCommentsAllowed(Group group, Topic topic, User user, boolean ignoreFrozen) {
if (user != null && (user.isBlocked() || (!ignoreFrozen && user.isFrozen()))) {
public boolean isCommentsAllowed(Group group, Topic topic, Optional<User> user, boolean ignoreFrozen) {
if (topic.isDeleted() || topic.isExpired() || topic.isDraft()) {
return false;
}

if (topic.isDeleted() || topic.isExpired() || topic.isDraft()) {
var effectiveUser = user.orElseGet(userService::getAnonymous);

if (effectiveUser.isBlocked() || (!ignoreFrozen && effectiveUser.isFrozen())) {
return false;
}

Expand All @@ -272,32 +277,32 @@ public boolean isCommentsAllowed(Group group, Topic topic, User user, boolean ig
return true;
}

if (user == null || user.isAnonymous()) {
if (user.isEmpty() || user.get().isAnonymous()) {
return false;
}

if (user.isModerator()) {
return true;
}
} else {
if (user.get().isModerator()) {
return true;
}

if (score == POSTSCORE_REGISTERED_ONLY) {
return true;
}
if (score == POSTSCORE_REGISTERED_ONLY) {
return true;
}

if (score == POSTSCORE_MODERATORS_ONLY) {
return false;
}
if (score == POSTSCORE_MODERATORS_ONLY) {
return false;
}

boolean isAuthor = user.getId() == topic.getAuthorUserId();
boolean isAuthor = user.get().getId() == topic.getAuthorUserId();

if (score == POSTSCORE_MOD_AUTHOR) {
return isAuthor;
}
if (score == POSTSCORE_MOD_AUTHOR) {
return isAuthor;
}

if (isAuthor) {
return true;
} else {
return user.getScore() >= score;
if (isAuthor) {
return true;
} else {
return user.get().getScore() >= score;
}
}
}

Expand Down Expand Up @@ -338,7 +343,7 @@ public boolean isCommentEditableNow(@Nonnull Comment comment, @Nullable User cur
boolean haveAnswers, @Nonnull Topic topic, MarkupType markup) {
Errors errors = new MapBindingResult(ImmutableMap.of(), "obj");

checkCommentsAllowed(topic, currentUser, errors);
checkCommentsAllowed(topic, Optional.ofNullable(currentUser), errors);
checkCommentEditableNow(comment, currentUser, haveAnswers, topic, errors, markup);

return !errors.hasErrors();
Expand Down
26 changes: 14 additions & 12 deletions src/main/scala/ru/org/linux/comment/AddCommentController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import org.springframework.web.bind.WebDataBinder
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.view.RedirectView
import ru.org.linux.auth.AuthUtil.AuthorizedOpt
import ru.org.linux.auth.{AccessViolationException, AuthUtil, IPBlockDao, IPBlockInfo}
import ru.org.linux.csrf.CSRFNoAuto
import ru.org.linux.markup.{MarkupPermissions, MarkupType, MessageTextService}
Expand All @@ -39,6 +40,7 @@ import ru.org.linux.util.{ServletParameterException, StringUtil}
import java.util.Optional
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
import scala.compat.java8.OptionConverters.RichOptionForJava8
import scala.jdk.CollectionConverters.*

@Controller
Expand All @@ -54,7 +56,7 @@ class AddCommentController(ipBlockDao: IPBlockDao, commentPrepareService: Commen
* Показ формы добавления ответа на комментарий.
*/
@RequestMapping(value = Array("/add_comment.jsp"), method = Array(RequestMethod.GET))
def showFormReply(@ModelAttribute("add") @Valid add: CommentRequest, errors: Errors): ModelAndView = {
def showFormReply(@ModelAttribute("add") @Valid add: CommentRequest, errors: Errors): ModelAndView = AuthorizedOpt { currentUser =>
if (add.getTopic == null)
throw new ServletParameterException("тема не задана")

Expand All @@ -64,11 +66,11 @@ class AddCommentController(ipBlockDao: IPBlockDao, commentPrepareService: Commen
add.setMode(tmpl.getFormatMode)
}

topicPermissionService.checkCommentsAllowed(add.getTopic, AuthUtil.getCurrentUser, errors)
topicPermissionService.checkCommentsAllowed(add.getTopic, currentUser.map(_.user).asJava, errors)

val postscore = topicPermissionService.getPostscore(add.getTopic)

new ModelAndView("add_comment", (commentService.prepareReplyto(add, AuthUtil.getCurrentUser, tmpl.getProf, add.getTopic).asScala + (
new ModelAndView("add_comment", (commentService.prepareReplyto(add, currentUser.map(_.user).orNull, tmpl.getProf, add.getTopic).asScala.toMap + (
"postscoreInfo" -> TopicPermissionService.getPostScoreInfo(postscore)
)).asJava)
}
Expand All @@ -77,11 +79,11 @@ class AddCommentController(ipBlockDao: IPBlockDao, commentPrepareService: Commen
* Показ топика с формой добавления комментария верхнего уровня.
*/
@RequestMapping(Array("/comment-message.jsp"))
def showFormTopic(@ModelAttribute("add") @Valid add: CommentRequest): ModelAndView = {
def showFormTopic(@ModelAttribute("add") @Valid add: CommentRequest): ModelAndView = AuthorizedOpt { currentUser =>
val tmpl = Template.getTemplate
val preparedTopic = topicPrepareService.prepareTopic(add.getTopic, AuthUtil.getCurrentUser)
val preparedTopic = topicPrepareService.prepareTopic(add.getTopic, currentUser.map(_.user).orNull)

if (!topicPermissionService.isCommentsAllowed(preparedTopic.group, add.getTopic, AuthUtil.getCurrentUser, false))
if (!topicPermissionService.isCommentsAllowed(preparedTopic.group, add.getTopic, currentUser.map(_.user).asJava, false))
throw new AccessViolationException("Это сообщение нельзя комментировать")

if (add.getMode == null) {
Expand All @@ -102,14 +104,14 @@ class AddCommentController(ipBlockDao: IPBlockDao, commentPrepareService: Commen
@RequestMapping(value = Array("/add_comment.jsp"), method = Array(RequestMethod.POST))
@CSRFNoAuto
def addComment(@ModelAttribute("add") @Valid add: CommentRequest, errors: Errors, request: HttpServletRequest,
@ModelAttribute("ipBlockInfo") ipBlockInfo: IPBlockInfo): ModelAndView = {
val user = commentService.getCommentUser(add, errors)
@ModelAttribute("ipBlockInfo") ipBlockInfo: IPBlockInfo): ModelAndView = AuthorizedOpt { sessionUserOpt =>
val user = commentService.getCommentUser(sessionUserOpt.map(_.user).orNull, add, errors)
commentService.checkPostData(add, user, ipBlockInfo, request, errors, false)

val comment = commentService.getComment(add, user, request)

if (add.getTopic != null) {
topicPermissionService.checkCommentsAllowed(add.getTopic, user, errors)
topicPermissionService.checkCommentsAllowed(add.getTopic, Some(user).asJava, errors)
}

val tmpl = Template.getTemplate
Expand Down Expand Up @@ -154,16 +156,16 @@ class AddCommentController(ipBlockDao: IPBlockDao, commentPrepareService: Commen
method = Array(RequestMethod.POST))
@ResponseBody
def addCommentAjax(@ModelAttribute("add") @Valid add: CommentRequest, errors: Errors, request: HttpServletRequest,
@ModelAttribute("ipBlockInfo") ipBlockInfo: IPBlockInfo): Json = {
val user = commentService.getCommentUser(add, errors)
@ModelAttribute("ipBlockInfo") ipBlockInfo: IPBlockInfo): Json = AuthorizedOpt { sessionUserOpt =>
val user = commentService.getCommentUser(sessionUserOpt.map(_.user).orNull, add, errors)

commentService.checkPostData(add, user, ipBlockInfo, request, errors, false)

val msg = commentService.getCommentBody(add, user, errors)
val comment = commentService.getComment(add, user, request)

if (add.getTopic != null) {
topicPermissionService.checkCommentsAllowed(add.getTopic, user, errors)
topicPermissionService.checkCommentsAllowed(add.getTopic, Some(user).asJava, errors)
}

if (add.isPreviewMode || errors.hasErrors || comment == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ class CommentPrepareService(textService: MessageTextService, msgbaseDao: Msgbase
val deletable = topicPermissionService.isCommentDeletableNow(comment, currentUser.orNull, topic, hasAnswers)
val editable = topicPermissionService.isCommentEditableNow(comment, currentUser.orNull, hasAnswers, topic, messageText.markup)

val authorReadonly = !topicPermissionService.isCommentsAllowed(group, topic, author, true)
val authorReadonly = !topicPermissionService.isCommentsAllowed(group, topic, Some(author).toJava, true)

PreparedComment(comment = comment, author = author, processedMessage = processedMessage, reply = replyInfo,
deletable = deletable, editable = editable, remark = remark, userpic = userpic, deleteInfo = apiDeleteInfo,
Expand Down Expand Up @@ -167,13 +167,6 @@ class CommentPrepareService(textService: MessageTextService, msgbaseDao: Msgbase
processedMessage = processedMessage, deletable = false, reactions = PreparedReactions.emptyDisabled)
}

def prepareCommentListRSS(list: Seq[Comment]): Seq[PreparedRSSComment] = {
list.map { comment =>
val messageText = msgbaseDao.getMessageText(comment.id)
prepareRSSComment(messageText, comment)
}
}

def prepareCommentList(comments: CommentList, list: Seq[Comment], topic: Topic, hideSet: Set[Int],
currentUser: Option[User], profile: Profile, ignoreList: Set[Int],
filterShow: Boolean): Seq[PreparedComment] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import org.springframework.web.bind.WebDataBinder
import org.springframework.web.bind.annotation.{InitBinder, ModelAttribute, RequestMapping, RequestMethod}
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.view.RedirectView
import ru.org.linux.auth.AuthUtil.AuthorizedOnly
import ru.org.linux.auth.AuthUtil.{AuthorizedOnly, AuthorizedOpt}
import ru.org.linux.auth.{AuthUtil, IPBlockDao, IPBlockInfo}
import ru.org.linux.csrf.CSRFNoAuto
import ru.org.linux.markup.{MarkupType, MessageTextService}
Expand All @@ -34,6 +34,7 @@ import ru.org.linux.util.ServletParameterException
import java.util
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
import scala.compat.java8.OptionConverters.RichOptionForJava8

@Controller
class EditCommentController(commentService: CommentCreateService, msgbaseDao: MsgbaseDao, ipBlockDao: IPBlockDao,
Expand Down Expand Up @@ -98,8 +99,8 @@ class EditCommentController(commentService: CommentCreateService, msgbaseDao: Ms
@CSRFNoAuto
def editCommentPostHandler(@ModelAttribute("add") @Valid commentRequest: CommentRequest, errors: Errors,
request: HttpServletRequest,
@ModelAttribute("ipBlockInfo") ipBlockInfo: IPBlockInfo): ModelAndView = {
val user = commentService.getCommentUser(commentRequest, errors)
@ModelAttribute("ipBlockInfo") ipBlockInfo: IPBlockInfo): ModelAndView = AuthorizedOnly { currentUser =>
val user = currentUser.user
commentService.checkPostData(commentRequest, user, ipBlockInfo, request, errors, true)

val comment = commentService.getComment(commentRequest, user, request)
Expand All @@ -120,7 +121,7 @@ class EditCommentController(commentService: CommentCreateService, msgbaseDao: Ms
if (commentRequest.getTopic != null) {
val postscore = topicPermissionService.getPostscore(commentRequest.getTopic)
formParams.put("postscoreInfo", TopicPermissionService.getPostScoreInfo(postscore))
topicPermissionService.checkCommentsAllowed(commentRequest.getTopic, user, errors)
topicPermissionService.checkCommentsAllowed(commentRequest.getTopic, Some(user).asJava, errors)
formParams.put("comment", commentPrepareService.prepareCommentForEdit(comment, msg))
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/ru/org/linux/topic/TopicController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ class TopicController(sectionService: SectionService, topicDao: TopicDao, prepar
params.put("group", group)
params.put("showAdsense", Boolean.box(currentUserOpt.isEmpty || !tmpl.getProf.isHideAdsense))

if (currentUserOpt.isEmpty) { // because users have IgnoreList and memories
if (currentUserOpt.isEmpty && topic.expired) {
val etag = TopicController.getEtag(topic)

response.setHeader("Etag", etag)
Expand Down
4 changes: 2 additions & 2 deletions src/main/scala/ru/org/linux/topic/TopicPrepareService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import ru.org.linux.util.StringUtil

import javax.annotation.Nullable
import scala.jdk.CollectionConverters.*
import scala.jdk.OptionConverters.RichOptional
import scala.jdk.OptionConverters.{RichOption, RichOptional}

@Service
class TopicPrepareService(sectionService: SectionService, groupDao: GroupDao, deleteInfoDao: DeleteInfoDao,
Expand Down Expand Up @@ -215,7 +215,7 @@ class TopicPrepareService(sectionService: SectionService, groupDao: GroupDao, de
val showComments = postscore != TopicPermissionService.POSTSCORE_HIDE_COMMENTS

new TopicMenu(topicEditable, tagsEditable, resolvable,
topicPermissionService.isCommentsAllowed(topic.group, topic.message, currentUser, false), deletable,
topicPermissionService.isCommentsAllowed(topic.group, topic.message, Option(currentUser).toJava, false), deletable,
undeletable, groupPermissionService.canCommit(currentUser, topic.message), userpic.orNull, showComments)
}

Expand Down

0 comments on commit 6708290

Please sign in to comment.