auth.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. //GetUserInfo1,
  126. GenerateLicense,
  127. ReadlicenseRecord,
  128. ReadUser,
  129. UpdateUser,
  130. DeleteUser,
  131. },
  132. }
  133. var GuestRole = Role{
  134. Id: 0,
  135. Name: "guest",
  136. Permissions: []Permission{
  137. ReadLicense,
  138. },
  139. }
  140. // RBAC 中间件
  141. func PermissionMiddleware(requiredPermission Permission) gin.HandlerFunc {
  142. return func(c *gin.Context) {
  143. userAny, exists := c.Get("userInfo")
  144. if !exists {
  145. c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
  146. c.Abort()
  147. return
  148. }
  149. userInfo := userAny.(*UserAuthInfo)
  150. uP := UserPermission{
  151. //UserInfo: *userInfo,
  152. Role: Role{
  153. Name: userInfo.Role,
  154. },
  155. }
  156. // switch userInfo.Role {
  157. // case "admin":
  158. // uP.Role = AdminRole
  159. // case "support":
  160. // uP.Role = SupportRole
  161. // case "guest":
  162. // uP.Role = GuestRole
  163. // default:
  164. // c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
  165. // c.Abort()
  166. // return
  167. // }
  168. // 检查用户是否具有所需的权限
  169. roleKey := userInfo.Role
  170. if role, exists := Roles[roleKey]; exists {
  171. // 如果存在,可以在这里使用 role 进行后续操作
  172. uP.Role = role
  173. } else {
  174. // 如果不存在,进行相应的处理
  175. global.Logger.Errorln("Role does not exist ")
  176. c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
  177. c.Abort()
  178. return
  179. }
  180. hasPermission := false
  181. for _, p := range uP.Role.Permissions {
  182. if p == requiredPermission {
  183. hasPermission = true
  184. break
  185. }
  186. }
  187. if !hasPermission {
  188. global.Logger.Errorln("没有权限 ")
  189. c.JSON(http.StatusForbidden, gin.H{"error": "没有权限"})
  190. c.Abort()
  191. return
  192. }
  193. c.Next()
  194. }
  195. }
  196. var mu sync.Mutex
  197. // 权限分配功能
  198. // func AssignRole(c *gin.Context) {
  199. // var req struct {
  200. // Username string `json:"username" binding:"required"`
  201. // Role string `json:"role" binding:"required"`
  202. // }
  203. // if err := c.ShouldBindJSON(&req); err != nil {
  204. // c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  205. // return
  206. // }
  207. // mu.Lock()
  208. // defer mu.Unlock()
  209. // //从数据库里查询用户
  210. // user, exists := users[req.Username]
  211. // if exists {
  212. // switch req.Role {
  213. // case "admin":
  214. // user.Role = AdminRole
  215. // case "user":
  216. // user.Role = UserRole
  217. // case "guest":
  218. // user.Role = GuestRole
  219. // default:
  220. // c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
  221. // return
  222. // }
  223. // users[req.Username] = user
  224. // } else {
  225. // c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
  226. // return
  227. // }
  228. // c.JSON(http.StatusOK, gin.H{"message": "Role assigned successfully"})
  229. // }