80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
package repo
|
|
|
|
import (
|
|
"admin/apps/user/model"
|
|
"admin/internal/errcode"
|
|
"admin/lib/tokenlib"
|
|
"errors"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
"time"
|
|
)
|
|
|
|
type ITokenRepo interface {
|
|
GetToken(token string) (*model.Token, bool, error)
|
|
GetTokenByUserId(userId int) (*model.Token, bool, error)
|
|
CreateToken(userId int, dura time.Duration) (*model.Token, error)
|
|
DeleteToken(token string) error
|
|
DeleteTokenByUserId(userId int) error
|
|
}
|
|
|
|
func NewTokenRepo(db *gorm.DB) ITokenRepo {
|
|
return &tokenRepoImpl{db: db}
|
|
}
|
|
|
|
type tokenRepoImpl struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func (impl *tokenRepoImpl) GetToken(token string) (*model.Token, bool, error) {
|
|
info := &model.Token{}
|
|
err := impl.db.Where("token = ?", token).First(info).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return info, false, nil
|
|
}
|
|
return nil, false, err
|
|
}
|
|
return info, true, nil
|
|
}
|
|
|
|
func (impl *tokenRepoImpl) GetTokenByUserId(userId int) (*model.Token, bool, error) {
|
|
info := &model.Token{}
|
|
err := impl.db.Where("user_id = ?", userId).First(info).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return info, false, nil
|
|
}
|
|
return nil, false, err
|
|
}
|
|
return info, true, nil
|
|
}
|
|
|
|
func (impl *tokenRepoImpl) CreateToken(userId int, dura time.Duration) (*model.Token, error) {
|
|
tokenStr, err := tokenlib.GenToken(userId, dura)
|
|
if err != nil {
|
|
return nil, errcode.New(errcode.ServerError, "gen token for user:%v error:%v", userId, err)
|
|
}
|
|
po := &model.Token{
|
|
Token: tokenStr,
|
|
UserId: userId,
|
|
ExpireAt: time.Now().Add(dura),
|
|
}
|
|
err = impl.db.Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "user_id"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"token", "expire_at"}),
|
|
}).Create(po).Error
|
|
if err != nil {
|
|
return nil, errcode.New(errcode.DBError, "save token for user:%v error:%v", po, err)
|
|
}
|
|
return po, err
|
|
}
|
|
|
|
func (impl *tokenRepoImpl) DeleteToken(token string) error {
|
|
return impl.db.Where("token = ?", token).Unscoped().Delete(new(model.Token)).Error
|
|
}
|
|
|
|
func (impl *tokenRepoImpl) DeleteTokenByUserId(userId int) error {
|
|
return impl.db.Where("user_id = ?", userId).Unscoped().Delete(new(model.Token)).Error
|
|
}
|