69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Repository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewRepository(db *sql.DB) *Repository {
|
|
return &Repository{db: db}
|
|
}
|
|
|
|
var ErrEmailTaken = errors.New("email already registered")
|
|
|
|
func (r *Repository) CreateUser(ctx context.Context, email, passwordHash, name string) (User, error) {
|
|
user := User{ID: uuid.New(), Email: strings.ToLower(strings.TrimSpace(email)), Name: strings.TrimSpace(name)}
|
|
_, err := r.db.ExecContext(ctx, `
|
|
INSERT INTO users (id, email, password_hash, name)
|
|
VALUES ($1, $2, $3, $4)
|
|
`, user.ID, user.Email, passwordHash, user.Name)
|
|
if err != nil {
|
|
if strings.Contains(strings.ToLower(err.Error()), "unique") {
|
|
return User{}, ErrEmailTaken
|
|
}
|
|
return User{}, fmt.Errorf("create user: %w", err)
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
func (r *Repository) FindByEmail(ctx context.Context, email string) (storedUser, error) {
|
|
var user storedUser
|
|
err := r.db.QueryRowContext(ctx, `
|
|
SELECT id, email, name, password_hash
|
|
FROM users
|
|
WHERE lower(email) = lower($1)
|
|
`, strings.TrimSpace(email)).Scan(&user.ID, &user.Email, &user.Name, &user.PasswordHash)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return storedUser{}, sql.ErrNoRows
|
|
}
|
|
if err != nil {
|
|
return storedUser{}, fmt.Errorf("find user by email: %w", err)
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
func (r *Repository) FindByID(ctx context.Context, id uuid.UUID) (User, error) {
|
|
var user User
|
|
err := r.db.QueryRowContext(ctx, `
|
|
SELECT id, email, name
|
|
FROM users
|
|
WHERE id = $1
|
|
`, id).Scan(&user.ID, &user.Email, &user.Name)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return User{}, sql.ErrNoRows
|
|
}
|
|
if err != nil {
|
|
return User{}, fmt.Errorf("find user by id: %w", err)
|
|
}
|
|
return user, nil
|
|
}
|