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.
54 lines
1.0 KiB
54 lines
1.0 KiB
package jwt
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"zestack.dev/slim"
|
|
)
|
|
|
|
type AuthConfig struct {
|
|
Skipper func(c slim.Context) bool
|
|
Finder Finder
|
|
Anonymously bool
|
|
Claims func(c slim.Context, token string, claims *Claims) error
|
|
}
|
|
|
|
func (config AuthConfig) ToMiddleware() slim.MiddlewareFunc {
|
|
if config.Finder == nil {
|
|
config.Finder = DefaultFinder
|
|
}
|
|
return func(c slim.Context, next slim.HandlerFunc) error {
|
|
if config.Skipper != nil && config.Skipper(c) {
|
|
return next(c)
|
|
}
|
|
token := config.Finder(c)
|
|
if token == "" {
|
|
if config.Anonymously {
|
|
return next(c)
|
|
}
|
|
return ErrTokenNotFound
|
|
}
|
|
claims, err := Verify(token)
|
|
if errors.Is(err, ErrTokenExpired) {
|
|
c.SetHeader("X-Token-Expired", "true")
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
if config.Claims != nil {
|
|
err = config.Claims(c, token, claims)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if c.Written() {
|
|
return nil
|
|
}
|
|
c.Set("jwt:token", token)
|
|
c.Set("jwt:claims", claims)
|
|
return next(c)
|
|
}
|
|
}
|
|
|
|
func Auth(c AuthConfig) slim.MiddlewareFunc {
|
|
return c.ToMiddleware()
|
|
}
|
|
|