package db import ( "context" "database/sql" "encoding/json" "errors" "strings" "unicode" "online-back/internal/identity/auth" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" "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))) AND deleted_at IS NULL LIMIT 1` loginByPhoneQuery = ` SELECT id, password FROM users WHERE (phone = $1 OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)) AND deleted_at IS NULL LIMIT 1` userByIDQuery = `SELECT id, password FROM users WHERE id = $1 AND deleted_at IS NULL` ) const profileFromClause = ` FROM users u LEFT JOIN LATERAL ( SELECT ru.role_id FROM role_user ru WHERE ru.user_id = u.id AND ru.deleted_at IS NULL ORDER BY ru.id LIMIT 1 ) ru ON true LEFT JOIN roles r ON r.id = ru.role_id AND r.deleted_at IS NULL` const profileBranchesJSON = `COALESCE(( SELECT json_agg(jsonb_build_object( 'id', b.id, 'uniqueCode', COALESCE(b.unique_code, ''), 'name', b.name ) ORDER BY b.id) FROM ( SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name FROM branch_user bu JOIN branches b ON b.id = bu.branch_id WHERE bu.user_id = u.id AND bu.deleted_at IS NULL AND b.deleted_at IS NULL ORDER BY b.id ) b ), '[]'::json)` const profilePermissionsJSON = `COALESCE(( SELECT json_agg(jsonb_build_object( 'id', p.id, 'code', COALESCE(p.code, ''), 'name', p.name, 'guardName', p.guard_name, 'module', COALESCE(p.module, '') ) ORDER BY p.module, p.id) FROM permissions p WHERE p.deleted_at IS NULL AND EXISTS ( SELECT 1 FROM permission_role pr WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL ) ), '[]'::json)` const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at, r.id, r.code, r.name, r.guard_name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1 AND u.deleted_at IS NULL` 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) { return scanProfile(r.client.QueryRow(ctx, profileQuery, id)) } 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 AND deleted_at IS NULL` func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) { tag, err := r.client.Exec(ctx, updateProfileQuery, dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id, ) if err != nil { return auth.UserProfileDTO{}, err } if tag.RowsAffected() == 0 { return auth.UserProfileDTO{}, pgx.ErrNoRows } return r.GetProfile(ctx, id) } func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) { var profile auth.UserProfileDTO var roleID sql.NullInt64 var roleCode, roleName, roleGuard sql.NullString var branchesJSON []byte var permissionsJSON []byte err := row.Scan( &profile.Id, &profile.Name, &profile.FirstName, &profile.LastName, &profile.Phone, &profile.Avatar, &profile.CreatedAt, &roleID, &roleCode, &roleName, &roleGuard, &branchesJSON, &permissionsJSON, ) if err != nil { return auth.UserProfileDTO{}, err } if roleID.Valid { profile.Role = &auth.ProfileRoleDTO{ Id: roleID.Int64, Code: roleCode.String, Name: roleName.String, GuardName: roleGuard.String, } } profile.Branches = []auth.ProfileBranchDTO{} if len(branchesJSON) > 0 && string(branchesJSON) != "null" { if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil { return auth.UserProfileDTO{}, err } } profile.Permissions = []auth.ProfilePermissionDTO{} if len(permissionsJSON) > 0 && string(permissionsJSON) != "null" { if err := json.Unmarshal(permissionsJSON, &profile.Permissions); err != nil { return auth.UserProfileDTO{}, err } } profile.Modules = auth.GroupProfileModules(profile.Permissions) return profile, nil } 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) AND deleted_at IS NULL )` 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 } tag, err := tx.Exec(ctx, ` INSERT INTO role_user (role_id, user_id) SELECT r.id, $1 FROM roles r WHERE r.code = 'user'`, userID) if err != nil { return 0, err } if tag.RowsAffected() == 0 { return 0, errors.New(`role "user" not found`) } 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)) AND deleted_at IS NULL 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 AND deleted_at IS NULL`, 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() }