Skip to content

Commit

Permalink
delip и banip в одной форме
Browse files Browse the repository at this point in the history
  • Loading branch information
maxcom committed Aug 13, 2024
1 parent 2277549 commit 0067628
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 155 deletions.
63 changes: 25 additions & 38 deletions src/main/java/ru/org/linux/auth/BanIPController.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 1998-2022 Linux.org.ru
* Copyright 1998-2024 Linux.org.ru
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
Expand All @@ -15,7 +15,6 @@

package ru.org.linux.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -31,15 +30,15 @@
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Optional;

@Controller
public class BanIPController {
private IPBlockDao ipBlockDao;
private final IPBlockDao ipBlockDao;

@Autowired
public void setIpBlockDao(IPBlockDao ipBlockDao) {
public BanIPController(IPBlockDao ipBlockDao) {
this.ipBlockDao = ipBlockDao;
}

Expand All @@ -58,42 +57,30 @@ public ModelAndView banIP(
throw new IllegalAccessException("Not authorized");
}

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Optional<OffsetDateTime> banTo = switch (time) {
case "hour" -> Optional.of(OffsetDateTime.now().plusHours(1));
case "day" -> Optional.of(OffsetDateTime.now().plusDays(1));
case "month" -> Optional.of(OffsetDateTime.now().plusMonths(1));
case "3month" -> Optional.of(OffsetDateTime.now().plusMonths(3));
case "6month" -> Optional.of(OffsetDateTime.now().plusMonths(6));
case "custom" -> {
int days = ServletRequestUtils.getRequiredIntParameter(request, "ban_days");

if ("hour".equals(time)) {
calendar.add(Calendar.HOUR_OF_DAY, 1);
} else if ("day".equals(time)) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
} else if ("month".equals(time)) {
calendar.add(Calendar.MONTH, 1);
} else if ("3month".equals(time)) {
calendar.add(Calendar.MONTH, 3);
} else if ("6month".equals(time)) {
calendar.add(Calendar.MONTH, 6);
} else if ("remove".equals(time)) {
} else if ("custom".equals(time)) {
int days = ServletRequestUtils.getRequiredIntParameter(request, "ban_days");
if (days <= 0 || days > 180) {
throw new UserErrorException("Invalid days count");
}

if (days <= 0 || days > 180) {
throw new UserErrorException("Invalid days count");
yield Optional.of(OffsetDateTime.now().plusDays(days));
}
case "unlim" -> Optional.empty();
case "remove" -> Optional.of(OffsetDateTime.now());
default -> throw new UserErrorException("Invalid count");
};

calendar.add(Calendar.DAY_OF_MONTH, days);
}

Timestamp ts;
if ("unlim".equals(time)) {
ts = null;
} else {
ts = new Timestamp(calendar.getTimeInMillis());
}

User user = AuthUtil.getCurrentUser();

user.checkCommit();
User moderator = AuthUtil.getCurrentUser();

ipBlockDao.blockIP(ip, user.getId(), reason, ts, allowPosting, captchaRequired);
ipBlockDao.blockIP(ip, moderator.getId(), reason, banTo.map(v -> new Timestamp(v.toInstant().toEpochMilli())).orElse(null),
allowPosting, captchaRequired);

return new ModelAndView(new RedirectView("sameip.jsp?ip=" + URLEncoder.encode(ip, StandardCharsets.UTF_8)));
}
Expand Down
80 changes: 57 additions & 23 deletions src/main/java/ru/org/linux/spring/DelIPController.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@

package ru.org.linux.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import ru.org.linux.auth.AccessViolationException;
import ru.org.linux.auth.AuthUtil;
import ru.org.linux.auth.IPBlockDao;
import ru.org.linux.comment.CommentDeleteService;
import ru.org.linux.comment.DeleteCommentResult;
import ru.org.linux.search.SearchQueueSender;
Expand All @@ -31,18 +31,23 @@
import ru.org.linux.user.UserErrorException;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Controller
public class DelIPController {
@Autowired
private SearchQueueSender searchQueueSender;

@Autowired
private CommentDeleteService commentDeleteService;
private final SearchQueueSender searchQueueSender;
private final CommentDeleteService commentDeleteService;
private final IPBlockDao ipBlockDao;

public DelIPController(SearchQueueSender searchQueueSender, CommentDeleteService commentDeleteService,
IPBlockDao ipBlockDao) {
this.searchQueueSender = searchQueueSender;
this.commentDeleteService = commentDeleteService;
this.ipBlockDao = ipBlockDao;
}

/**
* Контроллер удаление топиков и сообщений по ip и времени
Expand All @@ -54,8 +59,9 @@ public class DelIPController {
@RequestMapping(value="/delip.jsp", method= RequestMethod.POST)
public ModelAndView delIp(@RequestParam("reason") String reason,
@RequestParam("ip") String ip,
@RequestParam("time") String time
) {
@RequestParam("time") String time,
@RequestParam(value = "ban_time", required = false) String banTime,
@RequestParam(value = "ban_mode", required = false) String banMode) {
Map<String, Object> params = new HashMap<>();

Template tmpl = Template.getTemplate();
Expand All @@ -64,18 +70,24 @@ public ModelAndView delIp(@RequestParam("reason") String reason,
throw new AccessViolationException("Not moderator");
}

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());

switch (time) {
case "hour" -> calendar.add(Calendar.HOUR_OF_DAY, -1);
case "day" -> calendar.add(Calendar.DAY_OF_MONTH, -1);
case "3day" -> calendar.add(Calendar.DAY_OF_MONTH, -3);
case "5day" -> calendar.add(Calendar.DAY_OF_MONTH, -5);
var delFrom = switch (time) {
case "hour" -> Instant.now().minus(1, ChronoUnit.HOURS);
case "day" -> Instant.now().minus(1, ChronoUnit.DAYS);
case "3day" -> Instant.now().minus(3, ChronoUnit.DAYS);
case "5day" ->Instant.now().minus(5, ChronoUnit.DAYS);
default -> throw new UserErrorException("Invalid count");
}

Timestamp ts = new Timestamp(calendar.getTimeInMillis());
};

Optional<OffsetDateTime> banTo = switch (banTime) {
case "hour" -> Optional.of(OffsetDateTime.now().plusHours(1));
case "day" -> Optional.of(OffsetDateTime.now().plusDays(1));
case "month" -> Optional.of(OffsetDateTime.now().plusMonths(1));
case "3month" -> Optional.of(OffsetDateTime.now().plusMonths(3));
case "6month" -> Optional.of(OffsetDateTime.now().plusMonths(6));
case null, default -> Optional.empty();
};

Timestamp ts = new Timestamp(delFrom.toEpochMilli());
params.put("message", "Удаляем темы и сообщения после "+ ts +" с IP "+ip+"<br>");

User moderator = AuthUtil.getCurrentUser();
Expand All @@ -85,6 +97,28 @@ public ModelAndView delIp(@RequestParam("reason") String reason,
params.put("topics", deleteResult.getDeletedTopicIds().size()); // кол-во удаленных топиков
params.put("deleted", deleteResult.getDeleteInfo());

if (banTo.isPresent()) {
boolean allowPosting, captchaRequired;

switch(banMode) {
case "anonymous_and_captcha" -> {
allowPosting = true;
captchaRequired = true;
}
case "anonymous_only" -> {
allowPosting = true;
captchaRequired = false;
}
default -> {
allowPosting = false;
captchaRequired = false;
}
}

ipBlockDao.blockIP(ip, moderator.getId(), reason,
banTo.map(v -> new Timestamp(v.toInstant().toEpochMilli())).get(), allowPosting, captchaRequired);
}

for (int topicId : deleteResult.getDeletedTopicIds()) {
searchQueueSender.updateMessage(topicId, true);
}
Expand Down
13 changes: 2 additions & 11 deletions src/main/java/ru/org/linux/user/User.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 1998-2022 Linux.org.ru
* Copyright 1998-2024 Linux.org.ru
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
Expand Down Expand Up @@ -157,15 +157,6 @@ public void checkFrozen(Errors errors) {
}
}

public void checkCommit() throws AccessViolationException {
if (anonymous || blocked) {
throw new AccessViolationException("Commit access denied for anonymous user");
}
if (!canmod) {
throw new AccessViolationException("Commit access denied for user " + nick + " (" + id + ") ");
}
}

public boolean isFrozen() {
if (frozenUntil == null) {
return false;
Expand Down Expand Up @@ -316,7 +307,7 @@ public String getStatus() {

if (maxScore>=100 && text.isEmpty()) {
return getStars(score, maxScore, true);
} else if (maxScore>=100 && !text.isEmpty()) {
} else if (maxScore>=100) {
return text + " " + getStars(score, maxScore, true);
} else {
return text;
Expand Down
65 changes: 45 additions & 20 deletions src/main/webapp/WEB-INF/jsp/sameip.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,51 @@
</c:forEach>
</div>

<c:if test="${ip != null and !hasMask and empty score and not empty comments}">
<fieldset>
<legend>Удалить темы и сообщения с IP</legend>
<form method="post" action="delip.jsp">
<lor:csrf/>
<input type="hidden" name="ip" value="${ip}">
по причине: <br>
<input type="text" name="reason" maxlength="254" size="40" value=""><br>
за последний(ие) <select name="time">
<option value="hour">1 час</option>
<option value="day">1 день</option>
<option value="3day">3 дня</option>
<option value="5day">5 дней</option>
</select>
<c:if test="${blockInfo == null || not blockInfo.blocked}">
и
<select name="ban_time" onchange="banTimeChange(this);">
<option value="remove">не блокировать</option>
<option value="hour">блокировать на 1 час</option>
<option value="day">блокировать на 1 день</option>
<option value="month">блокировать на 1 месяц</option>
<option value="3month">блокировать на 3 месяца</option>
<option value="6month">блокировать на 6 месяцев</option>
<option value="unlim">блокировать постоянно</option>
</select>
<label style="display: none" ><input checked type="radio" name="ban_mode" value="anonymous_and_captcha">только anonymous, требовать captcha у зарегистрированных</label>
<label style="display: none"><input type="radio" name="ban_mode" value="anonymous_only">только anonymous</label>
<label style="display: none"><input type="radio" name="ban_mode" value="all">всех</label>
</c:if>
<p>
<button type="submit" name="del" class="btn btn-danger">del from ip</button>

<script type="text/javascript">
function banTimeChange(object) {
if ($(object).val() == "remove") {
$(object).parent().find("input[name=ban_mode]").parent().hide();
} else {
$(object).parent().find("input[name=ban_mode]").parent().show();
}
}
</script>
</form>
</fieldset>
</c:if>

<c:if test="${not empty users}">
<h2>Пользователи за год (по топикам и комментариям)
<c:if test="${hasMoreUsers}">(показаны первые ${rowsLimit})</c:if>
Expand Down Expand Up @@ -309,25 +354,5 @@
</script>
</form>
</fieldset>

<c:if test="${empty score}">
<fieldset>
<legend>Удалить темы и сообщения с IP</legend>
<form method="post" action="delip.jsp">
<lor:csrf/>
<input type="hidden" name="ip" value="${ip}">
по причине: <br>
<input type="text" name="reason" maxlength="254" size="40" value=""><br>
за последний(ие) <select name="time" onchange="checkCustomDel(this.selectedIndex);">
<option value="hour">1 час</option>
<option value="day">1 день</option>
<option value="3day">3 дня</option>
<option value="5day">5 дней</option>
</select>
<p>
<button type="submit" name="del" class="btn btn-danger">del from ip</button>
</form>
</fieldset>
</c:if>
</c:if>
<jsp:include page="/WEB-INF/jsp/footer.jsp"/>
Loading

0 comments on commit 0067628

Please sign in to comment.