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.

59 lines
1.4 KiB

2 years ago
package jwt
import (
"context"
"git.diulo.com/mogfee/kit/errors"
"git.diulo.com/mogfee/kit/transport"
"git.diulo.com/mogfee/kit/transport/http"
"strings"
)
2 years ago
type JwtDefault struct {
2 years ago
}
2 years ago
func (j *JwtDefault) GetToken(ctx context.Context, key string) (tokenStr string) {
2 years ago
arr := strings.Split(key, ":")
if len(arr) != 2 {
return ""
}
switch arr[0] {
case "cookie":
if tr, ok := transport.FromServerContext(ctx); ok {
if tr1, ok := tr.(http.Transporter); ok {
if co, err := tr1.Request().Cookie(arr[1]); err == nil {
return co.Value
}
}
}
case "header":
if tr, ok := transport.FromServerContext(ctx); ok {
return tr.RequestHeader().Get(arr[1])
}
case "query":
if tr, ok := transport.FromServerContext(ctx); ok {
if ht, ok := tr.(http.Transporter); ok {
return ht.Request().URL.Query().Get(arr[1])
}
}
}
return ""
}
2 years ago
func (j *JwtDefault) ParseToken(ctx context.Context, key string, token string) (*UserInfo, error) {
1 year ago
return Parse(key, token)
2 years ago
}
2 years ago
func (j *JwtDefault) Validate(ctx context.Context, permission string, permissions []string) error {
2 years ago
allowPers := strings.Split(permission, "|")
allowMap := make(map[string]bool, len(allowPers))
for _, v := range allowPers {
allowMap[v] = true
}
for _, v := range permissions {
if allowMap[v] {
return nil
}
}
return errors.Unauthorized("TOKEN_PERMISSION_BAD", "")
}