auth_middle.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. package middleware
  2. import (
  3. "Medical_ERP/common/global"
  4. "Medical_ERP/common/response"
  5. "Medical_ERP/conf"
  6. "Medical_ERP/services"
  7. "encoding/json"
  8. "errors"
  9. "github.com/beego/beego/v2/core/logs"
  10. beego "github.com/beego/beego/v2/server/web"
  11. "github.com/go-resty/resty/v2"
  12. "github.com/gobwas/glob"
  13. coreModel "gogs.baozhida.cn/zoie/OAuth-core/model"
  14. jwt "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
  15. "net/http"
  16. "strconv"
  17. "strings"
  18. adapter "github.com/beego/beego/v2/adapter"
  19. "github.com/beego/beego/v2/adapter/context"
  20. )
  21. const ErrUnauthorized = "Unauthorized"
  22. // AuthMiddle 中间件
  23. func AuthMiddle() {
  24. // 不 需要验证的url
  25. FilterExcludeURL, _ := beego.AppConfig.String("FilterExcludeURL")
  26. FilterOnlyLoginCheckURL, _ := beego.AppConfig.String("FilterOnlyLoginCheckURL")
  27. FilterNotEnterDeptURL, _ := beego.AppConfig.String("FilterNotEnterDeptURL")
  28. var filterLogin = func(ctx *context.Context) {
  29. url := ctx.Input.URL()
  30. method := ctx.Input.Method()
  31. if !strings.Contains(FilterExcludeURL, url) && !strings.Contains(url, "/swagger") && !strings.Contains(url, "/static") {
  32. // 验证登录
  33. usr, code, err := ValidateToken(ctx)
  34. if err != nil {
  35. ctx.Output.JSON(response.Error(code, err, err.Error()),
  36. true, true)
  37. return
  38. }
  39. if usr.DeptId == 0 && !strings.Contains(FilterNotEnterDeptURL, url) {
  40. ctx.Output.JSON(response.Error(global.EnterDeptErr, EnterDeptErr, EnterDeptErr.Error()),
  41. true, true)
  42. return
  43. }
  44. // 过滤掉不需要验证权限的路由
  45. if !strings.Contains(FilterOnlyLoginCheckURL, url) {
  46. if usr.RoleKey != "admin" {
  47. //校验权限
  48. if !checkPermission(usr.RoleKey, url, method) {
  49. ctx.Output.JSON(response.Error(global.NoAccessErr, nil, "无权访问"), true, true)
  50. return
  51. }
  52. }
  53. }
  54. ctx.Input.SetData(global.ContextKeyUserObj, usr)
  55. }
  56. }
  57. adapter.InsertFilter("/api/*", adapter.BeforeRouter, filterLogin)
  58. }
  59. var EnterDeptErr = errors.New("请先进入公司")
  60. func ValidateToken(c *context.Context) (coreModel.UserInfo, int, error) {
  61. reqPath := "/api/service/userinfo"
  62. url := conf.OAuthBaseUrl + reqPath
  63. r, reqError := resty.New().R().SetHeaders(
  64. map[string]string{
  65. "Authorization": c.Request.Header.Get("Authorization"),
  66. "serviceId": strconv.Itoa(global.ServiceId),
  67. },
  68. ).Get(url)
  69. if reqError != nil {
  70. logs.Error(reqError)
  71. return coreModel.UserInfo{}, global.BadRequest, reqError
  72. }
  73. type Res struct {
  74. response.Msg
  75. Data coreModel.UserInfo `json:"data"`
  76. }
  77. var res Res // 替换为你期望的结构体类型
  78. err := json.Unmarshal(r.Body(), &res)
  79. if err != nil {
  80. logs.Error(err)
  81. return coreModel.UserInfo{}, global.BadRequest, err
  82. }
  83. if res.Code != http.StatusOK {
  84. logs.Error(errors.New(res.Msg.Msg))
  85. return coreModel.UserInfo{}, int(res.Code), errors.New(res.Msg.Msg)
  86. }
  87. c.Input.SetData(jwt.JwtPayloadKey, jwt.MapClaims{
  88. "uuid": res.Data.Uuid,
  89. "identity": float64(res.Data.UserId),
  90. "username": res.Data.UserName,
  91. "roleName": res.Data.RoleName,
  92. "deptName": res.Data.DeptName,
  93. "roleKey": res.Data.RoleKey,
  94. "userId": float64(res.Data.UserId),
  95. "roleId": float64(res.Data.RoleId),
  96. "dataScope": float64(res.Data.DataScope),
  97. "deptId": float64(res.Data.DeptId),
  98. })
  99. return res.Data, global.MsgOk, nil
  100. }
  101. // 验证权限
  102. func checkPermission(roleKey, url string, method string) bool {
  103. RoleApiService := services.RoleApi{}
  104. apiList, err := RoleApiService.GetRoleApi(roleKey)
  105. if err != nil {
  106. return false
  107. }
  108. for _, v := range apiList {
  109. g := glob.MustCompile(strings.Replace(v.Path, ":id", "?", -1))
  110. if g.Match(url) && v.Action == method {
  111. return true
  112. }
  113. }
  114. return false
  115. }