SecurityUtils.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package com.ruoyi.common.utils;
  2. import cn.dev33.satoken.stp.StpUtil;
  3. import cn.hutool.http.HttpStatus;
  4. import com.ruoyi.common.core.domain.entity.SysUser;
  5. import com.ruoyi.common.core.service.IUserService;
  6. import com.ruoyi.common.exception.ServiceException;
  7. import com.ruoyi.common.utils.spring.SpringUtils;
  8. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  9. /**
  10. * 安全服务工具类
  11. *
  12. * @author ruoyi
  13. */
  14. public class SecurityUtils
  15. {
  16. /**
  17. * 用户ID
  18. **/
  19. public static Long getUserId()
  20. {
  21. return StpUtil.getLoginIdAsLong();
  22. }
  23. /**
  24. * 获取部门ID
  25. **/
  26. public static Long getDeptId()
  27. {
  28. try
  29. {
  30. return getUser().getDeptId();
  31. }
  32. catch (Exception e)
  33. {
  34. throw new ServiceException("获取部门ID异常", HttpStatus.HTTP_UNAUTHORIZED);
  35. }
  36. }
  37. /**
  38. * 获取用户账户
  39. **/
  40. public static String getUsername()
  41. {
  42. try
  43. {
  44. return getUser().getUserName();
  45. }
  46. catch (Exception e)
  47. {
  48. throw new ServiceException("获取用户账户异常", HttpStatus.HTTP_UNAUTHORIZED);
  49. }
  50. }
  51. /**
  52. * 获取用户
  53. **/
  54. public static SysUser getUser()
  55. {
  56. try
  57. {
  58. return SpringUtils.getBean(IUserService.class).selectUserById(getUserId());
  59. }
  60. catch (Exception e)
  61. {
  62. throw new ServiceException("获取用户信息异常", HttpStatus.HTTP_UNAUTHORIZED);
  63. }
  64. }
  65. /**
  66. * 生成BCryptPasswordEncoder密码
  67. *
  68. * @param password 密码
  69. * @return 加密字符串
  70. */
  71. public static String encryptPassword(String password)
  72. {
  73. BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  74. return passwordEncoder.encode(password);
  75. }
  76. /**
  77. * 判断密码是否相同
  78. *
  79. * @param rawPassword 真实密码
  80. * @param encodedPassword 加密后字符
  81. * @return 结果
  82. */
  83. public static boolean matchesPassword(String rawPassword, String encodedPassword)
  84. {
  85. BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  86. return passwordEncoder.matches(rawPassword, encodedPassword);
  87. }
  88. /**
  89. * 是否为管理员
  90. *
  91. * @param userId 用户ID
  92. * @return 结果
  93. */
  94. public static boolean isAdmin(Long userId)
  95. {
  96. return userId != null && 1L == userId;
  97. }
  98. }