auth.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package middlewares
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "sync"
  7. "xugu_license/internal/global"
  8. "xugu_license/internal/models"
  9. "github.com/gin-gonic/gin"
  10. )
  11. var Roles = map[string]Role{
  12. "admin": AdminRole,
  13. "supportRole": SupportRole,
  14. "guest": GuestRole,
  15. }
  16. type UserPermission struct {
  17. UserInfo models.UserInfo
  18. Role Role
  19. }
  20. // 定义权限类型
  21. type Permission string
  22. const (
  23. // License 相关权限
  24. GenerateLicense Permission = "generate_license" //生成license
  25. UploadLicense Permission = "upload_license" //上传license
  26. ReadLicense Permission = "read_license" //读取license
  27. ReadAllLicense Permission = "read_all_license" //读取所有license
  28. ReadlicenseRecord Permission = "read_license_record" //读取license
  29. UpdateLicense Permission = "update_license" //更新license
  30. DeleteLicense Permission = "delete_license" //删除license
  31. // 消息分发权限
  32. DispatLicense Permission = "dispat_license" //分发license
  33. // 主动抓取oaLicense到支撑库
  34. CaptureLicenseOnceToDb Permission = "capture_license_once_to_db" //主动抓取oaLicense到支撑库
  35. // 获得用户信息
  36. //GetUserInfo1 Permission = "get_user_info" //获得用户信息
  37. // 用户管理权限
  38. CreateUser Permission = "create_user" //创建用户
  39. ReadUser Permission = "read_user" //读取用户
  40. UpdateUser Permission = "update_user" //更新用户
  41. DeleteUser Permission = "delete_user" //删除用户
  42. //角色管理权限
  43. CreateRole Permission = "create_role" //创建角色
  44. DeleteRole Permission = "delete_role" //删除角色
  45. UpdateRole Permission = "update_role" //更新角色
  46. GetRole Permission = "get_role" //获得角色
  47. )
  48. // 定义映射
  49. var permissionMap = map[string]Permission{
  50. "generate_license": GenerateLicense,
  51. "upload_license": UploadLicense,
  52. "read_license": ReadLicense,
  53. "read_all_license": ReadAllLicense,
  54. "read_license_record": ReadlicenseRecord,
  55. "update_license": UpdateLicense,
  56. "delete_license": DeleteLicense,
  57. "dispat_license": DispatLicense,
  58. "capture_license_once_to_db": CaptureLicenseOnceToDb,
  59. //"get_user_info": GetUserInfo1,
  60. "create_user": CreateUser,
  61. "read_user": ReadUser,
  62. "update_user": UpdateUser,
  63. "delete_user": DeleteUser,
  64. "create_role": CreateRole,
  65. "delete_role": DeleteRole,
  66. "update_role": UpdateRole,
  67. "get_role": GetRole,
  68. }
  69. // MapBasedStringToPermission 使用 map 进行字符串到 Permission 的转换
  70. func MapBasedStringToPermission(permissionStr string) (Permission, error) {
  71. fmt.Println("permissionStr: ", permissionStr)
  72. if perm, exists := permissionMap[permissionStr]; exists {
  73. return perm, nil
  74. }
  75. return "", errors.New("invalid permission string")
  76. }
  77. // StringsToPermissions 将字符串数组转换为 Permission 数组
  78. func StringsToPermissions(permissionStrs []string) ([]Permission, error) {
  79. var permissions []Permission
  80. fmt.Println("permissionStrs: ", permissionStrs)
  81. for _, str := range permissionStrs {
  82. perm, err := MapBasedStringToPermission(str)
  83. if err != nil {
  84. return nil, err // 如果有任何一个字符串无效,返回错误
  85. }
  86. permissions = append(permissions, perm)
  87. }
  88. return permissions, nil
  89. }
  90. type Role struct {
  91. Id int
  92. Name string
  93. Permissions []Permission
  94. }
  95. var AdminRole = Role{
  96. Id: 0,
  97. Name: "admin",
  98. Permissions: []Permission{
  99. GenerateLicense,
  100. UploadLicense,
  101. ReadLicense,
  102. ReadAllLicense,
  103. UpdateLicense,
  104. DeleteLicense,
  105. DispatLicense,
  106. CaptureLicenseOnceToDb,
  107. //GetUserInfo1,
  108. ReadlicenseRecord,
  109. CreateUser,
  110. ReadUser,
  111. UpdateUser,
  112. DeleteUser,
  113. CreateRole,
  114. DeleteRole,
  115. UpdateRole,
  116. GetRole,
  117. },
  118. }
  119. var SupportRole = Role{
  120. Id: 0,
  121. Name: "support",
  122. Permissions: []Permission{
  123. ReadLicense,
  124. DispatLicense,
  125. ReadLicense,
  126. //GetUserInfo1,
  127. ReadlicenseRecord,
  128. ReadUser,
  129. UpdateUser,
  130. DeleteUser,
  131. CreateRole,
  132. UploadLicense,
  133. },
  134. }
  135. var GuestRole = Role{
  136. Id: 0,
  137. Name: "guest",
  138. Permissions: []Permission{
  139. ReadLicense,
  140. },
  141. }
  142. // RBAC 中间件
  143. func PermissionMiddleware(requiredPermission Permission) gin.HandlerFunc {
  144. return func(c *gin.Context) {
  145. userAny, exists := c.Get("userInfo")
  146. if !exists {
  147. c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
  148. c.Abort()
  149. return
  150. }
  151. userInfo := userAny.(*UserAuthInfo)
  152. uP := UserPermission{
  153. //UserInfo: *userInfo,
  154. Role: Role{
  155. Name: userInfo.Role,
  156. },
  157. }
  158. // switch userInfo.Role {
  159. // case "admin":
  160. // uP.Role = AdminRole
  161. // case "support":
  162. // uP.Role = SupportRole
  163. // case "guest":
  164. // uP.Role = GuestRole
  165. // default:
  166. // c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
  167. // c.Abort()
  168. // return
  169. // }
  170. // 检查用户是否具有所需的权限
  171. roleKey := userInfo.Role
  172. if role, exists := Roles[roleKey]; exists {
  173. // 如果存在,可以在这里使用 role 进行后续操作
  174. uP.Role = role
  175. } else {
  176. // 如果不存在,进行相应的处理
  177. global.Logger.Errorln("Role does not exist ")
  178. c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
  179. c.Abort()
  180. return
  181. }
  182. hasPermission := false
  183. for _, p := range uP.Role.Permissions {
  184. if p == requiredPermission {
  185. hasPermission = true
  186. break
  187. }
  188. }
  189. if !hasPermission {
  190. global.Logger.Errorln("没有权限 ")
  191. c.JSON(http.StatusForbidden, gin.H{"error": "没有权限"})
  192. c.Abort()
  193. return
  194. }
  195. c.Next()
  196. }
  197. }
  198. var mu sync.Mutex
  199. // 权限分配功能
  200. // func AssignRole(c *gin.Context) {
  201. // var req struct {
  202. // Username string `json:"username" binding:"required"`
  203. // Role string `json:"role" binding:"required"`
  204. // }
  205. // if err := c.ShouldBindJSON(&req); err != nil {
  206. // c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  207. // return
  208. // }
  209. // mu.Lock()
  210. // defer mu.Unlock()
  211. // //从数据库里查询用户
  212. // user, exists := users[req.Username]
  213. // if exists {
  214. // switch req.Role {
  215. // case "admin":
  216. // user.Role = AdminRole
  217. // case "user":
  218. // user.Role = UserRole
  219. // case "guest":
  220. // user.Role = GuestRole
  221. // default:
  222. // c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
  223. // return
  224. // }
  225. // users[req.Username] = user
  226. // } else {
  227. // c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
  228. // return
  229. // }
  230. // c.JSON(http.StatusOK, gin.H{"message": "Role assigned successfully"})
  231. // }