SysPasswordService.java 2.6 KB

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