88 lines
2.2 KiB
Go
88 lines
2.2 KiB
Go
package server
|
||
|
||
import (
|
||
apiUser "admin/apps/user/api"
|
||
"admin/internal/context"
|
||
"admin/internal/errcode"
|
||
"admin/internal/permission"
|
||
"admin/lib/xlog"
|
||
"strings"
|
||
)
|
||
|
||
func (srv *Server) CheckToken(ctx *context.WebContext) {
|
||
reqPath := ctx.GinCtx().Request.URL.Path
|
||
xlog.Tracef("请求路径:%v, 头:%+v", reqPath, ctx.GinCtx().Request.Header)
|
||
if strings.Contains(reqPath, "/login") {
|
||
return
|
||
}
|
||
if len(reqPath) > 3 && reqPath[:4] != "/api" { // 用来过滤出非/api请求,前后端部署到一起时,访问静态页面的请求跳过token检查
|
||
ctx.GinCtx().Next()
|
||
return
|
||
}
|
||
|
||
err := ctx.ExtractHeader()
|
||
if err != nil {
|
||
ctx.Fail(errcode.New(errcode.HeaderParamsInvalid, "header invalid"))
|
||
return
|
||
}
|
||
|
||
authRsp, err := apiUser.GetUserApiInstance().Auth(ctx, &apiUser.AuthReq{
|
||
Token: ctx.Header.Token,
|
||
UserId: ctx.Header.UserId,
|
||
})
|
||
if err != nil {
|
||
ctx.Fail(err)
|
||
return
|
||
}
|
||
|
||
ctx.Header.UserName = authRsp.User.NickName
|
||
|
||
ctx.GinCtx().Set("userInfo", authRsp)
|
||
ctx.GinCtx().Next()
|
||
return
|
||
}
|
||
|
||
func (srv *Server) CheckPermissions(ctx *context.WebContext) {
|
||
userInfoI, find := ctx.GinCtx().Get("userInfo")
|
||
if !find {
|
||
ctx.Fail(errcode.New(errcode.TokenInvalid, "not found ctx userInfo"))
|
||
return
|
||
}
|
||
userInfo, _ := userInfoI.(*apiUser.UserInfo)
|
||
|
||
projectId, resource := getCtxURIProjectIdAndResource(ctx)
|
||
if projectId <= 0 {
|
||
if ctx.GinCtx().Request.URL.Path == "/api/project" {
|
||
if userInfo.Character != "admin" {
|
||
ctx.Fail(errcode.New(errcode.NoPermission, "user %v is not admin, can't operate project", ctx.Header.UserId))
|
||
return
|
||
}
|
||
ctx.GinCtx().Next()
|
||
return
|
||
}
|
||
ctx.Fail(errcode.New(errcode.NoPermission, "project_id %v in ctx invalid", projectId))
|
||
return
|
||
}
|
||
if resource == "" {
|
||
ctx.Fail(errcode.New(errcode.NoPermission, "resource %v in ctx invalid", resource))
|
||
return
|
||
}
|
||
|
||
reqPermission := permission.GetProjectResourcePermission(projectId, resource, ctx.GinCtx().Request.Method)
|
||
|
||
if userInfo.Character == "admin" {
|
||
ctx.GinCtx().Next()
|
||
return
|
||
}
|
||
|
||
for _, v := range userInfo.Permissions {
|
||
if reqPermission == v {
|
||
ctx.GinCtx().Next()
|
||
return
|
||
}
|
||
}
|
||
|
||
ctx.Fail(errcode.New(errcode.NoPermission, "user %v don't have permission %v", ctx.Header.UserId, reqPermission))
|
||
return
|
||
}
|