56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package token
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type SQLiteTokenStore struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
type Token struct {
|
|
TokenID string `gorm:"primaryKey"`
|
|
UserID int64 `gorm:"index"`
|
|
Expiration time.Time `gorm:"index"`
|
|
}
|
|
|
|
// NewSQLiteTokenStore creates a new SQLiteTokenStore with the given GORM DB instance.
|
|
// Actually can be used for any GORM-supported database.
|
|
func NewSQLiteTokenStore(db *gorm.DB) (*SQLiteTokenStore, error) {
|
|
if db == nil {
|
|
return nil, fmt.Errorf("db is nil")
|
|
}
|
|
return &SQLiteTokenStore{
|
|
db: db,
|
|
}, nil
|
|
}
|
|
|
|
func (s *SQLiteTokenStore) revoke(tokenID string, expiresAt time.Time) error {
|
|
return s.db.Create(&Token{
|
|
TokenID: tokenID,
|
|
Expiration: expiresAt,
|
|
}).Error
|
|
}
|
|
|
|
func (s *SQLiteTokenStore) isRevoked(tokenID string) (bool, error) {
|
|
var count int64
|
|
err := s.db.Model(&Token{}).Where("token_id = ?", tokenID).Count(&count).Error
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return count > 0, nil
|
|
}
|
|
|
|
func (s *SQLiteTokenStore) init() error {
|
|
// AutoMigrate models
|
|
err := s.db.AutoMigrate(&Token{})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to migrate Token model: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|