mw_auth.go 863 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package middleware
  2. import (
  3. "github.com/gogf/gf/v2/net/ghttp"
  4. "gxt-api-frame/app/errors"
  5. "gxt-api-frame/library/auth"
  6. "gxt-api-frame/library/gplus"
  7. "gxt-api-frame/library/utils"
  8. )
  9. func UserAuthMiddleware(skippers ...SkipperFunc) ghttp.HandlerFunc {
  10. jwt := auth.New()
  11. return func(r *ghttp.Request) {
  12. if len(skippers) > 0 && skippers[0](r) {
  13. r.Middleware.Next()
  14. return
  15. }
  16. var userId string
  17. if t := gplus.GetToken(r); t != "" {
  18. id, err := jwt.ParseUserID(t)
  19. if err != nil {
  20. gplus.ResError(r, err)
  21. }
  22. userId = id
  23. }
  24. if userId != "" {
  25. gplus.SetUserId(r, userId)
  26. }
  27. if userId == "" {
  28. if utils.GetConfig("common.RunMode").String() == "debug" {
  29. gplus.SetUserId(r, utils.GetConfig("root.user_name").String())
  30. r.Middleware.Next()
  31. return
  32. }
  33. gplus.ResError(r, errors.ErrNoPerm)
  34. }
  35. r.Middleware.Next()
  36. }
  37. }