|
|
@ -15,6 +15,8 @@ const ( |
|
|
|
type userIdKey struct{} |
|
|
|
type userIdKey struct{} |
|
|
|
type authKey struct { |
|
|
|
type authKey struct { |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
type ParseFunc func(key string, tokenStr string) (*token.UserInfo, error) |
|
|
|
type JwtOption func(o *options) |
|
|
|
type JwtOption func(o *options) |
|
|
|
|
|
|
|
|
|
|
|
func WithJwtKey(jwtKey string) JwtOption { |
|
|
|
func WithJwtKey(jwtKey string) JwtOption { |
|
|
@ -35,16 +37,24 @@ func WithValidatePermission(validatePermission func(permissions []string, key st |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func WithParseFunc(parseFunc ParseFunc) JwtOption { |
|
|
|
|
|
|
|
return func(o *options) { |
|
|
|
|
|
|
|
o.parseFunc = parseFunc |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
type options struct { |
|
|
|
type options struct { |
|
|
|
jwtKey string |
|
|
|
jwtKey string |
|
|
|
validate func(authKey string) error |
|
|
|
validate func(authKey string) error |
|
|
|
validatePermission func(validatePermission []string, key string) bool |
|
|
|
validatePermission func(validatePermission []string, key string) bool |
|
|
|
|
|
|
|
parseFunc ParseFunc |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
func JWT(opts ...JwtOption) middleware.Middleware { |
|
|
|
func JWT(opts ...JwtOption) middleware.Middleware { |
|
|
|
var cfg = &options{ |
|
|
|
var cfg = &options{ |
|
|
|
jwtKey: "JssLx22bjQwnyqby", |
|
|
|
jwtKey: "JssLx22bjQwnyqby", |
|
|
|
validatePermission: InSlice, |
|
|
|
validatePermission: InSlice, |
|
|
|
|
|
|
|
parseFunc: token.Parse, |
|
|
|
} |
|
|
|
} |
|
|
|
for _, o := range opts { |
|
|
|
for _, o := range opts { |
|
|
|
o(cfg) |
|
|
|
o(cfg) |
|
|
@ -62,7 +72,7 @@ func JWT(opts ...JwtOption) middleware.Middleware { |
|
|
|
if tr, ok := transport.FromServerContext(ctx); ok { |
|
|
|
if tr, ok := transport.FromServerContext(ctx); ok { |
|
|
|
tokenStr = tr.RequestHeader().Get("token") |
|
|
|
tokenStr = tr.RequestHeader().Get("token") |
|
|
|
} |
|
|
|
} |
|
|
|
userInfo, err := token.Parse(cfg.jwtKey, tokenStr) |
|
|
|
userInfo, err := cfg.parseFunc(cfg.jwtKey, tokenStr) |
|
|
|
if err != nil { |
|
|
|
if err != nil { |
|
|
|
return nil, err |
|
|
|
return nil, err |
|
|
|
} |
|
|
|
} |
|
|
|