Merge branch 'feature/debug-token' into develop
This commit is contained in:
		
						commit
						c35e1402c3
					
				| @ -41,7 +41,7 @@ func (m *FsGuestModel) GenerateGuestID(ctx context.Context, AccessSecret uint64) | ||||
| 			Ctime:    &now, | ||||
| 			Utime:    &now, | ||||
| 		} | ||||
| 		return tx.Model(FsUserInfo{}).Create(uinfo).Error | ||||
| 		return tx.Model(&FsUserInfo{}).Create(uinfo).Error | ||||
| 	}) | ||||
| 
 | ||||
| 	if err != nil { | ||||
|  | ||||
| @ -13,6 +13,9 @@ Auth: | ||||
|     AccessExpire: 2592000 | ||||
|     RefreshAfter: 1592000 | ||||
| 
 | ||||
| Debug: | ||||
|   Password: "fusen-test-pwd" | ||||
| 
 | ||||
| OAuth: | ||||
|   google: | ||||
|     appid: "1064842923358-e94msq2glj6qr4lrva9ts3hqjjt53q8h.apps.googleusercontent.com" | ||||
|  | ||||
| @ -16,6 +16,11 @@ type Config struct { | ||||
| 	MainAddress   string | ||||
| 	WebsocketAddr string | ||||
| 
 | ||||
| 	Debug struct { | ||||
| 		Password string | ||||
| 	} | ||||
| 	//   Password: "fusen-test-pwd" | ||||
| 
 | ||||
| 	OAuth struct { | ||||
| 		Google struct { | ||||
| 			Appid  string | ||||
|  | ||||
| @ -27,6 +27,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { | ||||
| 				Path:    "/api/auth/accept-cookie", | ||||
| 				Handler: AcceptCookieHandler(serverCtx), | ||||
| 			}, | ||||
| 			{ | ||||
| 				Method:  http.MethodPost, | ||||
| 				Path:    "/api/auth/debug/token/create", | ||||
| 				Handler: UserDebugTokenHandler(serverCtx), | ||||
| 			}, | ||||
| 			{ | ||||
| 				Method:  http.MethodGet, | ||||
| 				Path:    "/api/auth/oauth2/login/google", | ||||
|  | ||||
							
								
								
									
										35
									
								
								server/auth/internal/handler/userdebugtokenhandler.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								server/auth/internal/handler/userdebugtokenhandler.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,35 @@ | ||||
| package handler | ||||
| 
 | ||||
| import ( | ||||
| 	"net/http" | ||||
| 	"reflect" | ||||
| 
 | ||||
| 	"fusenapi/utils/basic" | ||||
| 
 | ||||
| 	"fusenapi/server/auth/internal/logic" | ||||
| 	"fusenapi/server/auth/internal/svc" | ||||
| 	"fusenapi/server/auth/internal/types" | ||||
| ) | ||||
| 
 | ||||
| func UserDebugTokenHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { | ||||
| 	return func(w http.ResponseWriter, r *http.Request) { | ||||
| 
 | ||||
| 		var req types.RequestUserDebug | ||||
| 		userinfo, err := basic.RequestParse(w, r, svcCtx, &req) | ||||
| 		if err != nil { | ||||
| 			return | ||||
| 		} | ||||
| 
 | ||||
| 		// 创建一个业务逻辑层实例 | ||||
| 		l := logic.NewUserDebugTokenLogic(r.Context(), svcCtx) | ||||
| 
 | ||||
| 		rl := reflect.ValueOf(l) | ||||
| 		basic.BeforeLogic(w, r, rl) | ||||
| 
 | ||||
| 		resp := l.UserDebugToken(&req, userinfo) | ||||
| 
 | ||||
| 		if !basic.AfterLogic(w, r, rl, resp) { | ||||
| 			basic.NormalAfterLogic(w, r, resp) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										63
									
								
								server/auth/internal/logic/userdebugtokenlogic.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										63
									
								
								server/auth/internal/logic/userdebugtokenlogic.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,63 @@ | ||||
| package logic | ||||
| 
 | ||||
| import ( | ||||
| 	"fusenapi/utils/auth" | ||||
| 	"fusenapi/utils/basic" | ||||
| 	"time" | ||||
| 
 | ||||
| 	"context" | ||||
| 
 | ||||
| 	"fusenapi/server/auth/internal/svc" | ||||
| 	"fusenapi/server/auth/internal/types" | ||||
| 
 | ||||
| 	"github.com/zeromicro/go-zero/core/logx" | ||||
| ) | ||||
| 
 | ||||
| type UserDebugTokenLogic struct { | ||||
| 	logx.Logger | ||||
| 	ctx    context.Context | ||||
| 	svcCtx *svc.ServiceContext | ||||
| } | ||||
| 
 | ||||
| func NewUserDebugTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDebugTokenLogic { | ||||
| 	return &UserDebugTokenLogic{ | ||||
| 		Logger: logx.WithContext(ctx), | ||||
| 		ctx:    ctx, | ||||
| 		svcCtx: svcCtx, | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| // 处理进入前逻辑w,r | ||||
| // func (l *UserDebugTokenLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { | ||||
| // } | ||||
| 
 | ||||
| func (l *UserDebugTokenLogic) UserDebugToken(req *types.RequestUserDebug, userinfo *auth.UserInfo) (resp *basic.Response) { | ||||
| 	// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) | ||||
| 	// userinfo 传入值时, 一定不为null | ||||
| 	if req.Password != l.svcCtx.Config.Debug.Password { | ||||
| 		return resp.SetStatusAddMessage(basic.CodeApiErr, "密码错误") | ||||
| 	} | ||||
| 	var accessExpire int64 = 3600 | ||||
| 	if req.Exp != nil { | ||||
| 		accessExpire = *req.Exp | ||||
| 	} | ||||
| 
 | ||||
| 	debug := &auth.Debug{ | ||||
| 		IsCache:          req.IsCache, | ||||
| 		IsAllTemplateTag: req.IsAllTemplateTag, | ||||
| 	} | ||||
| 
 | ||||
| 	dtoken, err := auth.GenerateBaseJwtTokenUint64(auth.DefaultDebugJwtSecret, accessExpire, time.Now().UTC().Unix(), debug) | ||||
| 	if err != nil { | ||||
| 		return resp.SetStatusWithMessage(basic.CodeApiErr, "GenerateBaseJwtTokenUint64错误") | ||||
| 	} | ||||
| 
 | ||||
| 	return resp.SetStatus(basic.CodeOK, map[string]any{ | ||||
| 		"debug_token": dtoken, | ||||
| 	}) | ||||
| } | ||||
| 
 | ||||
| // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 | ||||
| // func (l *UserDebugTokenLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { | ||||
| // // httpx.OkJsonCtx(r.Context(), w, resp) | ||||
| // } | ||||
| @ -5,6 +5,13 @@ import ( | ||||
| 	"fusenapi/utils/basic" | ||||
| ) | ||||
| 
 | ||||
| type RequestUserDebug struct { | ||||
| 	Password         string `json:"password"`            // 密码,内部使用都是明文 | ||||
| 	Exp              *int64 `json:"exp"`                 // 过期时间, 不发默认一天 | ||||
| 	IsCache          int64  `json:"is_cache"`            // 是否缓存 | ||||
| 	IsAllTemplateTag int64  `json:"is_all_template_tag"` // 是开启全部模板 | ||||
| } | ||||
| 
 | ||||
| type RequestAuthDelete struct { | ||||
| 	Email string `json:"email"` | ||||
| } | ||||
| @ -90,10 +97,10 @@ type File struct { | ||||
| } | ||||
| 
 | ||||
| type Meta struct { | ||||
| 	TotalCount  int64 `json:"totalCount"` | ||||
| 	PageCount   int64 `json:"pageCount"` | ||||
| 	CurrentPage int   `json:"currentPage"` | ||||
| 	PerPage     int   `json:"perPage"` | ||||
| 	TotalCount  int64 `json:"total_count"` | ||||
| 	PageCount   int64 `json:"page_count"` | ||||
| 	CurrentPage int   `json:"current_page"` | ||||
| 	PerPage     int   `json:"per_page"` | ||||
| } | ||||
| 
 | ||||
| // Set 设置Response的Code和Message值 | ||||
|  | ||||
| @ -22,6 +22,10 @@ service auth { | ||||
| 	@handler AcceptCookieHandler | ||||
| 	post /api/auth/accept-cookie(request) returns (response); | ||||
| 	 | ||||
| 	// 获取测试链接 | ||||
| 	@handler UserDebugTokenHandler | ||||
| 	post /api/auth/debug/token/create(RequestUserDebug) returns (response); | ||||
| 	 | ||||
| 	// 谷歌第三方登录 | ||||
| 	@handler UserGoogleLoginHandler | ||||
| 	get /api/auth/oauth2/login/google(RequestGoogleLogin) returns (response); | ||||
| @ -52,6 +56,12 @@ service auth { | ||||
| } | ||||
| 
 | ||||
| type ( | ||||
| 	RequestUserDebug { | ||||
| 		Password         string `json:"password"`            // 密码,内部使用都是明文 | ||||
| 		Exp              *int64 `json:"exp"`                 // 过期时间, 不发默认一天 | ||||
| 		IsCache          int64  `json:"is_cache"`            // 是否缓存 | ||||
| 		IsAllTemplateTag int64  `json:"is_all_template_tag"` // 是开启全部模板 | ||||
| 	} | ||||
| 
 | ||||
| 	// RequestAuthDelete 用于debug | ||||
| 	RequestAuthDelete { | ||||
|  | ||||
| @ -7,17 +7,19 @@ import ( | ||||
| 	"fmt" | ||||
| 	"log" | ||||
| 	"net/http" | ||||
| 	"reflect" | ||||
| 	"strings" | ||||
| ) | ||||
| 
 | ||||
| var DefaultJwtSecret uint64 = 21321321321 | ||||
| var DefaultDebugJwtSecret uint64 = 3285631123 | ||||
| 
 | ||||
| func ParseJwtTokenHeader[T any](r *http.Request) (string, *T, error) { | ||||
| func ParseJwtTokenWithHeader[T any](header string, r *http.Request) (string, *T, error) { | ||||
| 	//TODO: | ||||
| 	// var u T | ||||
| 	// return "", &u, nil | ||||
| 
 | ||||
| 	AuthKey := r.Header.Get("Authorization") | ||||
| 	AuthKey := r.Header.Get(header) | ||||
| 	if AuthKey == "" { | ||||
| 		return "", nil, nil | ||||
| 	} | ||||
| @ -107,3 +109,69 @@ func TParseJwtTokenHeader[T any](AuthKey string) (string, *T, error) { | ||||
| 
 | ||||
| 	// return nil, errors.New(fmt.Sprint("Invalid token", err)) | ||||
| } | ||||
| 
 | ||||
| func ParseDebugJwtTokenWithHeader(header string, r *http.Request) (*Debug, error) { | ||||
| 
 | ||||
| 	AuthKey := r.Header.Get(header) | ||||
| 	if AuthKey == "" { | ||||
| 		return nil, nil | ||||
| 	} | ||||
| 	if len(AuthKey) <= 15 { | ||||
| 		return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) | ||||
| 	} | ||||
| 	// AuthKey = AuthKey[7:] 如果没有Bearer | ||||
| 
 | ||||
| 	claims, err := ParseJwtTokenUint64Secret(AuthKey, DefaultDebugJwtSecret) | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
| 	} | ||||
| 
 | ||||
| 	var debug Debug | ||||
| 	// 使用反射获取 Debug 结构体的类型和值 | ||||
| 	debugType := reflect.TypeOf(debug) | ||||
| 	debugValue := reflect.ValueOf(&debug).Elem() | ||||
| 
 | ||||
| 	// 遍历 Debug 结构体的字段 | ||||
| 	for i := 0; i < debugType.NumField(); i++ { | ||||
| 		field := debugType.Field(i) | ||||
| 		tag := field.Tag.Get("json") | ||||
| 
 | ||||
| 		// 在 MapClaims 中查找对应的值 | ||||
| 		value, ok := claims[tag] | ||||
| 		if !ok { | ||||
| 			return nil, fmt.Errorf("`%s` tag is not exists", tag) | ||||
| 		} | ||||
| 
 | ||||
| 		// 使用反射设置字段的值 | ||||
| 		fieldValue := debugValue.Field(i) | ||||
| 
 | ||||
| 		switch fieldValue.Kind() { | ||||
| 		case reflect.String: | ||||
| 			fieldValue.SetString(value.(string)) | ||||
| 		case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64: | ||||
| 			fieldValue.SetInt(int64(value.(float64))) | ||||
| 		case reflect.Bool: | ||||
| 			fieldValue.SetBool(value.(bool)) | ||||
| 		case reflect.Ptr: // 处理指针类型 | ||||
| 			if fieldValue.IsNil() { // 检查指针是否为零值 | ||||
| 				newValue := reflect.New(fieldValue.Type().Elem()) // 创建新的指针值 | ||||
| 				fieldValue.Set(newValue)                          // 将新值设置为字段的值 | ||||
| 			} | ||||
| 			elemValue := fieldValue.Elem() | ||||
| 			switch elemValue.Kind() { | ||||
| 			case reflect.String: | ||||
| 				elemValue.SetString(value.(string)) | ||||
| 			case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64: | ||||
| 				elemValue.SetInt(int64(value.(float64))) | ||||
| 			case reflect.Bool: | ||||
| 				elemValue.SetBool(value.(bool)) | ||||
| 			default: | ||||
| 				return nil, fmt.Errorf("`%s` type is not supported", elemValue.Kind()) | ||||
| 			} | ||||
| 		default: | ||||
| 			return nil, fmt.Errorf("`%s` type is not supported", fieldValue.Kind()) | ||||
| 		} | ||||
| 	} | ||||
| 
 | ||||
| 	return &debug, nil | ||||
| } | ||||
|  | ||||
| @ -6,6 +6,8 @@ import ( | ||||
| 	"encoding/binary" | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
| 	"log" | ||||
| 	"reflect" | ||||
| 
 | ||||
| 	"github.com/golang-jwt/jwt" | ||||
| 	"github.com/zeromicro/go-zero/core/logx" | ||||
| @ -22,10 +24,19 @@ const ( | ||||
| 	IDTYPE_Guest IDTYPE = 2 | ||||
| ) | ||||
| 
 | ||||
| // Debug 相关的结构 | ||||
| type Debug struct { | ||||
| 	Exp              *int64 `json:"exp"` | ||||
| 	IsCache          int64  `json:"is_cache"`            // 是否缓存 | ||||
| 	IsAllTemplateTag int64  `json:"is_all_template_tag"` // 是开启全部模板 | ||||
| } | ||||
| 
 | ||||
| // UserInfo 用户的信息 | ||||
| type UserInfo struct { | ||||
| 	UserId  int64 `json:"user_id"` | ||||
| 	GuestId int64 `json:"guest_id"` | ||||
| 	Exp     int64 `json:"exp"` //截止有效时间 | ||||
| 	UserId  int64  `json:"user_id"` | ||||
| 	GuestId int64  `json:"guest_id"` | ||||
| 	Exp     int64  `json:"exp"` //截止有效时间 | ||||
| 	Debug   *Debug `json:"debug,omitempty"` | ||||
| } | ||||
| 
 | ||||
| // GetIdType 用户确认用户身份类型 | ||||
| @ -161,6 +172,46 @@ func GenerateJwtTokenUint64(AccessSecret uint64, accessExpire, nowSec int64, use | ||||
| 	return token.SignedString(key) | ||||
| } | ||||
| 
 | ||||
| // GenerateBaseJwtTokenUint64 网站jwt token生成 | ||||
| func GenerateBaseJwtTokenUint64(AccessSecret uint64, accessExpire int64, nowSec int64, myclaims any) (string, error) { | ||||
| 
 | ||||
| 	claims := make(jwt.MapClaims) | ||||
| 	claims["exp"] = nowSec + accessExpire | ||||
| 	claims["iat"] = nowSec | ||||
| 
 | ||||
| 	// if userid == 0 && guestid == 0 { | ||||
| 	// 	err := errors.New("userid and guestid cannot be 0 at the same time") | ||||
| 	// 	logx.Error(err) | ||||
| 	// 	return "", err | ||||
| 	// } | ||||
| 
 | ||||
| 	// 使用反射获取 MyClaims 结构体的类型和值 | ||||
| 	myclaimsType := reflect.TypeOf(myclaims) | ||||
| 	if myclaimsType.Kind() != reflect.Ptr { | ||||
| 		log.Println(myclaimsType.Kind()) | ||||
| 		panic("myclaimsType must be ptr") | ||||
| 	} | ||||
| 	myclaimsType = myclaimsType.Elem() | ||||
| 	myclaimsValue := reflect.ValueOf(myclaims).Elem() | ||||
| 
 | ||||
| 	// 遍历 MyClaims 结构体的字段 | ||||
| 	for i := 0; i < myclaimsType.NumField(); i++ { | ||||
| 		field := myclaimsType.Field(i) | ||||
| 		tag := field.Tag.Get("json") | ||||
| 		value := myclaimsValue.Field(i).Interface() | ||||
| 		// 将字段值赋给 claims 对象的相应键 | ||||
| 		claims[tag] = value | ||||
| 	} | ||||
| 
 | ||||
| 	token := jwt.New(jwt.SigningMethodHS256) | ||||
| 	token.Claims = claims | ||||
| 
 | ||||
| 	key := make([]byte, 8) | ||||
| 	binary.BigEndian.PutUint64(key, AccessSecret) | ||||
| 
 | ||||
| 	return token.SignedString(key) | ||||
| } | ||||
| 
 | ||||
| // GenerateJwtToken 网站jwt token生成 | ||||
| func GenerateJwtToken(accessSecret *string, accessExpire, nowSec int64, userid int64, guestid int64) (string, error) { | ||||
| 	claims := make(jwt.MapClaims) | ||||
|  | ||||
| @ -3,12 +3,38 @@ package auth | ||||
| import ( | ||||
| 	"crypto/sha256" | ||||
| 	"encoding/base64" | ||||
| 	"encoding/json" | ||||
| 	"fmt" | ||||
| 	"log" | ||||
| 	"net/http" | ||||
| 	"testing" | ||||
| 	"time" | ||||
| ) | ||||
| 
 | ||||
| func TestCase(t *testing.T) { | ||||
| 	info := &UserInfo{ | ||||
| 		UserId: 1, | ||||
| 	} | ||||
| 	log.Println(info) | ||||
| 	data, _ := json.Marshal(info) | ||||
| 	log.Println(string(data)) | ||||
| 
 | ||||
| 	a := `{"user_id":0,"guest_id":1,"exp":0, "debug": { "exp": 12321213321}}` | ||||
| 	err := json.Unmarshal([]byte(a), info) | ||||
| 	log.Println(err) | ||||
| 	log.Printf("%#v %v", info, info.Debug) | ||||
| 
 | ||||
| 	// now := time.Now().UTC().Unix() | ||||
| 	v, err := GenerateBaseJwtTokenUint64(DefaultDebugJwtSecret, time.Now().UTC().Unix(), 3600, info.Debug) | ||||
| 	log.Println(v, err) | ||||
| 	d, err := ParseDebugJwtTokenWithHeader("Debug-Token", &http.Request{ | ||||
| 		Header: http.Header{ | ||||
| 			"Debug-Token": []string{v}, | ||||
| 		}, | ||||
| 	}) | ||||
| 	log.Println(d, err) | ||||
| } | ||||
| 
 | ||||
| // TestGenJwt 测试jwt序列化 | ||||
| func TestGenJwt(t *testing.T) { | ||||
| 	now := time.Now().UTC().Unix() | ||||
|  | ||||
| @ -117,10 +117,10 @@ var ( | ||||
| ) | ||||
| 
 | ||||
| type Response struct { | ||||
| 	rewriteHandlerFunc http.HandlerFunc | ||||
| 	Code               int         `json:"code"` | ||||
| 	Message            string      `json:"msg"` | ||||
| 	Data               interface{} `json:"data"` | ||||
| 	Code    int         `json:"code"` | ||||
| 	Message string      `json:"msg"` | ||||
| 	Data    interface{} `json:"data"` | ||||
| 	Debug   interface{} `json:"debug"` // debug的相关数据 | ||||
| } | ||||
| 
 | ||||
| // Set 设置Response的Code和Message值 | ||||
| @ -273,22 +273,3 @@ func RequestFileParse(r *http.Request, req any) error { | ||||
| 
 | ||||
| 	return nil | ||||
| } | ||||
| 
 | ||||
| // RewriteHandler | ||||
| func (resp *Response) SetRewriteHandler(do http.HandlerFunc) *Response { | ||||
| 	resp = &Response{ | ||||
| 		Code: 304, | ||||
| 	} | ||||
| 	resp.rewriteHandlerFunc = do | ||||
| 	return resp | ||||
| } | ||||
| 
 | ||||
| // RewriteHandler | ||||
| func (resp *Response) rewriteHandler(w http.ResponseWriter, r *http.Request) { | ||||
| 	resp.rewriteHandlerFunc(w, r) | ||||
| } | ||||
| 
 | ||||
| // Set 设置Response的Code和Message值 | ||||
| func (resp *Response) isRewriteHandler() bool { | ||||
| 	return resp.rewriteHandlerFunc != nil | ||||
| } | ||||
|  | ||||
| @ -61,7 +61,13 @@ func ParseJwtToken(r *http.Request, svcCtx any) (*auth.UserInfo, error) { | ||||
| 	// userId, err := strconv.ParseInt(token, 10, 64) | ||||
| 
 | ||||
| 	var secret uint64 = 0 | ||||
| 	token, info, err := auth.ParseJwtTokenHeader[auth.UserInfo](r) //解析Token头, 和payload信息 | ||||
| 	token, info, err := auth.ParseJwtTokenWithHeader[auth.UserInfo]("Authorization", r) //解析Token头, 和payload信息 | ||||
| 	if err != nil { | ||||
| 		logx.Error(err) | ||||
| 		return nil, err | ||||
| 	} | ||||
| 
 | ||||
| 	debugInfo, err := auth.ParseDebugJwtTokenWithHeader("Debug-Token", r) //解析Token头, 和payload信息 | ||||
| 	if err != nil { | ||||
| 		logx.Error(err) | ||||
| 		return nil, err | ||||
| @ -115,6 +121,10 @@ func ParseJwtToken(r *http.Request, svcCtx any) (*auth.UserInfo, error) { | ||||
| 		userinfo = &auth.UserInfo{UserId: 0, GuestId: 0} | ||||
| 	} | ||||
| 
 | ||||
| 	if debugInfo != nil { | ||||
| 		userinfo.Debug = debugInfo | ||||
| 	} | ||||
| 
 | ||||
| 	return userinfo, nil | ||||
| } | ||||
| 
 | ||||
| @ -130,6 +140,8 @@ func RequestParse(w http.ResponseWriter, r *http.Request, svcCtx any, LogicReque | ||||
| 		return nil, err | ||||
| 	} | ||||
| 
 | ||||
| 	// Debug-Token | ||||
| 
 | ||||
| 	// 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 | ||||
| 	if err = httpx.Parse(r, LogicRequest); err != nil { | ||||
| 		httpx.OkJsonCtx(r.Context(), w, &Response{ | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user