feat: openid login

This commit is contained in:
zzw
2026-09-02 17:37:12 +08:00
parent 540f74f9b7
commit bb14f9e324
38 changed files with 1627 additions and 1091 deletions
+67 -49
View File
@@ -2,76 +2,94 @@ package utils
import (
"errors"
"github.com/golang-jwt/jwt/v4"
"fmt"
"strconv"
"time"
"github.com/golang-jwt/jwt/v4"
)
type Jwt struct {
const (
TokenTypeAccess = "access"
TokenTypeRefresh = "refresh"
)
type JWT struct {
Secret string
Ttl int
TTL int
Issuer string
}
type JwtInfo struct {
Id int `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id"`
NickName string `json:"nick_name"`
DepartmentId int `gorm:"column:department_id;type:int(11);default:0;comment:部门ID" json:"department_id"`
PostId int `gorm:"column:post_id;type:int(11);default:0;comment:岗位ID;NOT NULL" json:"post_id"`
LastTime CustomTime `gorm:"column:last_time;type:datetime;comment:最后一次登录时间" json:"last_time"`
func NewJWT(secret, issuer string, ttlSeconds int) (*JWT, error) {
if secret == "" {
return nil, errors.New("jwt secret empty")
}
if ttlSeconds < 1 {
return nil, errors.New("jwt ttl invalid")
}
return &JWT{
Secret: secret,
TTL: ttlSeconds,
Issuer: issuer,
}, nil
}
type Claims struct {
UserID int64 `json:"user_id"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Mobile string `json:"mobile"`
Gender uint8 `json:"gender"`
Birthday string `json:"birthday"`
Type uint8 `json:"type"` // 1销售 2门店 3普通用户
ClientCode string `json:"client_code"`
SaleId int64 `json:"sale_id,omitempty"`
StoreId int64 `json:"store_id,omitempty"`
TokenType string `json:"token_type"` // access | refresh
jwt.RegisteredClaims
}
type Token struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
func (j *JWT) Sign(claims Claims) (string, error) {
if j == nil {
return "", errors.New("jwt not initialized")
}
now := time.Now()
claims.Issuer = j.Issuer
claims.IssuedAt = jwt.NewNumericDate(now)
claims.ExpiresAt = jwt.NewNumericDate(now.Add(time.Duration(j.TTL) * time.Second))
claims.ID = strconv.FormatInt(claims.UserID, NumberTen)
// GetToken 获取token
//
// access is true 获取登录token
// access is false 获取置换token
func (j *Jwt) GetToken(user JwtInfo, access bool) (string, error) {
j.setJwtConfig(access)
// 创建 Claims
user.Issuer = j.Issuer
user.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Duration(j.Ttl) * time.Second)) // 过期时间
user.ID = strconv.Itoa(user.Id)
// 生成token对象
token := jwt.NewWithClaims(jwt.SigningMethodHS256, user)
// 生成签名字符串
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(j.Secret))
}
// ParseToken 校验token
//
// access is true 校验登录token
// access is false 校验置换token
func (j *Jwt) ParseToken(tokenString string, access bool) (*JwtInfo, error) {
j.setJwtConfig(access)
// 解析token
token, err := jwt.ParseWithClaims(tokenString, &JwtInfo{}, func(token *jwt.Token) (interface{}, error) {
func (j *JWT) Parse(tokenString string) (*Claims, error) {
if j == nil {
return nil, errors.New("jwt not initialized")
}
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(j.Secret), nil
})
if err != nil { // 解析token失败
if err != nil {
return nil, err
}
//对token对象中的Claim进行类型断言
claims, ok := token.Claims.(*JwtInfo)
if ok && token.Valid { // 校验token
claims.LastTime = Now()
return claims, nil
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, errors.New("invalid token")
}
return nil, errors.New("is check false")
return claims, nil
}
func (j *Jwt) setJwtConfig(access bool) {
j.Ttl = GetConfigInt("jwt.access_ttl")
j.Issuer = GetConfigString("jwt.issuer")
j.Secret = GetConfigString("jwt.access_secret")
if !access {
j.Ttl = GetConfigInt("jwt.refresh_ttl")
j.Secret = GetConfigString("jwt.refresh_secret")
func (j *JWT) ParseExpect(tokenString, expectType string) (*Claims, error) {
claims, err := j.Parse(tokenString)
if err != nil {
return nil, err
}
if claims.TokenType != expectType {
return nil, fmt.Errorf("unexpected token type: %s", claims.TokenType)
}
return claims, nil
}