1
13693261870
2024-11-19 0bee2e75107b91cbe7bab8045319bb6709a3606f
1
已添加6个文件
443 ■■■■■ 文件已修改
se-modules/se-system/src/main/java/com/se/system/controller/TokenController.java 95 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-system/src/main/java/com/se/system/domain/LoginBody.java 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-system/src/main/java/com/se/system/domain/RegisterBody.java 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-system/src/main/java/com/se/system/service/SysLoginService.java 163 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-system/src/main/java/com/se/system/service/SysPasswordService.java 87 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-system/src/main/java/com/se/system/service/SysRecordLogService.java 48 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-system/src/main/java/com/se/system/controller/TokenController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,95 @@
package com.se.system.controller;
import com.se.common.core.domain.R;
import com.se.common.core.utils.AesUtils;
import com.se.common.core.utils.JwtUtils;
import com.se.common.core.utils.StringUtils;
import com.se.common.security.auth.AuthUtil;
import com.se.common.security.service.TokenService;
import com.se.common.security.utils.SecurityUtils;
import com.se.system.api.model.LoginUser;
import com.se.system.domain.LoginBody;
import com.se.system.service.SysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
 * token æŽ§åˆ¶
 *
 * @author admin
 */
@RestController
public class TokenController {
    @Resource
    private TokenService tokenService;
    @Autowired
    private SysLoginService sysLoginService;
    @Value("${enableEncrypt}")
    boolean enableEncrypt;
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) throws Exception {
        if (enableEncrypt && !StringUtils.isEmpty(form.getPassword())) {
            form.setPassword(AesUtils.decrypt(form.getPassword()));
        }
        // ç”¨æˆ·ç™»å½•
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // èŽ·å–ç™»å½•token
        return R.ok(tokenService.createToken(userInfo));
    }
    @GetMapping("validate")
    @PostMapping("validate")
    public R<Object> validate(HttpServletRequest request) {
        try {
            boolean flag = false;
            String token = SecurityUtils.getToken(request);
            if (!StringUtils.isNotEmpty(token)) {
                String userName = JwtUtils.getUserName(token);
                flag = !StringUtils.isEmpty(userName);
            }
            return R.ok(flag);
        } catch (Exception ex) {
            return R.fail(ex.getMessage());
        }
    }
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // åˆ é™¤ç”¨æˆ·ç¼“存记录
            AuthUtil.logoutByToken(token);
            // è®°å½•用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }
    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // åˆ·æ–°ä»¤ç‰Œæœ‰æ•ˆæœŸ
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
    /*@PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // ç”¨æˆ·æ³¨å†Œ
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }*/
}
se-modules/se-system/src/main/java/com/se/system/domain/LoginBody.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,39 @@
package com.se.system.domain;
/**
 * ç”¨æˆ·ç™»å½•对象
 *
 * @author admin
 */
public class LoginBody
{
    /**
     * ç”¨æˆ·å
     */
    private String username;
    /**
     * ç”¨æˆ·å¯†ç 
     */
    private String password;
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }
}
se-modules/se-system/src/main/java/com/se/system/domain/RegisterBody.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,11 @@
package com.se.system.domain;
/**
 * ç”¨æˆ·æ³¨å†Œå¯¹è±¡
 *
 * @author admin
 */
public class RegisterBody extends LoginBody
{
}
se-modules/se-system/src/main/java/com/se/system/service/SysLoginService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,163 @@
package com.se.system.service;
import com.se.common.core.constant.CacheConstants;
import com.se.common.core.constant.Constants;
import com.se.common.core.constant.SecurityConstants;
import com.se.common.core.constant.UserConstants;
import com.se.common.core.domain.R;
import com.se.common.core.enums.UserStatus;
import com.se.common.core.exception.ServiceException;
import com.se.common.core.text.Convert;
import com.se.common.core.utils.DateUtils;
import com.se.common.core.utils.StringUtils;
import com.se.common.core.utils.ip.IpUtils;
import com.se.common.redis.service.RedisService;
import com.se.common.security.utils.SecurityUtils;
import com.se.system.api.RemoteUserService;
import com.se.system.api.domain.SysUser;
import com.se.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
 * ç™»å½•校验方法
 *
 * @author admin
 */
