security_util.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- coding: utf-8 -*-
  2. # @Author : YY
  3. import bcrypt
  4. from flask import abort
  5. from flask_login import current_user
  6. from ruoyi_common.constant import HttpStatus
  7. from ruoyi_common.domain.entity import LoginUser
  8. from ruoyi_common.utils.base import UtilException
  9. def get_user_id() -> int:
  10. """
  11. 获取当前登录用户的ID
  12. Raises:
  13. UtilException: 获取用户ID异常
  14. Returns:
  15. int: 当前登录用户的ID
  16. """
  17. try:
  18. return get_login_user().user_id
  19. except Exception:
  20. raise UtilException("获取用户ID异常", HttpStatus.UNAUTHORIZED)
  21. def get_dept_id() -> int:
  22. """
  23. 获取当前登录用户的部门ID
  24. Raises:
  25. UtilException: 获取部门ID异常
  26. Returns:
  27. int: 当前登录用户的部门ID
  28. """
  29. try:
  30. return get_login_user().dept_id
  31. except Exception:
  32. raise UtilException("获取部门ID异常", HttpStatus.UNAUTHORIZED)
  33. def get_username() -> str:
  34. """
  35. 获取当前登录用户的账户
  36. Raises:
  37. UtilException: 获取用户账户异常
  38. Returns:
  39. str: 当前登录用户的账户
  40. """
  41. try:
  42. return get_login_user().user_name
  43. except Exception as e:
  44. raise UtilException("获取用户账户异常", HttpStatus.UNAUTHORIZED)
  45. def get_login_user() -> LoginUser:
  46. """
  47. 获取当前登录用户的信息
  48. Raises:
  49. UtilException: 获取用户信息异常
  50. Returns:
  51. LoginUser: 当前登录用户的信息
  52. """
  53. try:
  54. # 检查是否有Flask-Login支持
  55. if hasattr(current_user, 'is_authenticated'):
  56. if not current_user.is_authenticated:
  57. abort(401)
  58. return current_user
  59. else:
  60. # 如果没有Flask-Login支持,返回None或抛出异常
  61. raise UtilException("获取用户信息异常", HttpStatus.UNAUTHORIZED)
  62. except Exception:
  63. raise UtilException("获取用户信息异常", HttpStatus.UNAUTHORIZED)
  64. def encrypt_password(password:str) -> str:
  65. """
  66. 加密密码
  67. Args:
  68. password (str): 原始密码
  69. Returns:
  70. str: 加密后的密码
  71. """
  72. salt = bcrypt.gensalt(rounds=10,prefix=b'2a')
  73. bcrypt_password = bcrypt.hashpw(password.encode('utf-8'), salt)
  74. return bcrypt_password
  75. def matches_password(raw_password:str, encoded_password:str) -> bool:
  76. """
  77. 验证密码是否匹配
  78. Args:
  79. raw_password (str): 原始密码
  80. encoded_password (str): 加密后的密码
  81. Returns:
  82. bool: 密码是否匹配
  83. """
  84. return bcrypt.checkpw(raw_password.encode('utf-8'), encoded_password.encode('utf-8'))
  85. def is_admin(user_id) -> bool:
  86. """
  87. 判断用户是否为管理员
  88. Args:
  89. user_id (int): 用户ID
  90. Returns:
  91. bool: 用户是否为管理员
  92. """
  93. return user_id is not None and user_id == 1
  94. def login_user_is_admin() -> bool:
  95. """
  96. 判断当前登录用户是否为管理员
  97. Returns:
  98. bool: 当前登录用户是否为管理员
  99. """
  100. return is_admin(get_user_id())