4 Commits

12 changed files with 413 additions and 4 deletions

View File

@@ -0,0 +1,51 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.pojo.dto.UserBanDTO;
import com.bao.dating.pojo.entity.UserBan;
import com.bao.dating.service.UserBanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 管理员控制器
* @author lenovo
*/
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private UserBanService userBanService;
/**
* 封禁用户
*/
@PostMapping("/{userId}/ban")
public Result<?> banUser(@PathVariable Long userId,
@RequestBody UserBanDTO userBanDTO) {
userBanDTO.setUserId(userId);
userBanService.banUser(userBanDTO);
return Result.success(ResultCode.SUCCESS, "封禁成功");
}
/**
* 解封用户
*/
@PostMapping("/{userId}/unban")
public Result<?> unbanUser(@PathVariable Long userId) {
userBanService.unbanUser(userId);
return Result.success(ResultCode.SUCCESS, "解封成功");
}
/**
* 查询封禁状态
*/
@GetMapping("/{userId}/banInfo")
public Result<UserBan> banInfo(@PathVariable Long userId) {
UserBan ban = userBanService.getActiveBan(userId);
return Result.success(ResultCode.SUCCESS, "查询成功", ban);
}
}

View File

@@ -44,10 +44,10 @@ public class TokenInterceptor implements HandlerInterceptor {
}
// 从 header 获取 token
String token = request.getHeader("token");
try {
log.info("jwt校验: {}", token);
// 验证 token 是否有效(包括是否过期)
if (!JwtUtil.validateToken(token)) {
log.error("Token无效或已过期");
@@ -66,10 +66,22 @@ public class TokenInterceptor implements HandlerInterceptor {
response.getWriter().write("登录已失效, 请重新登录");
return false;
}
// 解析 token
Long userId = Long.valueOf(JwtUtil.getSubjectFromToken(token));
// 检查用户是否被封禁
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
String reason = String.valueOf(redisTemplate.opsForValue().get(banKey));
log.error("用户 {} 已被封禁,原因:{}", userId, reason);
response.setStatus(403);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("账号已被封禁:" + reason);
return false;
}
// 从Redis获取存储的token进行比对
Object redisTokenObj = redisTemplate.opsForValue().get("login:token:" + userId);
String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;

View File

@@ -73,6 +73,14 @@ public class WsAuthInterceptor implements HandshakeInterceptor {
Long userId = Long.valueOf(userIdStr);
// 检查用户是否被封禁
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
String reason = String.valueOf(redisTemplate.opsForValue().get(banKey));
log.error("WebSocket拒绝用户 {} 被封禁,原因:{}", userId, reason);
return false;
}
// 从Redis获取存储的token进行比对
String redisTokenKey = "login:token:" + userId;
Object redisTokenObj = redisTemplate.opsForValue().get(redisTokenKey);

View File

@@ -0,0 +1,43 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.UserBan;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserBanMapper {
/**
* 新增封禁记录
* @param userBan 封禁记录
* @return 影响行数
*/
int insertBan(UserBan userBan);
/**
* 查询是否存在生效中的封禁
* @param userId 用户ID
* @return 存在返回1不存在返回0
*/
int existsActiveBan(@Param("userId") Long userId);
/**
* 查询生效中的封禁记录
* @param userId 用户ID
* @return 封禁记录
*/
UserBan selectActiveBan(@Param("userId") Long userId);
/**
* 解封用户
* @param userId 用户ID
* @return 影响行数
*/
int unbanUser(@Param("userId") Long userId);
/**
* 定时任务:过期自动解封
* @return 影响行数
*/
int updateExpiredBans();
}

View File

@@ -0,0 +1,13 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 用户封禁数据传输对象
* @author KilLze
*/
@Data
public class UserBanDTO {
private Long userId;
private String reason;
private Integer banDays;
}

View File

@@ -0,0 +1,30 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户封禁记录
* @author KilLze
*/
@Data
public class UserBan {
private Long id;
private Long userId;
private String reason;
private LocalDateTime banStartTime;
private LocalDateTime banEndTime;
/**
* 1:封禁中 0:已解封
*/
private Integer status;
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,31 @@
package com.bao.dating.service;
import com.bao.dating.pojo.dto.UserBanDTO;
import com.bao.dating.pojo.entity.UserBan;
/**
* 用户封禁服务接口
* @author KilLze
*/
public interface UserBanService {
/**
* 封禁用户
* @param userBanDTO 用户封禁信息
*
*/
void banUser(UserBanDTO userBanDTO);
/**
* 解封用户
* @param userId 用户ID
*/
void unbanUser(Long userId);
/**
* 查询封禁信息
* @param userId 用户ID
* @return 封禁信息
*/
UserBan getActiveBan(Long userId);
}

View File

@@ -0,0 +1,74 @@
package com.bao.dating.service.impl;
import com.bao.dating.mapper.UserBanMapper;
import com.bao.dating.pojo.dto.UserBanDTO;
import com.bao.dating.pojo.entity.UserBan;
import com.bao.dating.service.UserBanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
@Service
public class UserBanServiceImpl implements UserBanService {
@Autowired
private UserBanMapper userBanMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void banUser(UserBanDTO userBanDTO) {
// 已被封禁,直接拒绝
if (userBanMapper.existsActiveBan(userBanDTO.getUserId()) > 0) {
throw new RuntimeException("用户已处于封禁状态");
}
LocalDateTime now = LocalDateTime.now();
LocalDateTime endTime = userBanDTO.getBanDays() == null ? null : now.plusDays(userBanDTO.getBanDays());
// 1. 写数据库
UserBan ban = new UserBan();
ban.setUserId(userBanDTO.getUserId());
ban.setReason(userBanDTO.getReason());
ban.setBanStartTime(now);
ban.setBanEndTime(endTime);
ban.setStatus(1);
userBanMapper.insertBan(ban);
// 2. 写 Redis
String key = "user:ban:" + userBanDTO.getUserId();
if (userBanDTO.getBanDays() == null) {
redisTemplate.opsForValue().set(key, userBanDTO.getReason());
} else {
redisTemplate.opsForValue().set(key, userBanDTO.getReason(), userBanDTO.getBanDays(), TimeUnit.DAYS);
}
// 3. 踢下线
redisTemplate.delete("login:token:" + userBanDTO.getUserId());
}
/**
* 解封用户
*/
@Override
public void unbanUser(Long userId) {
// 更新数据库
userBanMapper.unbanUser(userId);
// 删除 Redis
redisTemplate.delete("user:ban:" + userId);
}
/**
* 获取用户封禁信息
*/
@Override
public UserBan getActiveBan(Long userId) {
return userBanMapper.selectActiveBan(userId);
}
}

View File

@@ -20,6 +20,7 @@ import com.bao.dating.util.CodeUtil;
import com.bao.dating.util.FileUtil;
import com.bao.dating.util.JwtUtil;
import com.bao.dating.util.MD5Util;
import com.bao.dating.util.UserBanUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -66,6 +67,9 @@ public class UserServiceImpl implements UserService {
@Autowired
private VerificationCodeService verificationCodeService;
@Autowired
private UserBanUtil userBanValidator;
/**
* 用户登录
*
@@ -92,6 +96,8 @@ public class UserServiceImpl implements UserService {
if (!match) {
throw new RuntimeException("密码错误");
}
// 用户封禁验证
userBanValidator.validateUserNotBanned(user.getUserId());
// 生成token
String token = JwtUtil.generateToken(String.valueOf(user.getUserId()));
@@ -485,4 +491,4 @@ public class UserServiceImpl implements UserService {
}
return result;
}
}
}

View File

@@ -0,0 +1,26 @@
package com.bao.dating.task;
import com.bao.dating.mapper.UserBanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@EnableScheduling
public class UserBanScheduleTask {
@Autowired
private UserBanMapper userBanMapper;
/**
* 每天凌晨 3 点同步过期封禁
*/
@Scheduled(cron = "0 0 3 * * ?")
public void syncExpiredUserBan() {
int rows = userBanMapper.updateExpiredBans();
log.info("封禁同步任务执行完成,解封 {} 个用户", rows);
}
}

View File

@@ -0,0 +1,65 @@
package com.bao.dating.util;
import com.bao.dating.context.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* 用户封禁验证工具类
* 提供统一的用户封禁状态检查功能
*
* @author KilLze
*/
@Component
public class UserBanUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 验证指定用户是否被封禁
*
* @param userId 用户ID
* @throws RuntimeException 如果用户被封禁则抛出异常
*/
public void validateUserNotBanned(Long userId) {
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
String reason = (String) redisTemplate.opsForValue().get(banKey);
// 获取剩余过期时间(秒)
Long ttlSeconds = redisTemplate.getExpire(banKey, TimeUnit.SECONDS);
String remainingTime = "";
if (ttlSeconds != null && ttlSeconds > 0) {
long days = ttlSeconds / (24 * 3600);
long hours = (ttlSeconds % (24 * 3600)) / 3600;
long minutes = (ttlSeconds % 3600) / 60;
if (days > 0) {
remainingTime = ",剩余时间:" + days + "" + hours + "小时";
} else if (hours > 0) {
remainingTime = ",剩余时间:" + hours + "小时" + minutes + "分钟";
} else {
remainingTime = ",剩余时间:" + minutes + "分钟";
}
} else {
remainingTime = ",永久封禁";
}
throw new RuntimeException("账号已被封禁,原因:" + reason + remainingTime);
}
}
/**
* 验证当前登录用户是否被封禁
*
* @throws RuntimeException 如果用户被封禁则抛出异常
*/
public void validateCurrentUserNotBanned() {
Long userId = UserContext.getUserId();
validateUserNotBanned(userId);
}
}

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.UserBanMapper">
<!-- 向数据库中添加用户封禁信息 -->
<insert id="insertBan" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user_ban
(user_id, reason, ban_start_time, ban_end_time, status)
VALUES
(#{userId}, #{reason}, #{banStartTime}, #{banEndTime}, #{status})
</insert>
<!-- 查询指定用户是否存在未过期的封禁信息 -->
<select id="existsActiveBan" resultType="int">
SELECT COUNT(1)
FROM user_ban
WHERE user_id = #{userId}
AND status = 1
LIMIT 1
</select>
<!-- 查询指定用户是否存在未过期的封禁信息 -->
<select id="selectActiveBan" resultType="com.bao.dating.pojo.entity.UserBan">
SELECT *
FROM user_ban
WHERE user_id = #{userId}
AND status = 1
LIMIT 1
</select>
<!-- 解封指定用户 -->
<update id="unbanUser">
UPDATE user_ban
SET status = 0
WHERE user_id = #{userId}
AND status = 1
</update>
<!-- 批量更新已过期的封禁信息 -->
<update id="updateExpiredBans">
UPDATE user_ban
SET status = 0
WHERE status = 1
AND ban_end_time IS NOT NULL
AND ban_end_time &lt; NOW()
</update>
</mapper>