SecurityUtils.java 2.8 KB

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