package middleware import ( "Medical_ERP/common/global" "Medical_ERP/common/response" "Medical_ERP/conf" "Medical_ERP/services" "encoding/json" "errors" "github.com/beego/beego/v2/core/logs" beego "github.com/beego/beego/v2/server/web" "github.com/go-resty/resty/v2" "github.com/gobwas/glob" coreModel "gogs.baozhida.cn/zoie/OAuth-core/model" jwt "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth" "net/http" "strconv" "strings" adapter "github.com/beego/beego/v2/adapter" "github.com/beego/beego/v2/adapter/context" ) const ErrUnauthorized = "Unauthorized" // AuthMiddle 中间件 func AuthMiddle() { // 不 需要验证的url FilterExcludeURL, _ := beego.AppConfig.String("FilterExcludeURL") FilterOnlyLoginCheckURL, _ := beego.AppConfig.String("FilterOnlyLoginCheckURL") FilterNotEnterDeptURL, _ := beego.AppConfig.String("FilterNotEnterDeptURL") var filterLogin = func(ctx *context.Context) { url := ctx.Input.URL() method := ctx.Input.Method() if !strings.Contains(FilterExcludeURL, url) && !strings.Contains(url, "/swagger") && !strings.Contains(url, "/static") { // 验证登录 usr, code, err := ValidateToken(ctx) if err != nil { ctx.Output.JSON(response.Error(code, err, err.Error()), true, true) return } if usr.DeptId == 0 && !strings.Contains(FilterNotEnterDeptURL, url) { ctx.Output.JSON(response.Error(global.EnterDeptErr, EnterDeptErr, EnterDeptErr.Error()), true, true) return } // 过滤掉不需要验证权限的路由 if !strings.Contains(FilterOnlyLoginCheckURL, url) { if usr.RoleKey != "admin" { //校验权限 if !checkPermission(usr.RoleKey, url, method) { ctx.Output.JSON(response.Error(global.NoAccessErr, nil, "无权访问"), true, true) return } } } ctx.Input.SetData(global.ContextKeyUserObj, usr) } } adapter.InsertFilter("/api/*", adapter.BeforeRouter, filterLogin) } var EnterDeptErr = errors.New("请先进入公司") func ValidateToken(c *context.Context) (coreModel.UserInfo, int, error) { reqPath := "/api/service/userinfo" url := conf.OAuthBaseUrl + reqPath r, reqError := resty.New().R().SetHeaders( map[string]string{ "Authorization": c.Request.Header.Get("Authorization"), "serviceId": strconv.Itoa(global.ServiceId), }, ).Get(url) if reqError != nil { logs.Error(reqError) return coreModel.UserInfo{}, global.BadRequest, reqError } type Res struct { response.Msg Data coreModel.UserInfo `json:"data"` } var res Res // 替换为你期望的结构体类型 err := json.Unmarshal(r.Body(), &res) if err != nil { logs.Error(err) return coreModel.UserInfo{}, global.BadRequest, err } if res.Code != http.StatusOK { logs.Error(errors.New(res.Msg.Msg)) return coreModel.UserInfo{}, int(res.Code), errors.New(res.Msg.Msg) } c.Input.SetData(jwt.JwtPayloadKey, jwt.MapClaims{ "uuid": res.Data.Uuid, "identity": float64(res.Data.UserId), "username": res.Data.UserName, "roleName": res.Data.RoleName, "deptName": res.Data.DeptName, "roleKey": res.Data.RoleKey, "userId": float64(res.Data.UserId), "roleId": float64(res.Data.RoleId), "dataScope": float64(res.Data.DataScope), "deptId": float64(res.Data.DeptId), }) return res.Data, global.MsgOk, nil } // 验证权限 func checkPermission(roleKey, url string, method string) bool { RoleApiService := services.RoleApi{} apiList, err := RoleApiService.GetRoleApi(roleKey) if err != nil { return false } for _, v := range apiList { g := glob.MustCompile(strings.Replace(v.Path, ":id", "?", -1)) if g.Match(url) && v.Action == method { return true } } return false }