package auth import ( "context" "errors" "fmt" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) // User is the application-side view of a row in the users table. type User struct { ID uuid.UUID Email string PasswordHash *string // nil for OIDC-only accounts OIDCSubject *string OIDCIssuer *string DisplayName *string } // ErrUserNotFound is returned when no user matches the query. var ErrUserNotFound = errors.New("user not found") // UserStore wraps database access for the users table. type UserStore struct { pool *pgxpool.Pool } // NewUserStore constructs a UserStore backed by the given pool. func NewUserStore(pool *pgxpool.Pool) *UserStore { return &UserStore{pool: pool} } // CreateUser inserts a new user with a password hash (email/password accounts). // It returns the created user. Email uniqueness violations surface as ErrEmailTaken. var ErrEmailTaken = errors.New("email already registered") func (s *UserStore) CreateUser(ctx context.Context, email, passwordHash, displayName string) (User, error) { const q = ` INSERT INTO users (email, password_hash, display_name) VALUES ($1, $2, NULLIF($3, '')) RETURNING id, email, password_hash, oidc_subject, oidc_issuer, display_name` var u User var dn *string err := s.pool.QueryRow(ctx, q, email, passwordHash, displayName). Scan(&u.ID, &u.Email, &u.PasswordHash, &u.OIDCSubject, &u.OIDCIssuer, &dn) if err != nil { if isUniqueViolation(err) { return User{}, fmt.Errorf("%w: %s", ErrEmailTaken, email) } return User{}, fmt.Errorf("create user: %w", err) } u.DisplayName = dn return u, nil } // GetUserByEmail loads a user by its (case-sensitive) email address. func (s *UserStore) GetUserByEmail(ctx context.Context, email string) (User, error) { const q = ` SELECT id, email, password_hash, oidc_subject, oidc_issuer, display_name FROM users WHERE email = $1` var u User var dn *string err := s.pool.QueryRow(ctx, q, email). Scan(&u.ID, &u.Email, &u.PasswordHash, &u.OIDCSubject, &u.OIDCIssuer, &dn) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return User{}, ErrUserNotFound } return User{}, fmt.Errorf("get user by email: %w", err) } u.DisplayName = dn return u, nil } // GetUserByID loads a user by its primary key. func (s *UserStore) GetUserByID(ctx context.Context, id uuid.UUID) (User, error) { const q = ` SELECT id, email, password_hash, oidc_subject, oidc_issuer, display_name FROM users WHERE id = $1` var u User var dn *string err := s.pool.QueryRow(ctx, q, id). Scan(&u.ID, &u.Email, &u.PasswordHash, &u.OIDCSubject, &u.OIDCIssuer, &dn) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return User{}, ErrUserNotFound } return User{}, fmt.Errorf("get user by id: %w", err) } u.DisplayName = dn return u, nil }