123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- package middleware
- import (
- "context"
- "net/http"
- "wechat-api/ent"
- "wechat-api/ent/apikey"
- "wechat-api/ent/predicate"
- "wechat-api/internal/utils/contextkey"
- "wechat-api/internal/config"
- "github.com/redis/go-redis/v9"
- "github.com/suyuan32/simple-admin-common/utils/jwt"
- "github.com/zeromicro/go-zero/core/errorx"
- "github.com/zeromicro/go-zero/rest/httpx"
- )
- type OpenAuthorityMiddleware struct {
- DB *ent.Client
- Rds redis.UniversalClient
- Config config.Config
- }
- func NewOpenAuthorityMiddleware(db *ent.Client, rds redis.UniversalClient, c config.Config) *OpenAuthorityMiddleware {
- return &OpenAuthorityMiddleware{
- DB: db,
- Rds: rds,
- Config: c,
- }
- }
- func (m *OpenAuthorityMiddleware) checkTokenUserInfo(ctx context.Context, loginToken string) (*ent.ApiKey, error) {
- var (
- rc int
- err error
- val *ent.ApiKey
- )
-
- val, rc, err = m.getTokenUserInfoByDb(ctx, loginToken)
- _ = rc
- if err != nil {
- return nil, err
- }
- return val, nil
- }
- func (m *OpenAuthorityMiddleware) getTokenUserInfoByDb(ctx context.Context, loginToken string) (*ent.ApiKey, int, error) {
- rcode := -1
- var predicates []predicate.ApiKey
- predicates = append(predicates, apikey.KeyEQ(loginToken))
- val, err := m.DB.ApiKey.Query().Where(predicates...).WithAgent().Only(ctx)
- if err != nil {
- return nil, rcode, err
- }
- return val, 1, nil
- }
- func (m *OpenAuthorityMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- ctx = contextkey.HttpResponseWriterKey.WithValue(ctx, w)
- authToken := jwt.StripBearerPrefixFromToken(r.Header.Get("Authorization"))
- if len(authToken) == 0 {
- httpx.Error(w, errorx.NewApiError(http.StatusForbidden, "无法获得token"))
- return
- }
- apiKeyObj, err := m.checkTokenUserInfo(ctx, authToken)
- if err != nil {
- httpx.Error(w, errorx.NewApiError(http.StatusForbidden, "无法获得合理的授权信息"))
- return
- }
-
- ctx = contextkey.AuthTokenInfoKey.WithValue(ctx, apiKeyObj)
-
- newReq := r.WithContext(ctx)
-
- next(w, newReq)
- }
- }
|