Repository: dragonflyoss/Dragonfly2
Pull request #552 (2021-08-15 09:44:36)

change rabc code struct
Signed-off-by: yxxhero <aiopsclub@163.com>

<!--- Provide a general summary of your changes in the Title above -->

## Description

<!--- Describe your changes in detail -->

## Related Issue
https://github.com/dragonflyoss/Dragonfly2/issues/546
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->

## Motivation and Context

<!--- Why is this change required? What problem does it solve? -->

## Screenshots (if appropriate):

## Types of changes

<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [x] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation Update (if none of the other choices apply)

## Checklist:

<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->

- [x] Code compiles correctly.
- [x] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [x] I have read the **CONTRIBUTING** document.
- [x] I have added tests to cover my changes.
- [x] All new and existing tests passed.


codecov-commenter: # [Codecov](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss) Report
> Merging [#552](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss) (fe0c890) into [main](https://codecov.io/gh/dragonflyoss/Dragonfly2/commit/5286be03ccf5dcf1b7ec3708e6a510c5cd628665?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss) (5286be0) will **decrease** coverage by `0.10%`.
> The diff coverage is `12.50%`.

[![Impacted file tree graph](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552/graphs/tree.svg?width=650&height=150&src=pr&token=PUICJYSAT7&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss)](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss)

```diff
@@            Coverage Diff             @@
##             main     #552      +/-   ##
==========================================
- Coverage   39.47%   39.36%   -0.11%     
==========================================
  Files          86       86              
  Lines        6559     6562       +3     
==========================================
- Hits         2589     2583       -6     
- Misses       3599     3609      +10     
+ Partials      371      370       -1     
```

| Flag | Coverage Δ | |
|---|---|---|
| e2etests | `?` | |
| unittests | `39.36% <12.50%> (-0.11%)` | :arrow_down: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss) | Coverage Δ | |
|---|---|---|
| [manager/permission/rbac/rbac.go](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss#diff-bWFuYWdlci9wZXJtaXNzaW9uL3JiYWMvcmJhYy5nbw==) | `28.30% <12.50%> (-11.33%)` | :arrow_down: |
| [client/daemon/peer/peertask\_stream.go](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss#diff-Y2xpZW50L2RhZW1vbi9wZWVyL3BlZXJ0YXNrX3N0cmVhbS5nbw==) | `56.79% <0.00%> (-0.70%)` | :arrow_down: |
| [client/daemon/peer/peertask\_file.go](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss#diff-Y2xpZW50L2RhZW1vbi9wZWVyL3BlZXJ0YXNrX2ZpbGUuZ28=) | `54.05% <0.00%> (-0.39%)` | :arrow_down: |
| [cdnsystem/daemon/cdn/cache\_writer.go](https://codecov.io/gh/dragonflyoss/Dragonfly2/pull/552/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=dragonflyoss#diff-Y2Ruc3lzdGVtL2RhZW1vbi9jZG4vY2FjaGVfd3JpdGVyLmdv) | `79.20% <0.00%> (+0.63%)` | :arrow_up: |


Patch:
diff --git a/manager/handlers/permission.go b/manager/handlers/permission.go
index 08df9a2e..d65a9ee8 100644
--- a/manager/handlers/permission.go
+++ b/manager/handlers/permission.go
@@ -23,92 +23,101 @@ import (
 	"github.com/gin-gonic/gin"
 )
 
-// @Summary Get PermissionGroups
-// @Description Get PermissionGroups
+// @Summary Get Permissions
+// @Description Get Permissions
 // @Tags permission
 // @Produce json
-// @Success 200 {object} types.PermissionGroups
-// @Failure 400
-// @Failure 500
-// @Router /permission/groups [get]
+// @Success 200 {object} RoutesInfo
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /permissions [get]
 
-func (h *Handlers) GetPermissionGroups(g *gin.Engine) func(ctx *gin.Context) {
+func (h *Handlers) GetPermissions(g *gin.Engine) func(ctx *gin.Context) {
 	return func(ctx *gin.Context) {
 
-		permissionGroups := h.Service.GetPermissionGroups(g)
+		permissionGroups := h.Service.GetPermissions(g)
 
 		ctx.JSON(http.StatusOK, permissionGroups)
 	}
 }
 
-// @Summary Get User Roles
-// @Description Get User Roles
-// @Tags permission
+// @Summary Create Role
+// @Description Create Role by json config
+// @Tags role
+// @Accept json
 // @Produce json
-// @Success 200 {object} []map[string]string
-// @Failure 400
-// @Failure 500
-// @Router /permission/roles/{subject} [get]
+// @Success 200
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /roles [post]
 
-func (h *Handlers) GetRolesForUser(ctx *gin.Context) {
-	var params types.UserRolesParams
-	if err := ctx.ShouldBindUri(&params); err != nil {
+func (h *Handlers) CreateRole(ctx *gin.Context) {
+	var json types.CreateRolePermissionRequest
+	if err := ctx.ShouldBindJSON(&json); err != nil {
 		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
 		return
 	}
-	roles, err := h.Service.GetRolesForUser(params.Subject)
+	err := h.Service.CreateRole(json)
 	if err != nil {
 		ctx.Error(err)
 		return
 	}
-	ctx.JSON(http.StatusOK, gin.H{"roles": roles})
-
+	ctx.Status(http.StatusOK)
 }
 
-// @Summary Judge User Role
-// @Description Judge User Role
-// @Tags permission
+// @Summary Update Role
+// @Description Remove Role Permission by json config
+// @Tags role
+// @Accept json
 // @Produce json
-// @Success 200 {object}
-// @Failure 400
-// @Failure 500
-// @Router /permission/{subject}/{object}/{action} [get]
+// @Success 200
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /roles/:role_name/permission [delete]
 
-func (h *Handlers) HasRoleForUser(ctx *gin.Context) {
-	var params types.UserHasRoleParams
+func (h *Handlers) RemoveRolePermission(ctx *gin.Context) {
+
+	var params types.RoleParams
 	if err := ctx.ShouldBindUri(&params); err != nil {
 		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
 		return
 	}
-	if params.Subject == "admin" {
-		ctx.JSON(http.StatusOK, gin.H{"has": true})
+	var json types.ObjectPermission
+	if err := ctx.ShouldBindJSON(&json); err != nil {
+		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
 		return
 	}
-	has, err := h.Service.HasRoleForUser(params.Subject, params.Object, params.Action)
+	err := h.Service.RemoveRolePermission(params.RoleName, json)
 	if err != nil {
 		ctx.Error(err)
 		return
 	}
-	ctx.JSON(http.StatusOK, gin.H{"has": has})
+	ctx.Status(http.StatusOK)
 }
 
-// @Summary Create Permission
-// @Description Create Permission by json config
-// @Tags permission
+// @Summary Update Role
+// @Description Add Role Permission by json config
+// @Tags role
 // @Accept json
 // @Produce json
 // @Success 200
-// @Failure 400
-// @Failure 500
-// @Router /permission [post]
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /roles/:role_name/permission [post]
 
-func (h *Handlers) CreatePermission(ctx *gin.Context) {
-	var json types.PolicyRequest
+func (h *Handlers) AddRolePermission(ctx *gin.Context) {
+
+	var params types.RoleParams
+	if err := ctx.ShouldBindUri(&params); err != nil {
+		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
+		return
+	}
+	var json types.ObjectPermission
 	if err := ctx.ShouldBindJSON(&json); err != nil {
 		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
 		return
 	}
-	err := h.Service.CreatePermission(json)
+	err := h.Service.AddRolePermission(params.RoleName, json)
 	if err != nil {
 		ctx.Error(err)
 		return
@@ -116,23 +125,57 @@ func (h *Handlers) CreatePermission(ctx *gin.Context) {
 	ctx.Status(http.StatusOK)
 }
 
+// @Summary Get Roles
+// @Description Get Roles by name
+// @Tags role
+// @Accept text
+// @Produce json
+// @Success 200
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /roles [get]
+
+func (h *Handlers) GetRoles(ctx *gin.Context) {
+	roles := h.Service.GetRoles()
+	ctx.JSON(http.StatusOK, roles)
+}
+
+// @Summary Get Role
+// @Description Get Role
+// @Tags permission
+// @Accept text
+// @Produce json
+// @Success 200
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /roles/:role_name [get]
+
+func (h *Handlers) GetRole(ctx *gin.Context) {
+	var params types.RoleParams
+	if err := ctx.ShouldBindUri(&params); err != nil {
+		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
+		return
+	}
+	ctx.JSON(http.StatusOK, h.Service.GetRole(params.RoleName))
+}
+
 // @Summary Destroy Permission
 // @Description Destroy Permission by json config
 // @Tags permission
 // @Accept json
 // @Produce json
 // @Success 200
-// @Failure 400
-// @Failure 500
-// @Router /permission [delete]
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /role/:role_name [delete]
 
-func (h *Handlers) DestroyPermission(ctx *gin.Context) {
-	var json types.PolicyRequest
-	if err := ctx.ShouldBindJSON(&json); err != nil {
+func (h *Handlers) DestroyRole(ctx *gin.Context) {
+	var params types.RoleParams
+	if err := ctx.ShouldBindUri(&params); err != nil {
 		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
 		return
 	}
-	err := h.Service.DestroyPermission(json)
+	err := h.Service.DestroyRole(params.RoleName)
 	if err != nil {
 		ctx.Error(err)
 		return
diff --git a/manager/handlers/user.go b/manager/handlers/user.go
index 2fd638a7..a36076af 100644
--- a/manager/handlers/user.go
+++ b/manager/handlers/user.go
@@ -48,3 +48,75 @@ func (h *Handlers) SignUp(ctx *gin.Context) {
 
 	ctx.JSON(http.StatusOK, user)
 }
+
+// @Summary Delete Role For User
+// @Description Delete Role For User by uri config
+// @Tags users
+// @Accept text
+// @Produce json
+// @Success 200
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /users/:id/roles/:role_name [delete]
+
+func (h *Handlers) DeleteRoleForUser(ctx *gin.Context) {
+	var params types.RoleRequest
+	if err := ctx.ShouldBindUri(&params); err != nil {
+		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
+		return
+	}
+	err := h.Service.DeleteRoleForUser(params.ID, params.RoleName)
+	if err != nil {
+		ctx.Error(err)
+		return
+	}
+	ctx.Status(http.StatusOK)
+}
+
+// @Summary Add Role For User
+// @Description Add Role For User by uri config
+// @Tags users
+// @Accept text
+// @Produce json
+// @Success 200
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /users/:id/roles/:role_name [post]
+
+func (h *Handlers) AddRoleToUser(ctx *gin.Context) {
+	var params types.RoleRequest
+	if err := ctx.ShouldBindUri(&params); err != nil {
+		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
+		return
+	}
+	err := h.Service.AddRoleForUser(params.ID, params.RoleName)
+	if err != nil {
+		ctx.Error(err)
+		return
+	}
+	ctx.Status(http.StatusOK)
+}
+
+// @Summary Get User Roles
+// @Description Get User Roles
+// @Tags User
+// @Produce json
+// @Success 200 {object} RoutesInfo
+// @Failure 400 {object} HTTPError
+// @Failure 500 {object} HTTPError
+// @Router /users/:id/roles [get]
+
+func (h *Handlers) GetRolesForUser(ctx *gin.Context) {
+	var params types.UserParams
+	if err := ctx.ShouldBindUri(&params); err != nil {
+		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"errors": err.Error()})
+		return
+	}
+	roles, err := h.Service.GetRolesForUser(params.ID, ctx.GetString("userName"))
+	if err != nil {
+		ctx.Error(err)
+		return
+	}
+	ctx.JSON(http.StatusOK, roles)
+
+}
diff --git a/manager/manager.go b/manager/manager.go
index 3fd8fb25..8144e7c8 100644
--- a/manager/manager.go
+++ b/manager/manager.go
@@ -83,6 +83,12 @@ func New(cfg *config.Config) (*Server, error) {
 	if err != nil {
 		return nil, err
 	}
+
+	// Initialize roles and check roles
+	err = rbac.InitRole(enforcer, router)
+	if err != nil {
+		return nil, err
+	}
 	restServer := &http.Server{
 		Addr:    cfg.Server.REST.Addr,
 		Handler: router,
diff --git a/manager/middlewares/jwt.go b/manager/middlewares/jwt.go
index dd2a8cad..3a756e77 100644
--- a/manager/middlewares/jwt.go
+++ b/manager/middlewares/jwt.go
@@ -29,6 +29,7 @@ import (
 
 type user struct {
 	userName string
+	ID       uint
 }
 
 func Jwt(service service.REST) (*jwt.GinJWTMiddleware, error) {
@@ -42,7 +43,7 @@ func Jwt(service service.REST) (*jwt.GinJWTMiddleware, error) {
 
 		IdentityHandler: func(c *gin.Context) interface{} {
 			claims := jwt.ExtractClaims(c)
-			userNmae, ok := claims[identityKey]
+			userName, ok := claims[identityKey]
 			if !ok {
 				c.JSON(http.StatusUnauthorized, gin.H{
 					"message": "Unavailable token: require username info",
@@ -50,10 +51,20 @@ func Jwt(service service.REST) (*jwt.GinJWTMiddleware, error) {
 				c.Abort()
 				return nil
 			}
+			userID, ok := claims["ID"]
+			if !ok {
+				c.JSON(http.StatusUnauthorized, gin.H{
+					"message": "Unavailable token: require id info",
+				})
+				c.Abort()
+				return nil
+			}
 			u := &user{
-				userName: userNmae.(string),
+				userName: userName.(string),
+				ID:       uint(userID.(float64)),
 			}
 			c.Set("userName", u.userName)
+			c.Set("userID", u.ID)
 			return u
 		},
 
@@ -75,6 +86,7 @@ func Jwt(service service.REST) (*jwt.GinJWTMiddleware, error) {
 			if u, ok := data.(*model.User); ok {
 				return jwt.MapClaims{
 					identityKey: u.Name,
+					"ID":        u.ID,
 				}
 			}
 			return jwt.MapClaims{}
diff --git a/manager/middlewares/rbac.go b/manager/middlewares/rbac.go
index 4870ba6f..5c47bbc0 100644
--- a/manager/middlewares/rbac.go
+++ b/manager/middlewares/rbac.go
@@ -19,6 +19,7 @@ package middlewares
 import (
 	"net/http"
 
+	logger "d7y.io/dragonfly/v2/internal/dflog"
 	"d7y.io/dragonfly/v2/manager/permission/rbac"
 	"github.com/casbin/casbin/v2"
 	"github.com/gin-gonic/gin"
@@ -29,7 +30,7 @@ func RBAC(e *casbin.Enforcer) gin.HandlerFunc {
 		userName := c.GetString("userName")
 		// request path
 		p := c.Request.URL.Path
-		permissionGroupName, err := rbac.GetAPIGroupName(p)
+		permissionName, err := rbac.GetAPIGroupName(p)
 		if err != nil {
 			c.Next()
 			return
@@ -50,10 +51,18 @@ func RBAC(e *casbin.Enforcer) gin.HandlerFunc {
 			c.Next()
 			return
 		}
-		res, err := e.Enforce(userName, permissionGroupName, action)
-		if err != nil || !res {
+		res, err := e.Enforce(userName, permissionName, action)
+		if err != nil {
+			logger.Errorf("RBAC validate error: %s", err)
 			c.JSON(http.StatusUnauthorized, gin.H{
-				"message": "permission validate error",
+				"message": "permission validate error, please see log!",
+			})
+			c.Abort()
+			return
+		}
+		if !res {
+			c.JSON(http.StatusUnauthorized, gin.H{
+				"message": "permission deny",
 			})
 			c.Abort()
 			return
diff --git a/manager/permission/rbac/rbac.go b/manager/permission/rbac/rbac.go
index c7d1628d..a7b47a28 100644
--- a/manager/permission/rbac/rbac.go
+++ b/manager/permission/rbac/rbac.go
@@ -18,6 +18,7 @@ package rbac
 
 import (
 	"errors"
+	"fmt"
 	"net/http"
 	"regexp"
 	"strings"
@@ -47,7 +48,7 @@ g = _, _
 e = some(where (p.eft == allow))
 
 [matchers]
-m = g(r.sub, p.sub) && r.obj == p.obj && (r.act == p.act || p.act == "*") || r.sub == "admin"
+m = g(r.sub, p.sub) && r.obj == p.obj && (r.act == p.act || p.act == "*")
 `
 
 func NewEnforcer(gdb *gorm.DB) (*casbin.Enforcer, error) {
@@ -69,12 +70,22 @@ func NewEnforcer(gdb *gorm.DB) (*casbin.Enforcer, error) {
 func InitRole(e *casbin.Enforcer, g *gin.Engine) error {
 	systemRoles := SystemRoles(g)
 
+	var err error
 	for _, role := range systemRoles {
 		roleInfo := strings.Split(role, ":")
-		_, err := e.AddPolicy(role, roleInfo[0], roleInfo[1])
+		_, err = e.AddPolicy(role, roleInfo[0], roleInfo[1])
 		if err != nil {
 			return err
 		}
+
+		// init admin permissions
+		_, err = e.AddPolicy("admin", roleInfo[0], "*")
+		if err != nil {
+			return err
+		}
+	}
+	if _, err := e.AddRoleForUser("admin", "admin"); err != nil {
+		return err
 	}
 	logger.Info("init and check role success")
 	return nil
@@ -95,14 +106,7 @@ func RoleName(object, action string) string {
 	if object == "admin" {
 		return "admin"
 	}
-	roleName := ""
-	switch action {
-	case "read":
-		roleName = object + ":" + "read"
-	case "write":
-		roleName = object + ":" + "*"
-	}
-	return roleName
+	return fmt.Sprintf("%s:%s", object, action)
 }
 
 func GetAPIGroupNames(g *gin.Engine) []string {
diff --git a/manager/router/router.go b/manager/router/router.go
index 53c2ea7d..39f62d52 100644
--- a/manager/router/router.go
+++ b/manager/router/router.go
@@ -19,7 +19,6 @@ package router
 import (
 	"d7y.io/dragonfly/v2/manager/handlers"
 	"d7y.io/dragonfly/v2/manager/middlewares"
-	rbacbase "d7y.io/dragonfly/v2/manager/permission/rbac"
 	"d7y.io/dragonfly/v2/manager/service"
 	"github.com/casbin/casbin/v2"
 	"github.com/gin-contrib/static"
@@ -61,7 +60,9 @@ func Init(verbose bool, publicPath string, service service.REST, enforcer *casbi
 	ai.POST("/signin", jwt.LoginHandler)
 	ai.POST("/signout", jwt.LogoutHandler)
 	ai.POST("/refresh_token", jwt.RefreshHandler)
-	ai.POST("/signup", jwt.MiddlewareFunc(), rbac, h.SignUp)
+	ai.POST("/:id/roles/:role_name", h.AddRoleToUser)
+	ai.DELETE("/:id/roles/:role_name", h.DeleteRoleForUser)
+	ai.POST("/signup", h.SignUp)
 
 	// Scheduler Cluster
 	sc := apiv1.Group("/scheduler-clusters")
@@ -98,13 +99,18 @@ func Init(verbose bool, publicPath string, service service.REST, enforcer *casbi
 	c.GET(":id", h.GetCDN)
 	c.GET("", h.GetCDNs)
 
+	// roles
+	re := apiv1.Group("/roles", jwt.MiddlewareFunc(), rbac)
+	re.POST("", h.CreateRole)
+	re.GET("", h.GetRoles)
+	re.DELETE("/:role_name", h.DestroyRole)
+	re.GET("/:role_name", h.GetRole)
+	re.POST("/:role_name/permission", h.AddRolePermission)
+	re.DELETE("/:role_name/permission", h.RemoveRolePermission)
+
 	// Permission
-	pn := apiv1.Group("/permission", jwt.MiddlewareFunc(), rbac)
-	pn.POST("", h.CreatePermission)
-	pn.DELETE("", h.DestroyPermission)
-	pn.GET("/groups", h.GetPermissionGroups(r))
-	pn.GET("/roles/:subject", h.GetRolesForUser)
-	pn.GET("/:subject/:object/:action", h.HasRoleForUser)
+	pn := apiv1.Group("/permissions", jwt.MiddlewareFunc(), rbac)
+	pn.GET("", h.GetPermissions(r))
 
 	// Security Group
 	sg := apiv1.Group("/security-groups")
@@ -127,12 +133,6 @@ func Init(verbose bool, publicPath string, service service.REST, enforcer *casbi
 	// Manager View
 	r.Use(static.Serve("/", static.LocalFile(publicPath, false)))
 
-	// Auto init roles and check roles
-	err = rbacbase.InitRole(enforcer, r)
-	if err != nil {
-		return nil, err
-	}
-
 	// Swagger
 	apiSeagger := ginSwagger.URL("/swagger/doc.json")
 	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, apiSeagger))
diff --git a/manager/service/permission.go b/manager/service/permission.go
index 8e0af879..d53c6e5a 100644
--- a/manager/service/permission.go
+++ b/manager/service/permission.go
@@ -17,86 +17,100 @@
 package service
 
 import (
-	"fmt"
-	"strings"
+	"errors"
 
 	logger "d7y.io/dragonfly/v2/internal/dflog"
+	"d7y.io/dragonfly/v2/manager/model"
 	"d7y.io/dragonfly/v2/manager/permission/rbac"
 	"d7y.io/dragonfly/v2/manager/types"
-	"d7y.io/dragonfly/v2/pkg/util/stringutils"
 	"github.com/gin-gonic/gin"
 )
 
-func (s *rest) GetPermissionGroups(g *gin.Engine) types.PermissionGroups {
-	groups := rbac.GetAPIGroupNames(g)
-	if !stringutils.Contains(groups, "admin") {
-		groups = append(groups, "admin")
+func (s *rest) GetPermissions(g *gin.Engine) types.Permissions {
+	return rbac.GetAPIGroupNames(g)
+}
+
+func (s *rest) CreateRole(json types.CreateRolePermissionRequest) error {
+	for _, p := range json.Permissions {
+		res, err := s.enforcer.AddPolicy(json.RoleName, p.Object, p.Action)
+		if err != nil {
+			return err
+		}
+		if !res {
+			logger.Infof("The role %s that %s for %s already exist. skip!", json.RoleName, p.Object, p.Action)
+		}
+
 	}
-	return groups
+	return nil
 }
 
-func (s *rest) CreatePermission(json types.PolicyRequest) error {
-	roleName := rbac.RoleName(json.Object, json.Action)
-	res, err := s.enforcer.AddRoleForUser(json.Subject, roleName)
+func (s *rest) GetRoles() []string {
+	return s.enforcer.GetAllSubjects()
+}
+
+func (s *rest) AddRolePermission(roleName string, json types.ObjectPermission) error {
+	_, err := s.enforcer.AddPolicy(roleName, json.Object, json.Action)
 	if err != nil {
 		return err
 	}
-	if !res {
-		logger.Infof("The role %s of %s already exist. skip!", roleName, json.Subject)
-	}
+
 	return nil
 }
 
-func (s *rest) GetRolesForUser(subject string) ([]map[string]string, error) {
-	result := []map[string]string{}
-	policyToAction := map[string]string{
-		"read": "read",
-		"*":    "write",
-	}
-	res, err := s.enforcer.GetRolesForUser(subject)
+func (s *rest) RemoveRolePermission(roleName string, json types.ObjectPermission) error {
+	_, err := s.enforcer.RemovePolicy(roleName, json.Object, json.Action)
 	if err != nil {
-		return nil, err
-	}
-
-	for _, role := range res {
-		if role == "admin" {
-			result = append(result, map[string]string{"object": "admin", "description": "admin", "action": ""})
-		} else {
-			roleInfo := strings.Split(role, ":")
-			action := policyToAction[roleInfo[1]]
-			result = append(result, map[string]string{"object": roleInfo[0], "description": fmt.Sprintf("%s for %s", action, roleInfo[0]), "action": action})
-		}
+		return err
 	}
-
-	return result, nil
+	return nil
 }
 
-func (s *rest) HasRoleForUser(subject, object, action string) (bool, error) {
-	roleName := rbac.RoleName(object, action)
-	res, err := s.enforcer.HasRoleForUser(subject, roleName)
+func (s *rest) DestroyRole(roleName string) error {
+	_, err := s.enforcer.DeleteRole(roleName)
+	s.enforcer.GetAllRoles()
 	if err != nil {
-		return false, err
+		return err
 	}
-	if action == "read" {
-		writeRoleName := rbac.RoleName(object, "write")
-		writeRes, err := s.enforcer.HasRoleForUser(subject, writeRoleName)
-		if err != nil {
-			return false, err
-		}
-		return res || writeRes, nil
+	return nil
+}
 
+func (s *rest) GetRole(roleName string) []map[string]string {
+	result := []map[string]string{}
+	policies := s.enforcer.GetFilteredPolicy(0, roleName)
+	for _, p := range policies {
+		result = append(result, map[string]string{"object": p[1], "action": p[2]})
 	}
-	return res, nil
+	return result
 }
 
-func (s *rest) DestroyPermission(json types.PolicyRequest) error {
-	roleName := rbac.RoleName(json.Object, json.Action)
-	res, err := s.enforcer.DeleteRoleForUser(json.Subject, roleName)
-	if err != nil {
-		return err
+func (s *rest) GetRolesForUser(UserID uint, currentUserName string) ([]string, error) {
+	var results []string
+	var err error
+	user := model.User{}
+	if err := s.db.First(&user, UserID).Error; err != nil {
+		return nil, err
 	}
-	if !res {
-		logger.Infof("The role %s of %s already remove. skip!", roleName, json.Subject)
+	queryUserName := user.Name
+
+	if queryUserName == currentUserName {
+		results, err = s.enforcer.GetRolesForUser(queryUserName)
+		if err != nil {
+			return nil, err
+		}
+	} else {
+		has, err := s.enforcer.Enforce(currentUserName, "users", "read")
+		if err != nil {
+			return nil, err
+		}
+		if has {
+			results, err = s.enforcer.GetRolesForUser(queryUserName)
+			if err != nil {
+				return nil, err
+			}
+		} else {
+			return nil, errors.New("permission deny")
+		}
 	}
-	return nil
+
+	return results, nil
 }
diff --git a/manager/service/service.go b/manager/service/service.go
index db40ed3d..a4d7d863 100644
--- a/manager/service/service.go
+++ b/manager/service/service.go
@@ -33,11 +33,18 @@ type REST interface {
 	SignIn(json types.SignInRequest) (*model.User, error)
 	SignUp(json types.SignUpRequest) (*model.User, error)
 
-	GetPermissionGroups(g *gin.Engine) types.PermissionGroups
-	CreatePermission(json types.PolicyRequest) error
-	DestroyPermission(json types.PolicyRequest) error
-	GetRolesForUser(subject string) ([]map[string]string, error)
-	HasRoleForUser(subject, object, action string) (bool, error)
+	AddRoleForUser(uint, string) error
+	DeleteRoleForUser(uint, string) error
+
+	GetPermissions(*gin.Engine) types.Permissions
+
+	CreateRole(json types.CreateRolePermissionRequest) error
+	DestroyRole(string) error
+	AddRolePermission(string, types.ObjectPermission) error
+	RemoveRolePermission(string, types.ObjectPermission) error
+	GetRoles() []string
+	GetRole(string) []map[string]string
+	GetRolesForUser(uint, string) ([]string, error)
 
 	CreateCDNCluster(types.CreateCDNClusterRequest) (*model.CDNCluster, error)
 	CreateCDNClusterWithSecurityGroupDomain(types.CreateCDNClusterRequest) (*model.CDNCluster, error)
diff --git a/manager/service/user.go b/manager/service/user.go
index 1d77a0d9..e0c390bf 100644
--- a/manager/service/user.go
+++ b/manager/service/user.go
@@ -61,3 +61,27 @@ func (s *rest) SignUp(json types.SignUpRequest) (*model.User, error) {
 
 	return &user, nil
 }
+
+func (s *rest) AddRoleForUser(UserID uint, roleName string) error {
+	user := model.User{}
+	if err := s.db.First(&user, UserID).Error; err != nil {
+		return err
+	}
+	_, err := s.enforcer.AddRoleForUser(user.Name, roleName)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+func (s *rest) DeleteRoleForUser(UserID uint, roleName string) error {
+	user := model.User{}
+	if err := s.db.First(&user, UserID).Error; err != nil {
+		return err
+	}
+	_, err := s.enforcer.DeleteRoleForUser(user.Name, roleName)
+	if err != nil {
+		return err
+	}
+	return nil
+}
diff --git a/manager/types/permission.go b/manager/types/permission.go
index 71193027..fad65c9f 100644
--- a/manager/types/permission.go
+++ b/manager/types/permission.go
@@ -16,20 +16,22 @@
 
 package types
 
-type PolicyRequest struct {
-	Subject string `form:"subject" binding:"required,min=1"`
-	Object  string `form:"object" binding:"required,min=1"`
-	Action  string `form:"aciton" binding:"omitempty,oneof=read write"`
+type RoleParams struct {
+	RoleName string `uri:"role_name" binding:"required,min=1"`
 }
 
-type PermissionGroups []string
+type UserParams struct {
+	ID uint `uri:"user_name" binding:"required"`
+}
 
-type UserRolesParams struct {
-	Subject string `uri:"subject" binding:"required"`
+type ObjectPermission struct {
+	Object string `json:"object" binding:"required,min=1"`
+	Action string `json:"action" binding:"required,oneof=read *"`
 }
 
-type UserHasRoleParams struct {
-	UserRolesParams
-	Object string `uri:"object" binding:"required"`
-	Action string `uri:"action" binding:"omitempty,oneof=read write"`
+type CreateRolePermissionRequest struct {
+	RoleName    string             `json:"role_name" binding:"required"`
+	Permissions []ObjectPermission `json:"permissions" binding:"dive"`
 }
+
+type Permissions []string
diff --git a/manager/types/user.go b/manager/types/user.go
index 48f167d6..f188123b 100644
--- a/manager/types/user.go
+++ b/manager/types/user.go
@@ -29,3 +29,8 @@ type SignUpRequest struct {
 	Location string `form:"location" binding:"omitempty"`
 	BIO      string `form:"bio" binding:"omitempty"`
 }
+
+type RoleRequest struct {
+	RoleName string `uri:"role_name" binding:"required,min=1"`
+	ID       uint   `uri:"id" binding:"required,min=1"`
+}


Test patch:
diff --git a/manager/permission/rbac/rbac_test.go b/manager/permission/rbac/rbac_test.go
index f5902ba9..8719c32d 100644
--- a/manager/permission/rbac/rbac_test.go
+++ b/manager/permission/rbac/rbac_test.go
@@ -91,7 +91,7 @@ func TestRoleName(t *testing.T) {
 		},
 		{
 			object:           "cdns",
-			action:           "write",
+			action:           "*",
 			exceptedRoleName: "cdns:*",
 		},
 	}