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.
57 lines
1.3 KiB
57 lines
1.3 KiB
package jwt |
|
|
|
import ( |
|
"context" |
|
"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 errorx.Forbidden("TOKEN_PERMISSION_BAD", "权限不足") |
|
}
|
|
|