55 lines
1.4 KiB
Go
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
|
|
}
|