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>
This commit is contained in:
2026-08-14 16:42:47 +05:00
parent 5e3c46da83
commit 514b9ca5fc
24 changed files with 1477 additions and 473 deletions

View File

@@ -27,15 +27,35 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
}
const (
loginQuery = `SELECT id, password FROM users WHERE email = $1`
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, loginQuery, dto.Email).Scan(&result.Id, &result.Password)
err := r.client.QueryRow(ctx, loginByNameQuery, strings.TrimSpace(dto.Name)).Scan(&result.Id, &result.Password)
return result, err
}
@@ -180,6 +200,46 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
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 {

View File

@@ -3,7 +3,8 @@ package auth
import "time"
type LoginDTO struct {
Email string `json:"email" binding:"required"`
Name string `json:"name"`
Phone string `json:"phone"`
Password string `json:"password" binding:"required"`
}
@@ -47,6 +48,24 @@ type VerifyDTO struct {
Code string `json:"code" binding:"required,len=6"`
}
type ForgotPasswordDTO struct {
Name string `json:"name" binding:"required"`
}
type ResetPasswordDTO struct {
Name string `json:"name" binding:"required"`
Code string `json:"code" binding:"required,len=6"`
Password string `json:"password" binding:"required,min=6"`
PasswordConfirm string `json:"passwordConfirm" binding:"required"`
}
type UserIdentity struct {
Id int
Name string
Username string
Phone string
}
type RegisterResult struct {
Phone string `json:"phone"`
ExpiresIn int `json:"expiresIn"`

View File

@@ -15,11 +15,13 @@ import (
)
const (
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
registerURL = "/register"
verifyURL = "/register/verify"
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
registerURL = "/register"
verifyURL = "/register/verify"
forgotPasswordURL = "/forgot-password"
resetPasswordURL = "/forgot-password/verify"
)
type handler struct {
@@ -37,6 +39,8 @@ func (h *handler) Register(router *gin.RouterGroup) {
router.POST(tokenURL, h.refreshToken)
router.POST(registerURL, h.register)
router.POST(verifyURL, h.verify)
router.POST(forgotPasswordURL, h.forgotPassword)
router.POST(resetPasswordURL, h.resetPassword)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
@@ -45,7 +49,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// login godoc
// @Summary Login
// @Description Authenticates a user by email and password
// @Description Authenticates a user by name or phone, and password
// @Tags auth
// @Accept json
// @Produce json
@@ -62,7 +66,12 @@ func (h *handler) login(c *gin.Context) {
}
tokenPair, err := h.service.Login(c.Request.Context(), dto)
if errors.Is(err, ErrInvalidInput) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if errors.Is(err, ErrInvalidCredentials) {
h.logger.Warnf("login failed for name=%q phone=%q: %v", dto.Name, dto.Phone, err)
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
@@ -128,12 +137,68 @@ func (h *handler) verify(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
// forgotPassword godoc
// @Summary Forgot password
// @Description Finds the user by name and sends an SMS verification code
// @Tags auth
// @Accept json
// @Produce json
// @Param body body ForgotPasswordDTO true "Forgot password payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /forgot-password [post]
func (h *handler) forgotPassword(c *gin.Context) {
var dto ForgotPasswordDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.service.ForgotPassword(c.Request.Context(), dto)
if err != nil {
h.respondRegisterError(c, err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// resetPassword godoc
// @Summary Reset password
// @Description Confirms the SMS code and sets a new password
// @Tags auth
// @Accept json
// @Produce json
// @Param body body ResetPasswordDTO true "Reset password payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /forgot-password/verify [post]
func (h *handler) resetPassword(c *gin.Context) {
var dto ResetPasswordDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
tokenPair, err := h.service.ResetPassword(c.Request.Context(), dto)
if err != nil {
h.respondRegisterError(c, err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
func (h *handler) respondRegisterError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrPasswordMismatch):
c.JSON(http.StatusBadRequest, appresult.ErrPasswordMismatch)
case errors.Is(err, ErrInvalidPhone), errors.Is(err, ErrInvalidInput):
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
case errors.Is(err, ErrNotFound):
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
case errors.Is(err, ErrConflict):
c.JSON(http.StatusConflict, appresult.ErrConflict)
case errors.Is(err, ErrInvalidCode):

View File

@@ -2,6 +2,7 @@ package auth
import (
"fmt"
"strconv"
"strings"
"unicode"
)
@@ -16,19 +17,30 @@ func onlyDigits(s string) string {
return b.String()
}
// NormalizePhone accepts Turkmen numbers in common local forms and
// returns +993 6X XX XX XX.
// NormalizePhone strips a leading +993 / 993 country code, then checks
// that the remaining local number is 8 digits with prefix 61–65 or 71–72.
// It returns +993 XX XX XX XX.
func NormalizePhone(raw string) (string, error) {
digits := onlyDigits(raw)
switch {
case strings.HasPrefix(digits, "993") && len(digits) == 11:
if strings.HasPrefix(digits, "993") {
digits = digits[3:]
case len(digits) == 9 && digits[0] == '8':
} else if len(digits) == 9 && digits[0] == '8' {
digits = digits[1:]
}
if len(digits) != 8 {
return "", ErrInvalidPhone
}
if !validMobilePrefix(digits[:2]) {
return "", ErrInvalidPhone
}
return fmt.Sprintf("+993 %s %s %s %s", digits[0:2], digits[2:4], digits[4:6], digits[6:8]), nil
}
func validMobilePrefix(prefix string) bool {
n, err := strconv.Atoi(prefix)
if err != nil {
return false
}
return (n >= 61 && n <= 65) || (n >= 71 && n <= 72)
}

View File

@@ -6,6 +6,7 @@ func TestNormalizePhone(t *testing.T) {
tests := []struct {
in, want string
}{
{"+99361531216", "+993 61 53 12 16"},
{"+993 61 92 92 48", "+993 61 92 92 48"},
{"+99361929248", "+993 61 92 92 48"},
{"99361929248", "+993 61 92 92 48"},
@@ -26,4 +27,22 @@ func TestNormalizePhone(t *testing.T) {
if _, err := NormalizePhone("123"); err != ErrInvalidPhone {
t.Errorf("NormalizePhone(123) error = %v, want ErrInvalidPhone", err)
}
validPrefixes := []string{"61", "62", "63", "64", "65", "71", "72"}
for _, prefix := range validPrefixes {
in := prefix + "929248"
if _, err := NormalizePhone(in); err != nil {
t.Errorf("NormalizePhone(%q) unexpected error: %v", in, err)
}
}
invalid := []string{
"60929248", "66929248", "70929248", "73929248", "81929248",
"+99366531216", "+99360929248",
}
for _, in := range invalid {
if _, err := NormalizePhone(in); err != ErrInvalidPhone {
t.Errorf("NormalizePhone(%q) error = %v, want ErrInvalidPhone", in, err)
}
}
}

View File

@@ -28,6 +28,7 @@ var (
ErrInvalidPhone = errors.New("invalid phone number")
ErrInvalidCode = errors.New("invalid or expired verification code")
ErrInvalidInput = errors.New("required parameter is missing or invalid")
ErrNotFound = errors.New("not found")
)
type Service struct {
@@ -40,13 +41,31 @@ func NewService(repository Repository, sender sms.Sender) *Service {
}
func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) {
user, err := s.repository.Login(ctx, dto)
if err != nil {
return nil, ErrInvalidCredentials
name := strings.TrimSpace(dto.Name)
phone := strings.TrimSpace(dto.Phone)
normalized, err := NormalizePhone(phone)
if err == nil {
dto.Phone = normalized
dto.Name = ""
} else {
dto.Phone = ""
dto.Name = name
if dto.Name == "" {
return nil, ErrInvalidInput
}
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
return nil, ErrInvalidCredentials
user, err := s.repository.Login(ctx, dto)
if err != nil {
return nil, fmt.Errorf("%w: user not found", ErrInvalidCredentials)
}
password := strings.TrimSpace(dto.Password)
if err := bcrypt.CompareHashAndPassword([]byte(strings.TrimSpace(user.Password)), []byte(password)); err != nil {
if user.Password != password {
return nil, fmt.Errorf("%w: password mismatch", ErrInvalidCredentials)
}
}
return utils.GenerateTokenPair(user.Id)
@@ -108,40 +127,112 @@ func (s *Service) Register(ctx context.Context, dto RegisterDTO) (RegisterResult
return RegisterResult{}, err
}
code := localOTP
// Production: replace the line above with generateOTP().
// code, err := generateOTP()
// if err != nil {
// return RegisterResult{}, err
// }
codeHash, err := bcrypt.GenerateFromPassword([]byte(code), bcrypt.DefaultCost)
if err != nil {
return RegisterResult{}, err
}
expiresAt := time.Now().UTC().Add(otpTTL)
if err := s.repository.UpsertVerification(ctx, Verification{
Name: name,
Username: username,
Phone: phone,
Password: string(hashedPassword),
CodeHash: string(codeHash),
ExpiresAt: expiresAt,
if err := s.storeAndSendOTP(ctx, Verification{
Name: name,
Username: username,
Phone: phone,
Password: string(hashedPassword),
}); err != nil {
return RegisterResult{}, err
}
if err := s.sms.Send(ctx, phone, fmt.Sprintf(otpMessageTm, code)); err != nil {
return RegisterResult{}, err
}
return RegisterResult{
Phone: phone,
ExpiresIn: int(otpTTL.Seconds()),
}, nil
}
func (s *Service) ForgotPassword(ctx context.Context, dto ForgotPasswordDTO) (RegisterResult, error) {
name := strings.TrimSpace(dto.Name)
if name == "" {
return RegisterResult{}, ErrInvalidInput
}
user, err := s.repository.GetUserByName(ctx, name)
if err != nil {
return RegisterResult{}, err
}
if strings.TrimSpace(user.Phone) == "" {
return RegisterResult{}, ErrInvalidPhone
}
if err := s.storeAndSendOTP(ctx, Verification{
Name: user.Name,
Username: user.Username,
Phone: user.Phone,
}); err != nil {
return RegisterResult{}, err
}
return RegisterResult{
Phone: user.Phone,
ExpiresIn: int(otpTTL.Seconds()),
}, nil
}
func (s *Service) ResetPassword(ctx context.Context, dto ResetPasswordDTO) (map[string]string, error) {
if dto.Password != dto.PasswordConfirm {
return nil, ErrPasswordMismatch
}
name := strings.TrimSpace(dto.Name)
if name == "" {
return nil, ErrInvalidInput
}
user, err := s.repository.GetUserByName(ctx, name)
if err != nil {
return nil, err
}
v, err := s.repository.GetVerificationByPhone(ctx, user.Phone)
if err != nil {
return nil, ErrInvalidCode
}
if v.Attempts >= maxVerifyTries || time.Now().UTC().After(v.ExpiresAt) {
return nil, ErrInvalidCode
}
if err := bcrypt.CompareHashAndPassword([]byte(v.CodeHash), []byte(strings.TrimSpace(dto.Code))); err != nil {
_ = s.repository.IncrementVerifyAttempts(ctx, v.ID)
return nil, ErrInvalidCode
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
if err := s.repository.CompletePasswordReset(ctx, user.Id, v.ID, string(hashedPassword)); err != nil {
return nil, err
}
return utils.GenerateTokenPair(user.Id)
}
func (s *Service) storeAndSendOTP(ctx context.Context, v Verification) error {
code := localOTP
// Production: replace the line above with generateOTP().
// code, err := generateOTP()
// if err != nil {
// return err
// }
codeHash, err := bcrypt.GenerateFromPassword([]byte(code), bcrypt.DefaultCost)
if err != nil {
return err
}
v.CodeHash = string(codeHash)
v.ExpiresAt = time.Now().UTC().Add(otpTTL)
if err := s.repository.UpsertVerification(ctx, v); err != nil {
return err
}
return s.sms.Send(ctx, v.Phone, fmt.Sprintf(otpMessageTm, code))
}
func (s *Service) Verify(ctx context.Context, dto VerifyDTO) (map[string]string, error) {
phone, err := NormalizePhone(dto.Phone)
if err != nil {
@@ -167,7 +258,7 @@ func (s *Service) Verify(ctx context.Context, dto VerifyDTO) (map[string]string,
return nil, err
}
return utils.GenerateUserTokenPair(userID)
return utils.GenerateTokenPair(userID)
}
// Production: uncomment generateOTP and add imports "crypto/rand" and "math/big".

View File

@@ -16,10 +16,19 @@ type fakeRepo struct {
verification Verification
getErr error
userID int
userByName UserIdentity
userByNameErr error
loginUser UserCredentials
loginErr error
lastLogin LoginDTO
}
func (f *fakeRepo) Login(context.Context, LoginDTO) (UserCredentials, error) {
return UserCredentials{}, errors.New("not implemented")
func (f *fakeRepo) Login(_ context.Context, dto LoginDTO) (UserCredentials, error) {
f.lastLogin = dto
if f.loginErr != nil {
return UserCredentials{}, f.loginErr
}
return f.loginUser, nil
}
func (f *fakeRepo) GetUserByID(context.Context, int) (UserCredentials, error) {
return UserCredentials{}, errors.New("not implemented")
@@ -50,6 +59,15 @@ func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error {
func (f *fakeRepo) CompleteRegistration(context.Context, Verification) (int, error) {
return f.userID, nil
}
func (f *fakeRepo) GetUserByName(context.Context, string) (UserIdentity, error) {
if f.userByNameErr != nil {
return UserIdentity{}, f.userByNameErr
}
return f.userByName, nil
}
func (f *fakeRepo) CompletePasswordReset(context.Context, int, int64, string) error {
return nil
}
type fakeSMS struct {
phone, message string
@@ -72,6 +90,54 @@ func validRegisterDTO() RegisterDTO {
}
}
func TestLoginRequiresNameOrPhone(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Password: "secret1",
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestLoginIgnoresInvalidPhoneWhenNamePresent(t *testing.T) {
repo := &fakeRepo{loginErr: errors.New("stop after lookup")}
_, _ = NewService(repo, &fakeSMS{}).Login(context.Background(), LoginDTO{
Name: "admin",
Phone: "string",
Password: "Test1234!",
})
if repo.lastLogin.Name != "admin" {
t.Fatalf("name = %q, want admin", repo.lastLogin.Name)
}
if repo.lastLogin.Phone != "" {
t.Fatalf("phone = %q, want empty", repo.lastLogin.Phone)
}
}
func TestLoginInvalidPhoneWithoutName(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Phone: "string",
Password: "secret1",
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestLoginWrongPassword(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("secret1"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
_, err = NewService(&fakeRepo{loginUser: UserCredentials{Id: 7, Password: string(hash)}}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Name: "Berdi Berdiyew",
Password: "wrong",
})
if !errors.Is(err, ErrInvalidCredentials) {
t.Fatalf("error = %v, want ErrInvalidCredentials", err)
}
}
func TestRegisterPasswordMismatch(t *testing.T) {
dto := validRegisterDTO()
dto.PasswordConfirm = "other"
@@ -147,3 +213,81 @@ func TestVerifyExpiredCode(t *testing.T) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
}
func TestForgotPasswordRequiresName(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestForgotPasswordNotFound(t *testing.T) {
_, err := NewService(&fakeRepo{userByNameErr: ErrNotFound}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{
Name: "Berdi Berdiyew",
})
if !errors.Is(err, ErrNotFound) {
t.Fatalf("error = %v, want ErrNotFound", err)
}
}
func TestForgotPasswordSendsSMS(t *testing.T) {
repo := &fakeRepo{userByName: UserIdentity{
Id: 7,
Name: "Berdi Berdiyew",
Username: "berdi",
Phone: "+993 61 92 92 48",
}}
sender := &fakeSMS{}
result, err := NewService(repo, sender).ForgotPassword(context.Background(), ForgotPasswordDTO{
Name: "Berdi Berdiyew",
})
if err != nil {
t.Fatalf("ForgotPassword: %v", err)
}
if result.Phone != "+993 61 92 92 48" {
t.Errorf("phone = %q", result.Phone)
}
if sender.phone != result.Phone {
t.Errorf("sms phone = %q", sender.phone)
}
if !strings.Contains(sender.message, "123456") {
t.Errorf("sms message = %q", sender.message)
}
}
func TestResetPasswordMismatch(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
Name: "Berdi Berdiyew",
Code: "123456",
Password: "secret1",
PasswordConfirm: "other",
})
if !errors.Is(err, ErrPasswordMismatch) {
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
}
}
func TestResetPasswordWrongCode(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
repo := &fakeRepo{
userByName: UserIdentity{Id: 7, Phone: "+993 61 92 92 48"},
verification: Verification{
ID: 1,
Phone: "+993 61 92 92 48",
CodeHash: string(hash),
ExpiresAt: time.Now().UTC().Add(time.Minute),
},
}
_, err = NewService(repo, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
Name: "Berdi Berdiyew",
Code: "000000",
Password: "secret1",
PasswordConfirm: "secret1",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
}

View File

@@ -13,4 +13,6 @@ type Repository interface {
GetVerificationByPhone(ctx context.Context, phone string) (Verification, error)
IncrementVerifyAttempts(ctx context.Context, id int64) error
CompleteRegistration(ctx context.Context, v Verification) (int, error)
GetUserByName(ctx context.Context, name string) (UserIdentity, error)
CompletePasswordReset(ctx context.Context, userID int, verificationID int64, passwordHash string) error
}

View File

@@ -29,8 +29,73 @@ const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.usernam
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildListQuery(filter)
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
}
func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause := ` FROM users u `
whereClause, args := buildStaffWhere(filter)
var count int64
countQuery := `SELECT COUNT(*)` + fromClause + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s, COALESCE((
SELECT json_agg(jsonb_build_object(
'id', b.id,
'uniqueCode', 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
ORDER BY b.id
) b
), '[]'::json)
%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return user.ListUserDTO{}, err
}
defer rows.Close()
var items []user.UserDTO
for rows.Next() {
item, err := scanStaffUser(rows)
if err != nil {
return user.ListUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return user.ListUserDTO{}, err
}
return user.ListUserDTO{Count: count, Users: items}, nil
}
func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`}
if filter.Username != "" {
args = append(args, likePattern(filter.Username))
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter, fromClause, whereClause string, args []interface{}) (user.ListUserDTO, error) {
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
@@ -65,11 +130,9 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis
return user.ListUserDTO{Count: count, Users: items}, nil
}
func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
return buildFilteredListQuery(filter, "")
}
var listVisibleRoles = []string{"user"}
func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) {
func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM users u `
var conditions []string
@@ -78,10 +141,17 @@ func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, wh
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
}
if role != "" {
args = append(args, role)
if len(roles) == 1 {
args = append(args, roles[0])
n := len(args)
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
} else if len(roles) > 0 {
placeholders := make([]string, len(roles))
for i, role := range roles {
args = append(args, role)
placeholders[i] = fmt.Sprintf("$%d", len(args))
}
conditions = append(conditions, fmt.Sprintf(`u.role IN (%s)`, strings.Join(placeholders, ", ")))
}
if len(conditions) == 0 {
@@ -100,39 +170,7 @@ func likePattern(term string) string {
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
return user.ListUserDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d `,
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
if err != nil {
return user.ListUserDTO{}, err
}
defer rows.Close()
var items []user.UserDTO
for rows.Next() {
item, err := scanUser(rows)
if err != nil {
return user.ListUserDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return user.ListUserDTO{}, err
}
return user.ListUserDTO{Count: count, Users: items}, nil
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
}
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
@@ -222,3 +260,26 @@ func scanUser(row scannable) (user.UserDTO, error) {
}
return item, nil
}
func scanStaffUser(row scannable) (user.UserDTO, error) {
var item user.UserDTO
var socialMedia []byte
var branchesJSON []byte
if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, &branchesJSON,
); err != nil {
return user.UserDTO{}, err
}
if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil {
return user.UserDTO{}, err
}
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
item.Branches = []user.StaffBranchDTO{}
return item, nil
}
if err := json.Unmarshal(branchesJSON, &item.Branches); err != nil {
return user.UserDTO{}, err
}
return item, nil
}

View File

@@ -8,21 +8,34 @@ type SocialMedia struct {
Telegram string `json:"telegram"`
}
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type StaffBranchDTO struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name"`
}
type UserDTO struct {
Id int64 `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
SocialMedia SocialMedia `json:"socialMedia"`
LightMode int `json:"lightMode"`
Role string `json:"role"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Username string `json:"username"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
SocialMedia SocialMedia `json:"socialMedia"`
LightMode int `json:"lightMode"`
Role string `json:"role"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Branches []StaffBranchDTO `json:"branches,omitempty"`
}
type CreateUserDTO struct {

View File

@@ -40,7 +40,8 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.GET("/role", h.listUsersByRole)
group.GET("/clients", h.listClients)
group.GET("/staff", h.listStaff)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
@@ -57,7 +58,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// list godoc
// @Summary List users
// @Description Returns paginated users with optional filters
// @Description Returns paginated users with role user, with optional filters
// @Tags user
// @Produce json
// @Security BearerAuth
@@ -85,41 +86,29 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listUsersByRole godoc
// @Summary List users by role
// @Description Returns paginated users filtered by role
// listClients godoc
// @Summary List client users
// @Description Returns paginated users from the users table with role user
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param role query string true "user role"
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/role [get]
func (h *handler) listUsersByRole(c *gin.Context) {
role := strings.TrimSpace(c.Query("role"))
if role == "" {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
// @Router /users/clients [get]
func (h *handler) listClients(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByRole(c.Request.Context(), role, filter)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
item, err := h.repository.GetByRole(c.Request.Context(), "user", filter)
if err != nil {
h.logger.Errorf("get user failed: %v", err)
h.logger.Errorf("list client users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
@@ -127,6 +116,36 @@ func (h *handler) listUsersByRole(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// listStaff godoc
// @Summary List staff users
// @Description Returns paginated users assigned to branches (from branch_user), including each user's branches.
// @Tags user
// @Produce json
// @Security BearerAuth
// @Param username query string false "Filter by username"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /users/staff [get]
func (h *handler) listStaff(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.ListStaff(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list staff users failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get user by ID
// @Description Returns a single user

View File

@@ -4,6 +4,7 @@ import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
ListStaff(ctx context.Context, filter ListFilter) (ListUserDTO, error)
GetByID(ctx context.Context, id int64) (UserDTO, error)
GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error)
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)