user/biz/mw/jwt.go
timerzz b4448efb2a
Some checks failed
Build image / build (push) Failing after 26s
添加工作流
2025-05-21 12:29:01 +08:00

55 lines
1.4 KiB
Go

package mw
import (
"context"
"net/http"
"time"
"gitea.timerzz.com/onecat/user/biz/handle"
"gitea.timerzz.com/onecat/user/biz/model/common"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/hertz-contrib/jwt"
)
const (
identityKey = "phone"
)
func NewJwt(authenticator func(ctx context.Context, c *app.RequestContext) (interface{}, error)) *jwt.HertzJWTMiddleware {
middleware, err := jwt.New(&jwt.HertzJWTMiddleware{
Realm: "kedaya-onecat-task",
Key: []byte("kedaya"),
Timeout: time.Hour * 24,
MaxRefresh: time.Hour,
IdentityKey: identityKey,
PayloadFunc: func(data interface{}) jwt.MapClaims {
if v, ok := data.(*common.User); ok {
return jwt.MapClaims{
identityKey: v.Phone,
}
}
return jwt.MapClaims{}
},
IdentityHandler: func(ctx context.Context, c *app.RequestContext) interface{} {
claims := jwt.ExtractClaims(ctx, c)
return &common.User{
Phone: claims[identityKey].(string),
}
},
Authenticator: authenticator,
LoginResponse: func(ctx context.Context, c *app.RequestContext, code int, token string, expire time.Time) {
c.JSON(http.StatusOK, handle.LoginResponse{
Token: token,
Expire: expire.Format(time.RFC3339),
Message: "success",
Code: code,
})
},
})
if err != nil {
hlog.Fatalf("JWT Error:" + err.Error())
}
return middleware
}