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"
- )
- /*
- //"wechat-api/internal/types/payload"
- var p types.payload.SendWxPayload
- */
- 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
- )
- /*
- r, e = m.getTokenUserInfoByRds(ctx, loginToken)
- fmt.Println("redis:", "code-", r, "err-", e)
- */
- val, rc, err = m.getTokenUserInfoByDb(ctx, loginToken)
- _ = rc
- if err != nil {
- return nil, err
- }
- return val, nil
- }
- /*
- func (m *OpenAuthorityMiddleware) getTokenUserInfoByRds(ctx context.Context, loginToken string) (code int, err error) {
- rcode := -1
- val, err := m.Rds.HGet(ctx, "api_key", loginToken).Result()
- if err == redis.Nil {
- rcode = 0
- } else if err == nil {
- rcode = 1
- }
- fmt.Printf("From Redis By Key:'%s' Get '%s'(%v)\n", loginToken, val, val)
- fmt.Println(val)
- return rcode, err
- }
- */
- 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) //context存入http.ResponseWriter
- 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.OpenapiTokenKey.WithValue(ctx, apiToken)
- ctx = contextkey.AuthTokenInfoKey.WithValue(ctx, apiKeyObj)
- /*
- fmt.Println("=========================================")
- fmt.Printf("In Middleware Get Token Info:\nKey:'%s'\n", apiKeyObj.Key)
- fmt.Printf("Title:'%s'\n", apiKeyObj.Title)
- fmt.Printf("OpenaiBase:'%s'\n", apiKeyObj.OpenaiBase)
- fmt.Printf("OpenaiKey:'%s'\n", apiKeyObj.OpenaiKey)
- fmt.Println("=========================================")
- claims, err := jwtutils.ParseJwtToken(m.Config.Auth.AccessSecret, authToken)
- fmt.Println("claims")
- fmt.Printf("%+v\n", claims)
- if err != nil {
- logx.Errorw("check user auth error", logx.Field("detail", err.Error()))
- httpx.Error(w, errorx.NewApiError(http.StatusInternalServerError, err.Error()))
- return
- }
- */
- newReq := r.WithContext(ctx)
- // Passthrough to next handler if need
- next(w, newReq)
- }
- }
|