180 lines
5.2 KiB
Go
180 lines
5.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"galo/internal/models"
|
|
)
|
|
|
|
var ErrNotFound = errors.New("not found")
|
|
|
|
// ErrEmailTaken and ErrPhoneTaken are returned when a unique constraint on the
|
|
// corresponding identifier is violated, so callers can map a race to the same
|
|
// conflict code as the pre-flight existence check.
|
|
var (
|
|
ErrEmailTaken = errors.New("email taken")
|
|
ErrPhoneTaken = errors.New("phone taken")
|
|
)
|
|
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
|
|
|
|
const userColumns = `id, COALESCE(email, ''), COALESCE(phone, ''), password_hash, name,
|
|
COALESCE(avatar_url, ''), COALESCE(preferences, '{}'::jsonb)::text, created_at`
|
|
|
|
func (s *Store) CreateUser(ctx context.Context, u *models.User) error {
|
|
_, err := s.pool.Exec(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 mapUniqueViolation(err)
|
|
}
|
|
|
|
func (s *Store) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
|
return s.scanUser(s.pool.QueryRow(ctx,
|
|
`SELECT `+userColumns+` FROM users WHERE lower(email) = lower($1)`, email))
|
|
}
|
|
|
|
func (s *Store) GetUserByPhone(ctx context.Context, phone string) (*models.User, error) {
|
|
return s.scanUser(s.pool.QueryRow(ctx,
|
|
`SELECT `+userColumns+` FROM users WHERE phone = $1`, phone))
|
|
}
|
|
|
|
func (s *Store) GetUserByID(ctx context.Context, id string) (*models.User, error) {
|
|
return s.scanUser(s.pool.QueryRow(ctx,
|
|
`SELECT `+userColumns+` FROM users WHERE id = $1`, id))
|
|
}
|
|
|
|
func (s *Store) scanUser(row pgx.Row) (*models.User, error) {
|
|
var u models.User
|
|
var prefs string
|
|
if err := row.Scan(&u.ID, &u.Email, &u.Phone, &u.PasswordHash, &u.Name, &u.AvatarURL, &prefs, &u.CreatedAt); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
if prefs != "" && prefs != "null" {
|
|
_ = json.Unmarshal([]byte(prefs), &u.Preferences)
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
func (s *Store) UpdateName(ctx context.Context, userID, name string) error {
|
|
tag, err := s.pool.Exec(ctx, `UPDATE users SET name = $2 WHERE id = $1`, userID, name)
|
|
return requireRow(tag, err)
|
|
}
|
|
|
|
func (s *Store) UpdatePasswordHash(ctx context.Context, userID, hash string) error {
|
|
tag, err := s.pool.Exec(ctx, `UPDATE users SET password_hash = $2 WHERE id = $1`, userID, hash)
|
|
return requireRow(tag, err)
|
|
}
|
|
|
|
func (s *Store) AddIdentifier(ctx context.Context, userID, email, phone string) error {
|
|
tag, err := s.pool.Exec(ctx,
|
|
`UPDATE users
|
|
SET email = COALESCE(NULLIF($2, ''), email),
|
|
phone = COALESCE(NULLIF($3, ''), phone)
|
|
WHERE id = $1`,
|
|
userID, email, phone)
|
|
if err != nil {
|
|
return mapUniqueViolation(err)
|
|
}
|
|
return requireRow(tag, nil)
|
|
}
|
|
|
|
func (s *Store) DeleteUser(ctx context.Context, userID string) error {
|
|
tag, err := s.pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, userID)
|
|
return requireRow(tag, err)
|
|
}
|
|
|
|
func (s *Store) UpdatePreferences(ctx context.Context, userID string, raw []byte) error {
|
|
tag, err := s.pool.Exec(ctx,
|
|
`UPDATE users SET preferences = $2::jsonb WHERE id = $1`, userID, string(raw))
|
|
return requireRow(tag, err)
|
|
}
|
|
|
|
func (s *Store) CreateRefreshToken(ctx context.Context, t *models.RefreshToken) error {
|
|
_, err := s.pool.Exec(ctx,
|
|
`INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3, $4)`,
|
|
t.ID, t.UserID, t.TokenHash, t.ExpiresAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (s *Store) GetRefreshToken(ctx context.Context, hash string) (*models.RefreshToken, error) {
|
|
var t models.RefreshToken
|
|
err := s.pool.QueryRow(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, &t.ExpiresAt, &t.RevokedAt, &t.CreatedAt)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &t, nil
|
|
}
|
|
|
|
func (s *Store) RevokeRefreshToken(ctx context.Context, id string) error {
|
|
_, err := s.pool.Exec(ctx,
|
|
`UPDATE refresh_tokens SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL`, id)
|
|
return err
|
|
}
|
|
|
|
func (s *Store) RevokeAllUserTokens(ctx context.Context, userID string) error {
|
|
_, err := s.pool.Exec(ctx,
|
|
`UPDATE refresh_tokens SET revoked_at = now() WHERE user_id = $1 AND revoked_at IS NULL`, userID)
|
|
return err
|
|
}
|
|
|
|
func nullIfEmpty(s string) *string {
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
return &s
|
|
}
|
|
|
|
type commandTag interface {
|
|
RowsAffected() int64
|
|
}
|
|
|
|
func requireRow(tag commandTag, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// mapUniqueViolation converts a PostgreSQL unique constraint violation into the
|
|
// domain sentinel so the service can return a conflict for the right field.
|
|
func mapUniqueViolation(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
if strings.Contains(pgErr.ConstraintName, "phone") {
|
|
return ErrPhoneTaken
|
|
}
|
|
return ErrEmailTaken
|
|
}
|
|
return err
|
|
}
|