forked from mtusi2026/mtusi2026lab3
59 lines
2.4 KiB
Go
59 lines
2.4 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
|
)
|
|
|
|
// CreateUser inserts a profile and enforces uniqueness inside PostgreSQL.
|
|
func (s *Store) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
|
|
return s.Register(ctx, user, "")
|
|
}
|
|
|
|
// Register atomically stores a profile and its password hash.
|
|
func (s *Store) Register(ctx context.Context, user dto.UserDTO, passwordHash string) (dto.UserDTO, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash)
|
|
VALUES(@id,@username,@display_name,@password_hash) RETURNING created_at`, pgx.StrictNamedArgs{
|
|
"id": user.ID,
|
|
"username": user.Username,
|
|
"display_name": user.DisplayName,
|
|
"password_hash": passwordHash,
|
|
}).Scan(&user.CreatedAt)
|
|
return user, normalize(err)
|
|
}
|
|
|
|
// User reads a profile without credentials.
|
|
func (s *Store) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var user dto.UserDTO
|
|
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at FROM users WHERE id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
|
return user, normalize(err)
|
|
}
|
|
|
|
// Credentials reads the account needed for password verification.
|
|
func (s *Store) Credentials(ctx context.Context, username string) (dto.UserDTO, string, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var user dto.UserDTO
|
|
var hash string
|
|
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=@username`, pgx.StrictNamedArgs{"username": username}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
|
return user, hash, normalize(err)
|
|
}
|
|
|
|
// UsersExist checks all distinct requested identifiers in one bounded query.
|
|
func (s *Store) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var exists bool
|
|
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT id FROM unnest(@ids::uuid[]) AS requested(id)
|
|
WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id=requested.id))`, pgx.StrictNamedArgs{"ids": ids}).Scan(&exists)
|
|
return exists, normalize(err)
|
|
}
|