|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"git.diulo.com/mogfee/kit/core/token"
|
|
|
|
"git.diulo.com/mogfee/kit/errors"
|
|
|
|
"git.diulo.com/mogfee/kit/rest"
|
|
|
|
"git.diulo.com/mogfee/kit/rest/httpx"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type UserInfo struct {
|
|
|
|
UserId string
|
|
|
|
UserName string
|
|
|
|
UserType string
|
|
|
|
Permissions []string
|
|
|
|
UniqueId string
|
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
//1. 解析token
|
|
|
|
//2. 获取用户信息
|
|
|
|
//3. 校验权限
|
|
|
|
//4. 设置ctx
|
|
|
|
authKey := FromAuthKeyContext(ctx)
|
|
|
|
needAuth := FromNeedAuthContext(ctx)
|
|
|
|
|
|
|
|
//解析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
|
|
|
|
}
|
|
|
|
if tokenStr != "" {
|
|
|
|
if err := func() error {
|
|
|
|
res, err := tokenServer.Parse(tokenStr)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if needAuth && res == nil {
|
|
|
|
return errors.Unauthorized("TOKEN_BAD", "")
|
|
|
|
}
|
|
|
|
if authKey != "" {
|
|
|
|
if err = defaultValidate(authKey, res); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
//if userInfo.UserId != "" {
|
|
|
|
// ctx = SetUserContext(ctx, userInfo)
|
|
|
|
//}
|
|
|
|
return nil
|
|
|
|
}(); err != nil {
|
|
|
|
if needAuth {
|
|
|
|
httpx.Error(w, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errors.Forbidden("TOKEN_PERMISSION_BAD", "权限不足")
|
|
|
|
}
|