miniprogram_middleware.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package middleware
  2. import (
  3. "context"
  4. "github.com/casbin/casbin/v2"
  5. "github.com/redis/go-redis/v9"
  6. "github.com/spf13/cast"
  7. "github.com/suyuan32/simple-admin-common/enum/errorcode"
  8. "github.com/suyuan32/simple-admin-core/rpc/coreclient"
  9. "github.com/zeromicro/go-zero/core/errorx"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "github.com/zeromicro/go-zero/rest/httpx"
  12. "net/http"
  13. "wechat-api/internal/config"
  14. jwtutils "wechat-api/internal/utils/jwt"
  15. )
  16. type MiniprogramMiddleware struct {
  17. Cbn *casbin.Enforcer
  18. Rds redis.UniversalClient
  19. CoreRpc coreclient.Core
  20. Config config.Config
  21. }
  22. func NewMiniprogramMiddleware(cbn *casbin.Enforcer, rds redis.UniversalClient, core coreclient.Core, c config.Config) *MiniprogramMiddleware {
  23. return &MiniprogramMiddleware{
  24. Cbn: cbn,
  25. Rds: rds,
  26. CoreRpc: core,
  27. Config: c,
  28. }
  29. }
  30. func (m *MiniprogramMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
  31. return func(w http.ResponseWriter, r *http.Request) {
  32. tokenStr := jwtutils.StripBearerPrefixFromToken(r.Header.Get("Authorization"))
  33. claims, err := jwtutils.ParseJwtToken(m.Config.Auth.AccessSecret, tokenStr)
  34. if err != nil {
  35. logx.Errorw("check user auth error", logx.Field("detail", err.Error()))
  36. httpx.Error(w, errorx.NewApiError(http.StatusInternalServerError, err.Error()))
  37. return
  38. }
  39. jwtUid, ok := claims["userId"]
  40. userId := cast.ToUint64(jwtUid)
  41. if ok && userId > 0 {
  42. r = r.WithContext(context.WithValue(r.Context(), "userId", userId))
  43. next(w, r)
  44. return
  45. } else {
  46. logx.Errorw("User need to login in to access the resource")
  47. httpx.Error(w, errorx.NewCodeError(errorcode.PermissionDenied, "User need to login in to access the resource"))
  48. return
  49. }
  50. }
  51. }