You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.1 KiB

2 years ago
package jwt
import (
"context"
11 months ago
"git.diulo.com/mogfee/kit/errors"
2 years ago
"git.diulo.com/mogfee/kit/middleware"
)
type JwtOption func(o *options)
func WithJwtKey(jwtKey string) JwtOption {
return func(o *options) {
o.jwtKey = jwtKey
}
}
1 year ago
func WithFromKey(fromKey string) JwtOption {
2 years ago
return func(o *options) {
1 year ago
o.fromKey = fromKey
2 years ago
}
}
1 year ago
func WithValidate(val JwtValidate) JwtOption {
2 years ago
return func(o *options) {
1 year ago
o.validate = val
1 year ago
}
}
2 years ago
type options struct {
1 year ago
jwtKey string
fromKey string //cookie:token header:key
validate JwtValidate
}
type JwtValidate interface {
//GetToken 获取token
GetToken(ctx context.Context, key string) (tokenStr string)
//ParseToken 解析token获取用户信息
ParseToken(ctx context.Context, key string, token string) (*UserInfo, error)
//Validate 校验权限
Validate(ctx context.Context, permission string, permissions []string) error
2 years ago
}
func JWT(opts ...JwtOption) middleware.Middleware {
var cfg = &options{
11 months ago
jwtKey: "JssLx22bjQwnyqby",
fromKey: "header:token",
//validate: &JwtDefault{},
2 years ago
}
for _, o := range opts {
o(cfg)
}
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, a any) (any, error) {
1 year ago
//1. 解析token
//2. 获取用户信息
//3. 校验权限
//4. 设置ctx
2 years ago
authKey := FromAuthKeyContext(ctx)
needAuth := FromNeedAuthContext(ctx)
2 years ago
1 year ago
// 解析token
11 months ago
//tokenStr := cfg.validate.GetToken(ctx, cfg.fromKey)
//if tokenStr == "" && needAuth {
// return nil, errors.Unauthorized("NO_TOKEN", "")
//}
tokenStr := ""
1 year ago
if tokenStr != "" {
if err := func() error {
userInfo, err := cfg.validate.ParseToken(ctx, cfg.jwtKey, tokenStr)
if err != nil {
return err
}
1 year ago
if needAuth && userInfo.UserId == "" {
11 months ago
return errors.Unauthorized("TOKEN_BAD", "")
1 year ago
}
if authKey != "" {
if err = cfg.validate.Validate(ctx, authKey, userInfo.Permissions); err != nil {
return err
}
}
1 year ago
if userInfo.UserId != "" {
1 year ago
ctx = SetUserContext(ctx, userInfo)
}
return nil
}(); err != nil {
if needAuth {
1 year ago
return nil, err
}
}
1 year ago
}
2 years ago
return handler(ctx, a)
}
}
}