08.RBAC判断权限
# 01.判断权限
# 1.1 adminRouter.go注册中间件
routers\adminRouter.go
package routers
import (
"beegoxiaomi/controllers/admin"
"beegoxiaomi/middleware"
"github.com/astaxie/beego"
)
func init() {
ns :=
beego.NewNamespace("/"+beego.AppConfig.String("adminPath"),
//中间件:匹配路由前会执,可以用于权限验证
//注意引入的包: github.com/astaxie/beego/context
beego.NSBefore(middleware.AdminAuth),
)
//注册 namespace
beego.AddNamespace(ns)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 1.2 middleware\adminAuth.go
middleware\adminAuth.go
package middleware
import (
"beegoxiaomi/models"
"net/url"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
)
func AdminAuth(ctx *context.Context) {
pathname := ctx.Request.URL.String()
userinfo, ok := ctx.Input.Session("userinfo").(models.Manager) //类型断言
if !(ok && userinfo.Username != "") {
if pathname != "/"+beego.AppConfig.String("adminPath")+"/login" && pathname != "/"+beego.AppConfig.String("adminPath")+"/login/doLogin" {
ctx.Redirect(302, "/"+beego.AppConfig.String("adminPath")+"/login")
}
} else {
pathname = strings.Replace(pathname, "/"+beego.AppConfig.String("adminPath"), "", 1)
urlPath, _ := url.Parse(pathname) //urlPath.Path /role/edit
//判断管理员是不是超级管理员以及判断排除的url地址
if userinfo.IsSuper == 0 && !excludeAuthPath(string(urlPath.Path)) {
// 1、根据角色获取当前角色的权限列表,然后把权限id放在一个map类型的对象里面
roleId := userinfo.RoleId
roleAccess := []models.RoleAccess{}
models.DB.Where("role_id=?", roleId).Find(&roleAccess)
roleAccessMap := make(map[int]int)
for _, v := range roleAccess {
roleAccessMap[v.AccessId] = v.AccessId
}
// 2、获取当前访问的url对应的权限id
/*
/beego_admin/manager 替换成 /manager
beego_admin/role/edit?id=11 替换成 /role/edit
pathname = strings.Replace(pathname, "/"+beego.AppConfig.String("adminPath"), "", 1)
urlPath, _ := url.Parse(pathname) //urlPath.Path /role/edit
*/
access := models.Access{}
models.DB.Where("url=?", urlPath.Path).Find(&access)
//3、判断当前访问的url对应的权限id 是否在权限列表的id中
if _, ok := roleAccessMap[access.Id]; !ok {
ctx.WriteString("没有权限")
return
}
}
}
}
//判断一个url是否在排除的地址里面
func excludeAuthPath(urlPath string) bool {
excludeAuthPathSlice := strings.Split(beego.AppConfig.String("excludeAuthPath"), ",")
for _, v := range excludeAuthPathSlice {
if v == urlPath {
return true
}
}
return false
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 1.3 conf\app.conf
- 配置哪些路径无需权限都可以访问
excludeAuthPath="/,/welcome,/login/loginOut"
1
上次更新: 2024/3/13 15:35:10