|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"git.diulo.com/mogfee/kit/errors"
|
|
|
|
"git.diulo.com/mogfee/kit/transport"
|
|
|
|
"git.diulo.com/mogfee/kit/transport/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JwtDefault struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *JwtDefault) GetToken(ctx context.Context, key string) (tokenStr string) {
|
|
|
|
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 ""
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *JwtDefault) ParseToken(ctx context.Context, key string, token string) (*UserInfo, error) {
|
|
|
|
return Parse(key, token)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *JwtDefault) Validate(ctx context.Context, permission string, permissions []string) error {
|
|
|
|
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", "")
|
|
|
|
}
|