This commit is contained in:
eson
2023-07-24 17:22:06 +08:00
parent 7ec78d1c35
commit a10e100364
23 changed files with 1004 additions and 137 deletions

View File

@@ -68,6 +68,11 @@ type BackendUserInfo struct {
DepartmentId int64 `json:"department_id"`
}
type OAuthInfo struct {
Id int64 `json:"id"`
Platform string `json:"platform"`
}
// 获取登录信息
func GetUserInfoFormMapClaims(claims jwt.MapClaims) (*UserInfo, error) {
userinfo := &UserInfo{}
@@ -195,3 +200,79 @@ func CheckValueRange[T comparable](v T, rangevalues ...T) bool {
}
return false
}
// GenerateRegisterToken 网站注册 token生成
func GenerateRegisterToken(accessSecret *string, accessExpire, nowSec int64, id int64, platform string) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = nowSec + accessExpire
claims["iat"] = nowSec
if id == 0 {
err := errors.New("userid and guestid cannot be 0 at the same time")
logx.Error(err)
return "", err
}
claims["id"] = id
claims["platform"] = platform
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(*accessSecret))
}
// GetRegisterFormMapClaims 获取注册唯一token标识登录信息
func GetRegisterFormMapClaims(claims jwt.MapClaims) (*OAuthInfo, error) {
oauthinfo := &OAuthInfo{}
if userid, ok := claims["id"]; ok {
uid, ok := userid.(float64)
if !ok {
err := errors.New(fmt.Sprint("parse uid form context err:", userid))
logx.Error("parse uid form context err:", err)
return nil, err
}
oauthinfo.Id = int64(uid)
} else {
err := errors.New(`id not in claims`)
logx.Error(`id not in claims`)
return nil, err
}
if splatform, ok := claims["id"]; ok {
platform, ok := splatform.(string)
if !ok {
err := errors.New(fmt.Sprint("parse uid form context err:", platform))
logx.Error("parse uid form context err:", err)
return nil, err
}
oauthinfo.Platform = platform
} else {
err := errors.New(`id not in claims`)
logx.Error(`id not in claims`)
return nil, err
}
return oauthinfo, nil
}
func getRegisterJwtClaims(Token string, AccessSecret *string) (jwt.MapClaims, error) {
token, err := jwt.Parse(Token, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return []byte(*AccessSecret), nil
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}