SecurityUtils.java 2.5 KB

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