All checks were successful
ci/woodpecker/push/build Pipeline was successful
Signed-off-by: Nikolai Rodionov <allanger@badhouseplants.net>
76 lines
1.9 KiB
Go
76 lines
1.9 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
|
|
"github.com/jackc/pgerrcode"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
var (
|
|
ErrAlreadyExists = errors.New("entry already exists")
|
|
ErrNotFound = errors.New("entry not found")
|
|
)
|
|
|
|
type AccountData struct {
|
|
UUID string
|
|
Email string
|
|
PasswordHash string
|
|
}
|
|
|
|
// CreateAccount adds a new account to a database
|
|
func CreateAccount(ctx context.Context, db *sql.DB, account *AccountData) error {
|
|
query := "INSERT INTO accounts (uuid, email, password_hash) VALUES ($1, $2, $3)"
|
|
|
|
if _, err := db.ExecContext(ctx, query, account.UUID, account.Email, account.PasswordHash); err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
if pgErr.Code == pgerrcode.UniqueViolation {
|
|
return ErrAlreadyExists
|
|
}
|
|
return err
|
|
}
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetPasswordHashForEmail returns the password hash for a user
|
|
func GetPasswordHashForEmail(ctx context.Context, db *sql.DB, email string) (hash string, err error) {
|
|
query := "SELECT password_hash FROM accounts WHERE email = $1;"
|
|
if err = db.QueryRowContext(ctx, query, email).Scan(&hash); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return "", ErrNotFound
|
|
}
|
|
return
|
|
}
|
|
return
|
|
}
|
|
|
|
// GetUUIDForEmail returns a uuid of a user
|
|
func GetUUIDForEmail(ctx context.Context, db *sql.DB, email string) (uuid string, err error) {
|
|
query := "SELECT uuid FROM accounts WHERE email = $1;"
|
|
if err = db.QueryRow(query, email).Scan(&uuid); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return "", ErrNotFound
|
|
}
|
|
return
|
|
}
|
|
return
|
|
}
|
|
|
|
// IsAccountExist checks if an account with a UUID exists in the db
|
|
func IsAccountExist(ctx context.Context, db *sql.DB, uuid string) (bool, error) {
|
|
exists := false
|
|
err := db.QueryRowContext(
|
|
ctx,
|
|
`SELECT EXISTS(
|
|
SELECT 1 FROM accounts WHERE uuid = $1
|
|
)`,
|
|
uuid,
|
|
).Scan(&exists)
|
|
return exists, err
|
|
}
|