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.

90 lines
1.9 KiB

2 years ago
package jwt
import (
11 months ago
"git.diulo.com/mogfee/kit/core/token"
11 months ago
"git.diulo.com/mogfee/kit/errors"
11 months ago
"git.diulo.com/mogfee/kit/rest"
"git.diulo.com/mogfee/kit/rest/httpx"
"net/http"
"strings"
2 years ago
)
11 months ago
type UserInfo struct {
UserId string
UserName string
UserType string
Permissions []string
UniqueId string
2 years ago
}
11 months ago
func Middleware() rest.Middleware {
tokenServer := token.NewTokenService("sfe023f_9fd&fwfl")
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
2 years ago
1 year ago
//1. 解析token
//2. 获取用户信息
//3. 校验权限
//4. 设置ctx
2 years ago
authKey := FromAuthKeyContext(ctx)
needAuth := FromNeedAuthContext(ctx)
2 years ago
11 months ago
//解析token
tokenStr := r.Header.Get("token")
if tokenStr == "" {
tokenStr = r.URL.Query().Get("token")
}
if tokenStr == "" && needAuth {
httpx.Error(w, errors.Unauthorized("NO_TOKEN", ""))
return
}
1 year ago
if tokenStr != "" {
if err := func() error {
11 months ago
res, err := tokenServer.Parse(tokenStr)
1 year ago
if err != nil {
return err
}
11 months ago
if needAuth && res == nil {
11 months ago
return errors.Unauthorized("TOKEN_BAD", "")
1 year ago
}
if authKey != "" {
11 months ago
if err = defaultValidate(authKey, res); err != nil {
1 year ago
return err
}
}
11 months ago
//if userInfo.UserId != "" {
// ctx = SetUserContext(ctx, userInfo)
//}
1 year ago
return nil
}(); err != nil {
if needAuth {
11 months ago
httpx.Error(w, err)
return
1 year ago
}
}
1 year ago
}
11 months ago
next(w, r)
}
}
}
func defaultValidate(authKey string, res any) error {
userInfo, ok := res.(*UserInfo)
if !ok {
return errors.Forbidden("TOKEN_PERMISSION_BAD", "权限不足")
}
allowMap := make(map[string]bool)
for _, v := range strings.Split(authKey, "|") {
allowMap[v] = true
}
for _, v := range userInfo.Permissions {
if allowMap[v] {
return nil
2 years ago
}
}
11 months ago
return errors.Forbidden("TOKEN_PERMISSION_BAD", "权限不足")
2 years ago
}