60 lines
No EOL
1.7 KiB
Go
60 lines
No EOL
1.7 KiB
Go
package repositories
|
|
|
|
import (
|
|
"database/sql"
|
|
"time"
|
|
|
|
"github.com/traefik/traefik-gui/backend/internal/models"
|
|
)
|
|
|
|
type SessionRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewSessionRepository(db *sql.DB) *SessionRepository {
|
|
return &SessionRepository{db: db}
|
|
}
|
|
|
|
func (r *SessionRepository) Create(session *models.Session) error {
|
|
_, err := r.db.Exec(
|
|
`INSERT INTO sessions (id, user_id, csrf_token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
|
|
session.ID, session.UserID, session.CSRFToken, session.CreatedAt, session.ExpiresAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (r *SessionRepository) GetByID(id string) (*models.Session, error) {
|
|
session := &models.Session{}
|
|
err := r.db.QueryRow(
|
|
`SELECT id, user_id, csrf_token, created_at, expires_at FROM sessions WHERE id = ?`, id,
|
|
).Scan(&session.ID, &session.UserID, &session.CSRFToken, &session.CreatedAt, &session.ExpiresAt)
|
|
if err == sql.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
return session, err
|
|
}
|
|
|
|
func (r *SessionRepository) Delete(id string) error {
|
|
_, err := r.db.Exec(`DELETE FROM sessions WHERE id = ?`, id)
|
|
return err
|
|
}
|
|
|
|
func (r *SessionRepository) DeleteByUserID(userID string) error {
|
|
_, err := r.db.Exec(`DELETE FROM sessions WHERE user_id = ?`, userID)
|
|
return err
|
|
}
|
|
|
|
func (r *SessionRepository) DeleteExpired() error {
|
|
_, err := r.db.Exec(`DELETE FROM sessions WHERE expires_at < ?`, time.Now())
|
|
return err
|
|
}
|
|
|
|
func (r *SessionRepository) RotateCSRFToken(id, newToken string) error {
|
|
_, err := r.db.Exec(`UPDATE sessions SET csrf_token = ? WHERE id = ?`, newToken, id)
|
|
return err
|
|
}
|
|
|
|
func (r *SessionRepository) ExtendExpiry(id string, newExpiry time.Time) error {
|
|
_, err := r.db.Exec(`UPDATE sessions SET expires_at = ? WHERE id = ?`, newExpiry, id)
|
|
return err
|
|
} |