backend/app/zeus/service/lark/internal/model/user_token.go

48 lines
1.1 KiB
Go

package model
import (
"git.icechen.cn/monorepo/backend/pkg/orm"
"github.com/gofiber/fiber/v2/utils"
"gorm.io/gorm"
"time"
)
// TokenEffectiveTime token有效时长
const TokenEffectiveTime = time.Hour * 2
type UserToken struct {
gorm.Model
Token string `json:"token" gorm:"token;uniqueIndex"`
ExpiresTime time.Time `json:"expires_time" gorm:"expires_time"`
UserInfoID uint `json:"user_info_id" gorm:"user_info_id"`
}
func (UserToken) TableName() string {
return "user_token"
}
// CreateToken 创建Token
func CreateToken(userInfoID uint) (string, error) {
userToken := UserToken{
Token: genToken(),
ExpiresTime: time.Now().Add(TokenEffectiveTime),
UserInfoID: userInfoID,
}
err := orm.DB.Where("user_info_id = ?", userInfoID).
Assign(UserToken{UserInfoID: userInfoID}).
FirstOrCreate(&userToken).Error
return userToken.Token, err
}
func genToken() string {
return utils.UUIDv4()
}
// GetToken 根据token获取token对象
func GetToken(token string) (UserToken, error) {
userToken := UserToken{}
err := orm.DB.Where("token = ? AND expires_time < ?", token, time.Now()).
First(&userToken).Error
return userToken, err
}