debug toekn

This commit is contained in:
eson
2023-10-17 17:25:48 +08:00
parent a1e0c7c5f5
commit e00dc9f3cf
12 changed files with 299 additions and 33 deletions

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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()