security_util.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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 is_admin(user_id) -> bool:
  65. """
  66. 判断用户是否为管理员
  67. Args:
  68. user_id (int): 用户ID
  69. Returns:
  70. bool: 用户是否为管理员
  71. """
  72. return user_id is not None and user_id == 1
  73. def is_user_admin(user) -> bool:
  74. """
  75. 通过用户对象判断是否为管理员
  76. Args:
  77. user: 用户对象
  78. Returns:
  79. bool: 是否为管理员
  80. """
  81. # 检查是否为超级管理员用户
  82. if is_admin(user.user_id):
  83. return True
  84. # 检查用户角色中是否包含admin角色
  85. if hasattr(user, 'roles') and user.roles:
  86. for role in user.roles:
  87. if hasattr(role, 'role_key') and role.role_key == 'admin':
  88. return True
  89. return False
  90. def login_user_is_admin() -> bool:
  91. """
  92. 判断当前登录用户是否为管理员
  93. Returns:
  94. bool: 当前登录用户是否为管理员
  95. """
  96. try:
  97. user = get_login_user().user
  98. return is_user_admin(user)
  99. except:
  100. return is_admin(get_user_id())