SysPasswordService.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package com.ruoyi.auth.service;
  2. import java.util.concurrent.TimeUnit;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Component;
  5. import com.ruoyi.common.core.constant.CacheConstants;
  6. import com.ruoyi.common.core.constant.Constants;
  7. import com.ruoyi.common.core.exception.ServiceException;
  8. import com.ruoyi.common.redis.service.RedisService;
  9. import com.ruoyi.common.security.utils.SecurityUtils;
  10. import com.ruoyi.system.api.domain.SysUser;
  11. /**
  12. * 登录密码方法
  13. *
  14. * @author ruoyi
  15. */
  16. @Component
  17. public class SysPasswordService
  18. {
  19. @Autowired
  20. private RedisService redisService;
  21. private int maxRetryCount = CacheConstants.passwordMaxRetryCount;
  22. private Long lockTime = CacheConstants.passwordLockTime;
  23. @Autowired
  24. private SysRecordLogService recordLogService;
  25. /**
  26. * 登录账户密码错误次数缓存键名
  27. *
  28. * @param username 用户名
  29. * @return 缓存键key
  30. */
  31. private String getCacheKey(String username)
  32. {
  33. return CacheConstants.PWD_ERR_CNT_KEY + username;
  34. }
  35. public void validate(SysUser user, String password)
  36. {
  37. String username = user.getUserName();
  38. Integer retryCount = redisService.getCacheObject(getCacheKey(username));
  39. if (retryCount == null)
  40. {
  41. retryCount = 0;
  42. }
  43. if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
  44. {
  45. String errMsg = String.format("密码输入错误%s次,帐户锁定%s分钟", maxRetryCount, lockTime);
  46. recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL,errMsg);
  47. throw new ServiceException(errMsg);
  48. }
  49. if (!matches(user, password))
  50. {
  51. retryCount = retryCount + 1;
  52. recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, String.format("密码输入错误%s次", retryCount));
  53. redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
  54. throw new ServiceException("用户不存在/密码错误");
  55. }
  56. else
  57. {
  58. clearLoginRecordCache(username);
  59. }
  60. }
  61. public boolean matches(SysUser user, String rawPassword)
  62. {
  63. return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
  64. }
  65. public void clearLoginRecordCache(String loginName)
  66. {
  67. if (redisService.hasKey(getCacheKey(loginName)))
  68. {
  69. redisService.deleteObject(getCacheKey(loginName));
  70. }
  71. }
  72. }