@Component
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private SysRecordLogService recordLogService;
    @Resource
    private RedisService redisService;
    /**
     * ç™»å½•
     */
    public LoginUser login(String username, String password)
    {
        // ç”¨æˆ·åæˆ–密码为空 é”™è¯¯
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // å¯†ç å¦‚果不在指定范围内 é”™è¯¯
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // ç”¨æˆ·åä¸åœ¨æŒ‡å®šèŒƒå›´å†… é”™è¯¯
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾,访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾,访问IP已被列入系统黑名单");
        }
        // æŸ¥è¯¢ç”¨æˆ·ä¿¡æ¯
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户:" + username + " ä¸å­˜åœ¨");
        }
        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起,您的账号已被删除");
            throw new ServiceException("对不起,您的账号:" + username + " å·²è¢«åˆ é™¤");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用,请联系管理员");
            throw new ServiceException("对不起,您的账号:" + username + " å·²åœç”¨");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }
    /**
     * è®°å½•登录信息
     *
     * @param userId ç”¨æˆ·ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        // æ›´æ–°ç”¨æˆ·ç™»å½•IP
        sysUser.setLoginIp(IpUtils.getIpAddr());
        // æ›´æ–°ç”¨æˆ·ç™»å½•æ—¶é—´
        sysUser.setLoginDate(DateUtils.getNowDate());
        remoteUserService.recordUserLogin(sysUser, SecurityConstants.INNER);
    }
    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }
    /**
     * æ³¨å†Œ
     */
    public void register(String username, String password)
    {
        // ç”¨æˆ·åæˆ–密码为空 é”™è¯¯
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        // æ³¨å†Œç”¨æˆ·ä¿¡æ¯
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }
}
se-modules/se-system/src/main/java/com/se/system/service/SysPasswordService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,87 @@
package com.se.system.service;
import com.se.common.core.constant.CacheConstants;
import com.se.common.core.constant.Constants;
import com.se.common.core.exception.ServiceException;
import com.se.common.redis.service.RedisService;
import com.se.common.security.utils.SecurityUtils;
import com.se.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
 * ç™»å½•密码方法
 *
 * @author admin
 */
@Component
@SuppressWarnings("ALL")
public class SysPasswordService
{
    @Autowired
    private RedisService redisService;
    private int maxRetryCount = CacheConstants.PASSWORD_MAX_RETRY_COUNT;
    private Long lockTime = CacheConstants.PASSWORD_LOCK_TIME;
    @Autowired
    private SysRecordLogService recordLogService;
    /**
     * ç™»å½•账户密码错误次数缓存键名
     *
     * @param username ç”¨æˆ·å
     * @return ç¼“存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }
    public void validate(SysUser user, String password)
    {
        String username = user.getUserName();
        Integer retryCount = redisService.getCacheObject(getCacheKey(username));
        if (retryCount == null)
        {
            retryCount = 0;
        }
        /*if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            String errMsg = String.format("密码输入错误%s次,帐户锁定%s分钟", maxRetryCount, lockTime);
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL,errMsg);
            throw new ServiceException(errMsg);
        }*/
        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, String.format("密码输入错误%s次", retryCount));
            redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new ServiceException("用户不存在/密码错误");
        }
        else
        {
            clearLoginRecordCache(username);
        }
    }
    public boolean matches(SysUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }
    public void clearLoginRecordCache(String loginName)
    {
        if (redisService.hasKey(getCacheKey(loginName)))
        {
            redisService.deleteObject(getCacheKey(loginName));
        }
    }
}
se-modules/se-system/src/main/java/com/se/system/service/SysRecordLogService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,48 @@
package com.se.system.service;
import com.se.common.core.constant.Constants;
import com.se.common.core.constant.SecurityConstants;
import com.se.common.core.utils.StringUtils;
import com.se.common.core.utils.ip.IpUtils;
import com.se.system.api.RemoteLogService;
import com.se.system.api.domain.SysLogininfor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * è®°å½•日志方法
 *
 * @author admin
 */
@Component
public class SysRecordLogService
{
    @Autowired
    private RemoteLogService remoteLogService;
    /**
     * è®°å½•登录信息
     *
     * @param username ç”¨æˆ·å
     * @param status çŠ¶æ€
     * @param message æ¶ˆæ¯å†…容
     * @return
     */
    public void recordLogininfor(String username, String status, String message)
    {
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(IpUtils.getIpAddr());
        logininfor.setMsg(message);
        // æ—¥å¿—状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
        {
            logininfor.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        }
        else if (Constants.LOGIN_FAIL.equals(status))
        {
            logininfor.setStatus(Constants.LOGIN_FAIL_STATUS);
        }
        remoteLogService.saveLogininfor(logininfor, SecurityConstants.INNER);
    }
}