123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257 |
- package middlewares
- import (
- "errors"
- "fmt"
- "net/http"
- "sync"
- "xugu_license/internal/global"
- "xugu_license/internal/models"
- "github.com/gin-gonic/gin"
- )
- var Roles = map[string]Role{
- "admin": AdminRole,
- "supportRole": SupportRole,
- "guest": GuestRole,
- }
- type UserPermission struct {
- UserInfo models.UserInfo
- Role Role
- }
- // 定义权限类型
- type Permission string
- const (
- // License 相关权限
- GenerateLicense Permission = "generate_license" //生成license
- UploadLicense Permission = "upload_license" //上传license
- ReadLicense Permission = "read_license" //读取license
- ReadAllLicense Permission = "read_all_license" //读取所有license
- ReadlicenseRecord Permission = "read_license_record" //读取license
- UpdateLicense Permission = "update_license" //更新license
- DeleteLicense Permission = "delete_license" //删除license
- // 消息分发权限
- DispatLicense Permission = "dispat_license" //分发license
- // 主动抓取oaLicense到支撑库
- CaptureLicenseOnceToDb Permission = "capture_license_once_to_db" //主动抓取oaLicense到支撑库
- // 获得用户信息
- //GetUserInfo1 Permission = "get_user_info" //获得用户信息
- // 用户管理权限
- CreateUser Permission = "create_user" //创建用户
- ReadUser Permission = "read_user" //读取用户
- UpdateUser Permission = "update_user" //更新用户
- DeleteUser Permission = "delete_user" //删除用户
- //角色管理权限
- CreateRole Permission = "create_role" //创建角色
- DeleteRole Permission = "delete_role" //删除角色
- UpdateRole Permission = "update_role" //更新角色
- GetRole Permission = "get_role" //获得角色
- )
- // 定义映射
- var permissionMap = map[string]Permission{
- "generate_license": GenerateLicense,
- "upload_license": UploadLicense,
- "read_license": ReadLicense,
- "read_all_license": ReadAllLicense,
- "read_license_record": ReadlicenseRecord,
- "update_license": UpdateLicense,
- "delete_license": DeleteLicense,
- "dispat_license": DispatLicense,
- "capture_license_once_to_db": CaptureLicenseOnceToDb,
- //"get_user_info": GetUserInfo1,
- "create_user": CreateUser,
- "read_user": ReadUser,
- "update_user": UpdateUser,
- "delete_user": DeleteUser,
- "create_role": CreateRole,
- "delete_role": DeleteRole,
- "update_role": UpdateRole,
- "get_role": GetRole,
- }
- // MapBasedStringToPermission 使用 map 进行字符串到 Permission 的转换
- func MapBasedStringToPermission(permissionStr string) (Permission, error) {
- fmt.Println("permissionStr: ", permissionStr)
- if perm, exists := permissionMap[permissionStr]; exists {
- return perm, nil
- }
- return "", errors.New("invalid permission string")
- }
- // StringsToPermissions 将字符串数组转换为 Permission 数组
- func StringsToPermissions(permissionStrs []string) ([]Permission, error) {
- var permissions []Permission
- fmt.Println("permissionStrs: ", permissionStrs)
- for _, str := range permissionStrs {
- perm, err := MapBasedStringToPermission(str)
- if err != nil {
- return nil, err // 如果有任何一个字符串无效,返回错误
- }
- permissions = append(permissions, perm)
- }
- return permissions, nil
- }
- type Role struct {
- Id int
- Name string
- Permissions []Permission
- }
- var AdminRole = Role{
- Id: 0,
- Name: "admin",
- Permissions: []Permission{
- GenerateLicense,
- UploadLicense,
- ReadLicense,
- ReadAllLicense,
- UpdateLicense,
- DeleteLicense,
- DispatLicense,
- CaptureLicenseOnceToDb,
- //GetUserInfo1,
- ReadlicenseRecord,
- CreateUser,
- ReadUser,
- UpdateUser,
- DeleteUser,
- CreateRole,
- DeleteRole,
- UpdateRole,
- GetRole,
- },
- }
- var SupportRole = Role{
- Id: 0,
- Name: "support",
- Permissions: []Permission{
- ReadLicense,
- DispatLicense,
- //GetUserInfo1,
- GenerateLicense,
- ReadlicenseRecord,
- ReadUser,
- UpdateUser,
- DeleteUser,
- },
- }
- var GuestRole = Role{
- Id: 0,
- Name: "guest",
- Permissions: []Permission{
- ReadLicense,
- },
- }
- // RBAC 中间件
- func PermissionMiddleware(requiredPermission Permission) gin.HandlerFunc {
- return func(c *gin.Context) {
- userAny, exists := c.Get("userInfo")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
- c.Abort()
- return
- }
- userInfo := userAny.(*UserAuthInfo)
- uP := UserPermission{
- //UserInfo: *userInfo,
- Role: Role{
- Name: userInfo.Role,
- },
- }
- // switch userInfo.Role {
- // case "admin":
- // uP.Role = AdminRole
- // case "support":
- // uP.Role = SupportRole
- // case "guest":
- // uP.Role = GuestRole
- // default:
- // c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
- // c.Abort()
- // return
- // }
- // 检查用户是否具有所需的权限
- roleKey := userInfo.Role
- if role, exists := Roles[roleKey]; exists {
- // 如果存在,可以在这里使用 role 进行后续操作
- uP.Role = role
- } else {
- // 如果不存在,进行相应的处理
- global.Logger.Errorln("Role does not exist ")
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
- c.Abort()
- return
- }
- hasPermission := false
- for _, p := range uP.Role.Permissions {
- if p == requiredPermission {
- hasPermission = true
- break
- }
- }
- if !hasPermission {
- global.Logger.Errorln("没有权限 ")
- c.JSON(http.StatusForbidden, gin.H{"error": "没有权限"})
- c.Abort()
- return
- }
- c.Next()
- }
- }
- var mu sync.Mutex
- // 权限分配功能
- // func AssignRole(c *gin.Context) {
- // var req struct {
- // Username string `json:"username" binding:"required"`
- // Role string `json:"role" binding:"required"`
- // }
- // if err := c.ShouldBindJSON(&req); err != nil {
- // c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
- // return
- // }
- // mu.Lock()
- // defer mu.Unlock()
- // //从数据库里查询用户
- // user, exists := users[req.Username]
- // if exists {
- // switch req.Role {
- // case "admin":
- // user.Role = AdminRole
- // case "user":
- // user.Role = UserRole
- // case "guest":
- // user.Role = GuestRole
- // default:
- // c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
- // return
- // }
- // users[req.Username] = user
- // } else {
- // c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
- // return
- // }
- // c.JSON(http.StatusOK, gin.H{"message": "Role assigned successfully"})
- // }
|