Files
online-backend/internal/identity/auth/db/postgresql.go
GuwandykA 514b9ca5fc Add forgot-password SMS reset, client/staff user lists, and regenerate Swagger.
Fold follow-up migrations into init, expose GET /users/clients and /users/staff, and refresh seed data.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 16:42:47 +05:00

252 lines
6.9 KiB
Go
Executable File

package db
import (
"context"
"errors"
"strings"
"unicode"
"online-back/internal/identity/auth"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Repository {
return &repository{
client: client,
logger: logger,
}
}
const (
loginByNameQuery = `
SELECT id, password FROM users
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
OR LOWER(TRIM(username)) = LOWER(TRIM($1))
LIMIT 1`
loginByPhoneQuery = `
SELECT id, password FROM users
WHERE phone = $1
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)
LIMIT 1`
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
FROM users WHERE id = $1`
)
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
phone := strings.TrimSpace(dto.Phone)
if phone != "" {
normalized := phone
if n, err := auth.NormalizePhone(phone); err == nil {
normalized = n
}
var result auth.UserCredentials
err := r.client.QueryRow(ctx, loginByPhoneQuery, normalized, digitString(phone)).Scan(&result.Id, &result.Password)
return result, err
}
var result auth.UserCredentials
err := r.client.QueryRow(ctx, loginByNameQuery, strings.TrimSpace(dto.Name)).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredentials, error) {
var result auth.UserCredentials
err := r.client.QueryRow(ctx, userByIDQuery, id).Scan(&result.Id, &result.Password)
return result, err
}
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
return profile, err
}
const updateProfileQuery = `
UPDATE users SET
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $6
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, updateProfileQuery,
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return auth.UserProfileDTO{}, err
}
return profile, err
}
func (r *repository) UserExists(ctx context.Context, username, phone string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1 FROM users
WHERE LOWER(username) = LOWER($1)
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2
)`
var exists bool
err := r.client.QueryRow(ctx, query, username, digitString(phone)).Scan(&exists)
return exists, err
}
func (r *repository) UsernameTaken(ctx context.Context, username, exceptPhone string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1 FROM registration_verifications
WHERE LOWER(username) = LOWER($1) AND phone <> $2
)`
var taken bool
err := r.client.QueryRow(ctx, query, username, exceptPhone).Scan(&taken)
return taken, err
}
const upsertVerificationQuery = `
INSERT INTO registration_verifications (name, username, phone, password, code_hash, attempts, expires_at)
VALUES ($1, $2, $3, $4, $5, 0, $6)
ON CONFLICT (phone) DO UPDATE SET
name = EXCLUDED.name,
username = EXCLUDED.username,
password = EXCLUDED.password,
code_hash = EXCLUDED.code_hash,
attempts = 0,
expires_at = EXCLUDED.expires_at,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`
func (r *repository) UpsertVerification(ctx context.Context, v auth.Verification) error {
_, err := r.client.Exec(ctx, upsertVerificationQuery,
v.Name, v.Username, v.Phone, v.Password, v.CodeHash, v.ExpiresAt,
)
return err
}
const getVerificationQuery = `
SELECT id, name, username, phone, password, code_hash, attempts, expires_at
FROM registration_verifications
WHERE phone = $1`
func (r *repository) GetVerificationByPhone(ctx context.Context, phone string) (auth.Verification, error) {
var v auth.Verification
err := r.client.QueryRow(ctx, getVerificationQuery, phone).Scan(
&v.ID, &v.Name, &v.Username, &v.Phone, &v.Password, &v.CodeHash, &v.Attempts, &v.ExpiresAt,
)
return v, err
}
func (r *repository) IncrementVerifyAttempts(ctx context.Context, id int64) error {
_, err := r.client.Exec(ctx, `
UPDATE registration_verifications
SET attempts = attempts + 1, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $1`, id)
return err
}
func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verification) (int, error) {
tx, err := r.client.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)
var userID int
err = tx.QueryRow(ctx, `
INSERT INTO users (name, username, phone, password, role, active, email)
VALUES ($1, $2, $3, $4, 'user', true, '')
RETURNING id`,
v.Name, v.Username, v.Phone, v.Password,
).Scan(&userID)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return 0, auth.ErrConflict
}
return 0, err
}
if _, err := tx.Exec(ctx, `DELETE FROM registration_verifications WHERE id = $1`, v.ID); err != nil {
return 0, err
}
if err := tx.Commit(ctx); err != nil {
return 0, err
}
return userID, nil
}
func (r *repository) GetUserByName(ctx context.Context, name string) (auth.UserIdentity, error) {
const query = `
SELECT id, name, username, phone FROM users
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
LIMIT 1`
var user auth.UserIdentity
err := r.client.QueryRow(ctx, query, name).Scan(&user.Id, &user.Name, &user.Username, &user.Phone)
if errors.Is(err, pgx.ErrNoRows) {
return auth.UserIdentity{}, auth.ErrNotFound
}
return user, err
}
func (r *repository) CompletePasswordReset(ctx context.Context, userID int, verificationID int64, passwordHash string) error {
tx, err := r.client.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
tag, err := tx.Exec(ctx, `
UPDATE users SET
password = $1,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $2`, passwordHash, userID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return auth.ErrNotFound
}
if _, err := tx.Exec(ctx, `DELETE FROM registration_verifications WHERE id = $1`, verificationID); err != nil {
return err
}
return tx.Commit(ctx)
}
func digitString(s string) string {
var b strings.Builder
for _, r := range s {
if unicode.IsDigit(r) {
b.WriteRune(r)
}
}
return b.String()
}