160 lines
5.2 KiB
Go
160 lines
5.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"galo/internal/models"
|
|
"galo/internal/sqliteutil"
|
|
)
|
|
|
|
// SQLiteStore is the SQLite implementation of Repository.
|
|
type SQLiteStore struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewSQLiteStore(db *sql.DB) *SQLiteStore { return &SQLiteStore{db: db} }
|
|
|
|
const sqliteUserColumns = `id, COALESCE(email, ''), COALESCE(phone, ''), password_hash, name,
|
|
COALESCE(avatar_url, ''), COALESCE(preferences, '{}'), created_at`
|
|
|
|
func (s *SQLiteStore) CreateUser(ctx context.Context, u *models.User) error {
|
|
_, err := s.db.ExecContext(ctx,
|
|
`INSERT INTO users (id, email, phone, password_hash, name, avatar_url)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
u.ID, nullIfEmpty(u.Email), nullIfEmpty(u.Phone), u.PasswordHash, u.Name, nullIfEmpty(u.AvatarURL))
|
|
return mapUniqueViolationSQLite(err)
|
|
}
|
|
|
|
func (s *SQLiteStore) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
|
return s.scanUser(s.db.QueryRowContext(ctx,
|
|
`SELECT `+sqliteUserColumns+` FROM users WHERE lower(email) = lower($1)`, email))
|
|
}
|
|
|
|
func (s *SQLiteStore) GetUserByPhone(ctx context.Context, phone string) (*models.User, error) {
|
|
return s.scanUser(s.db.QueryRowContext(ctx,
|
|
`SELECT `+sqliteUserColumns+` FROM users WHERE phone = $1`, phone))
|
|
}
|
|
|
|
func (s *SQLiteStore) GetUserByID(ctx context.Context, id string) (*models.User, error) {
|
|
return s.scanUser(s.db.QueryRowContext(ctx,
|
|
`SELECT `+sqliteUserColumns+` FROM users WHERE id = $1`, id))
|
|
}
|
|
|
|
func (s *SQLiteStore) scanUser(row *sql.Row) (*models.User, error) {
|
|
var u models.User
|
|
var prefs, createdAt string
|
|
if err := row.Scan(&u.ID, &u.Email, &u.Phone, &u.PasswordHash, &u.Name, &u.AvatarURL, &prefs, &createdAt); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
u.CreatedAt = sqliteutil.ParseTime(createdAt)
|
|
if prefs != "" && prefs != "null" {
|
|
_ = json.Unmarshal([]byte(prefs), &u.Preferences)
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
func (s *SQLiteStore) UpdateName(ctx context.Context, userID, name string) error {
|
|
return s.requireRow(s.db.ExecContext(ctx, `UPDATE users SET name = $2 WHERE id = $1`, userID, name))
|
|
}
|
|
|
|
func (s *SQLiteStore) UpdatePasswordHash(ctx context.Context, userID, hash string) error {
|
|
return s.requireRow(s.db.ExecContext(ctx, `UPDATE users SET password_hash = $2 WHERE id = $1`, userID, hash))
|
|
}
|
|
|
|
func (s *SQLiteStore) AddIdentifier(ctx context.Context, userID, email, phone string) error {
|
|
err := s.requireRow(s.db.ExecContext(ctx,
|
|
`UPDATE users
|
|
SET email = COALESCE(NULLIF($2, ''), email),
|
|
phone = COALESCE(NULLIF($3, ''), phone)
|
|
WHERE id = $1`,
|
|
userID, email, phone))
|
|
return mapUniqueViolationSQLite(err)
|
|
}
|
|
|
|
func (s *SQLiteStore) DeleteUser(ctx context.Context, userID string) error {
|
|
return s.requireRow(s.db.ExecContext(ctx, `DELETE FROM users WHERE id = $1`, userID))
|
|
}
|
|
|
|
func (s *SQLiteStore) UpdatePreferences(ctx context.Context, userID string, raw []byte) error {
|
|
return s.requireRow(s.db.ExecContext(ctx,
|
|
`UPDATE users SET preferences = $2 WHERE id = $1`, userID, string(raw)))
|
|
}
|
|
|
|
func (s *SQLiteStore) requireRow(res sql.Result, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *SQLiteStore) CreateRefreshToken(ctx context.Context, t *models.RefreshToken) error {
|
|
_, err := s.db.ExecContext(ctx,
|
|
`INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3, $4)`,
|
|
t.ID, t.UserID, t.TokenHash, sqliteutil.FormatTime(t.ExpiresAt))
|
|
return err
|
|
}
|
|
|
|
func (s *SQLiteStore) GetRefreshToken(ctx context.Context, hash string) (*models.RefreshToken, error) {
|
|
var t models.RefreshToken
|
|
var expiresAt, createdAt string
|
|
var revokedAt sql.NullString
|
|
err := s.db.QueryRowContext(ctx,
|
|
`SELECT id, user_id, token_hash, expires_at, revoked_at, created_at
|
|
FROM refresh_tokens WHERE token_hash = $1`, hash).
|
|
Scan(&t.ID, &t.UserID, &t.TokenHash, &expiresAt, &revokedAt, &createdAt)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
t.ExpiresAt = sqliteutil.ParseTime(expiresAt)
|
|
t.CreatedAt = sqliteutil.ParseTime(createdAt)
|
|
t.RevokedAt = sqliteutil.ParseNullTime(revokedAt)
|
|
return &t, nil
|
|
}
|
|
|
|
func (s *SQLiteStore) RevokeRefreshToken(ctx context.Context, id string) error {
|
|
_, err := s.db.ExecContext(ctx,
|
|
`UPDATE refresh_tokens SET revoked_at = $2 WHERE id = $1 AND revoked_at IS NULL`,
|
|
id, sqliteutil.FormatTime(time.Now()))
|
|
return err
|
|
}
|
|
|
|
func (s *SQLiteStore) RevokeAllUserTokens(ctx context.Context, userID string) error {
|
|
_, err := s.db.ExecContext(ctx,
|
|
`UPDATE refresh_tokens SET revoked_at = $2 WHERE user_id = $1 AND revoked_at IS NULL`,
|
|
userID, sqliteutil.FormatTime(time.Now()))
|
|
return err
|
|
}
|
|
|
|
// mapUniqueViolationSQLite converts a SQLite unique constraint violation into
|
|
// the domain sentinel so the service can return a conflict for the right field.
|
|
func mapUniqueViolationSQLite(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
msg := err.Error()
|
|
if strings.Contains(msg, "UNIQUE constraint failed") {
|
|
if strings.Contains(msg, "users.phone") {
|
|
return ErrPhoneTaken
|
|
}
|
|
if strings.Contains(msg, "users.email") {
|
|
return ErrEmailTaken
|
|
}
|
|
}
|
|
return err
|
|
}
|