77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package repository
|
|
|
|
import (
|
|
"ssq-desk/internal/database"
|
|
"ssq-desk/internal/storage/models"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// AuthRepository 授权数据访问接口
|
|
type AuthRepository interface {
|
|
Create(auth *models.Authorization) error
|
|
Update(auth *models.Authorization) error
|
|
GetByLicenseCode(licenseCode string) (*models.Authorization, error)
|
|
GetByDeviceID(deviceID string) (*models.Authorization, error)
|
|
}
|
|
|
|
// SQLiteAuthRepository SQLite 授权数据访问实现
|
|
type SQLiteAuthRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewSQLiteAuthRepository 创建 SQLite 授权数据访问实例
|
|
func NewSQLiteAuthRepository() (AuthRepository, error) {
|
|
db := database.GetSQLite()
|
|
if db == nil {
|
|
return nil, gorm.ErrInvalidDB
|
|
}
|
|
|
|
// 自动迁移
|
|
err := db.AutoMigrate(&models.Authorization{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &SQLiteAuthRepository{db: db}, nil
|
|
}
|
|
|
|
// Create 创建授权记录
|
|
func (r *SQLiteAuthRepository) Create(auth *models.Authorization) error {
|
|
now := time.Now()
|
|
if auth.CreatedAt.IsZero() {
|
|
auth.CreatedAt = now
|
|
}
|
|
if auth.UpdatedAt.IsZero() {
|
|
auth.UpdatedAt = now
|
|
}
|
|
return r.db.Create(auth).Error
|
|
}
|
|
|
|
// Update 更新授权记录
|
|
func (r *SQLiteAuthRepository) Update(auth *models.Authorization) error {
|
|
auth.UpdatedAt = time.Now()
|
|
return r.db.Save(auth).Error
|
|
}
|
|
|
|
// GetByLicenseCode 根据授权码查询
|
|
func (r *SQLiteAuthRepository) GetByLicenseCode(licenseCode string) (*models.Authorization, error) {
|
|
var auth models.Authorization
|
|
err := r.db.Where("license_code = ?", licenseCode).First(&auth).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &auth, nil
|
|
}
|
|
|
|
// GetByDeviceID 根据设备ID查询
|
|
func (r *SQLiteAuthRepository) GetByDeviceID(deviceID string) (*models.Authorization, error) {
|
|
var auth models.Authorization
|
|
err := r.db.Where("device_id = ? AND status = ?", deviceID, 1).First(&auth).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &auth, nil
|
|
}
|