Need to sort out
- The management background has the supermanagement permission, and the supermanagement has all permissions
- A common administrator can set a role
- Multiple rights can be assigned to a role
- In this way, we can flexibly manage the roles and permissions of common administrators
documentation
- Developed based on golang language
- Developed based on GIN network framework
- Developed based on MySQL5.8
- The permission management part is encapsulated as middleware and referenced in the Rourter file
- Non-core code has been omitted, with three vertical dots. said
Database table structure design
The administrator table
Permissions on the table
Character sheet
Indicates the permission field of the role table
Code section
The routing file
Package Server import (.... "OS" "github.com/gin-gonic/gin") // NewRouter Route configuration func NewRouter() *gin.Engine {r := Gin. Default () / / other middleware. R. gutierrez roup.. / / routing v1: = ("/API/v1 ") {v1. POST (" login ", Api.login) auth := v1.group ("") // Use(middleware.authRequired ()) Role permission check auth. Use (middleware. AuthCheckMiddleware) {... / / {auth. GET all the school GET ("/school/", api.GetSchoolInfo) } . . . } } return r }Copy the code
Permission verification middleware code
package middleware import ( . . . "fmt" "github.com/gin-gonic/gin" "net/http" "strings" ) var AuthCheckMiddleware = authCheck() func authCheck() gin.HandlerFunc { return func(c *gin.Context) { if admin, _ := c.Get("admin"); admin ! = nil { method := c.Request.Method url := c.Request.URL.Path adminInfo := admin.(**service.RunningClaims) isSuper := RoleId := (*adminInfo).roleId if IsSuper! = 1 { fmt.Println("method:", method) fmt.Println("url:", url) permissionFunc := strings.ToLower(fmt.Sprintf("%s_%s", method, url)) haveAuth := model.CheckRolePermission(uint(roleId), permissionFunc) fmt.Println("haveAuth ", haveAuth) if ! HaveAuth {c.json (http.statusok, api.returnjson {http.statusforbidden, "", "No access "}) c.apport ()}} c.ext ()}}}Copy the code
Role Model layer code
- CheckRolePermission is the key code
Type StringArray []string // Role type Role struct {Id int 'gorm:"column: Id "form:" Id" json:" Id "comment:" increment Id" SQL :"int(11),PRI" 'Name String' GORM :" Column: Name "form:" Name" JSON :" Name "comment:" role Name" SQL :" VARCHAR (255)" 'Description String 'gorM :"column:description" form:"description" JSON :"description" comment:" Description "SQL :" vARCHAR (255)"' Permission *StringArray `gorm:"type:json; Column :permission" form:"permission" json:"permission" comment:" permission" '} func (data *StringArray) Scan(val interface{}) (err error) { if val == nil { return nil } if payload, ok := val.([]byte); ok { var value []string err = json.Unmarshal(payload, &value) if err == nil { *data = value } } return } func CheckRolePermission(roleId uint, permissionFunc string) bool { if roleId == 0 { return false } var myRole Role err := DB.Where("id = ?" , roleId).First(&myRole).Error if err ! = gorm.ErrRecordNotFound { fmt.Printf("%v", myRole) permissions := myRole.Permission permissions.Scan(permissions) for _, permission := range *permissions { fmt.Println("permissionFunc:", permissionFunc) fmt.Println("permission:", permission) if strings.HasPrefix(permissionFunc, permission) { return true } } } return false }Copy the code
Running effect
Have permission
{"code": 403, "data": "", "message": "no access"}Copy the code
Without permission
{"code": 200, "data": true, "message": "update successful"}Copy the code
subsequent
The next chapter encapsulates the operation log management of the management background: The operation log of the administrator is saved in middleware + Goroutine mode