You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.7 KiB
64 lines
1.7 KiB
3 weeks ago
|
package repository
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"time"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type CaptchaRepository interface {
|
||
|
Create(ctx context.Context, captchaID, captchaText string, expiresAt time.Time) error
|
||
|
Get(ctx context.Context, captchaID string) (string, error)
|
||
|
Delete(ctx context.Context, captchaID string) error
|
||
|
CleanExpired(ctx context.Context) error
|
||
|
}
|
||
|
|
||
|
type captchaRepository struct {
|
||
|
db *gorm.DB
|
||
|
}
|
||
|
|
||
|
type Captcha struct {
|
||
|
ID string `gorm:"primarykey;size:32" json:"id"`
|
||
|
Text string `gorm:"size:10;not null" json:"-"`
|
||
|
ExpiresAt time.Time `gorm:"not null;index" json:"expires_at"`
|
||
|
CreatedAt time.Time `gorm:"not null" json:"created_at"`
|
||
|
}
|
||
|
|
||
|
func NewCaptchaRepository(db *gorm.DB) CaptchaRepository {
|
||
|
return &captchaRepository{
|
||
|
db: db,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (r *captchaRepository) Create(ctx context.Context, captchaID, captchaText string, expiresAt time.Time) error {
|
||
|
captcha := &Captcha{
|
||
|
ID: captchaID,
|
||
|
Text: captchaText,
|
||
|
ExpiresAt: expiresAt,
|
||
|
CreatedAt: time.Now(),
|
||
|
}
|
||
|
|
||
|
return r.db.WithContext(ctx).Create(captcha).Error
|
||
|
}
|
||
|
|
||
|
func (r *captchaRepository) Get(ctx context.Context, captchaID string) (string, error) {
|
||
|
var captcha Captcha
|
||
|
err := r.db.WithContext(ctx).Where("id = ? AND expires_at > ?", captchaID, time.Now()).First(&captcha).Error
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
// 获取后立即删除,确保一次性使用
|
||
|
r.db.WithContext(ctx).Delete(&captcha)
|
||
|
|
||
|
return captcha.Text, nil
|
||
|
}
|
||
|
|
||
|
func (r *captchaRepository) Delete(ctx context.Context, captchaID string) error {
|
||
|
return r.db.WithContext(ctx).Where("id = ?", captchaID).Delete(&Captcha{}).Error
|
||
|
}
|
||
|
|
||
|
func (r *captchaRepository) CleanExpired(ctx context.Context) error {
|
||
|
return r.db.WithContext(ctx).Where("expires_at <= ?", time.Now()).Delete(&Captcha{}).Error
|
||
|
}
|