Put the user's role and branch on GET /profile, upsert role_user and branch_user on POST, and drop their list endpoints.
Also accept flexible card-order form values, move mock seed under db/mock, and regenerate Swagger. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
7225dc0399
commit
8795ae2195
47 files changed
+1308
-1785
No files matched your search
@@ -2,6 +2,8 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -38,10 +40,36 @@ const (
|
||||
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`
|
||||
)
|
||||
|
||||
const profileFromClause = ` FROM users u
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id`
|
||||
|
||||
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
|
||||
ORDER BY b.id
|
||||
) b
|
||||
), '[]'::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, ` + profileBranchesJSON + profileFromClause + ` WHERE u.id = $1`
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
|
||||
phone := strings.TrimSpace(dto.Phone)
|
||||
if phone != "" {
|
||||
@@ -66,31 +94,39 @@ func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredenti
|
||||
}
|
||||
|
||||
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
|
||||
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
|
||||
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
|
||||
WHERE id = $6`
|
||||
|
||||
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,
|
||||
tag, err := r.client.Exec(ctx, updateProfileQuery,
|
||||
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
|
||||
).Scan(
|
||||
)
|
||||
if err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return auth.UserProfileDTO{}, pgx.ErrNoRows
|
||||
}
|
||||
return r.GetProfile(ctx, id)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanProfile(row scannable) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
var roleID sql.NullInt64
|
||||
var roleCode, roleName sql.NullString
|
||||
var branchesJSON []byte
|
||||
|
||||
err := row.Scan(
|
||||
&profile.Id,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
@@ -98,11 +134,31 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
&roleID,
|
||||
&roleCode,
|
||||
&roleName,
|
||||
&branchesJSON,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
return profile, err
|
||||
|
||||
if roleID.Valid {
|
||||
profile.Role = &auth.ProfileRoleDTO{
|
||||
Id: roleID.Int64,
|
||||
Code: roleCode.String,
|
||||
Name: roleName.String,
|
||||
}
|
||||
}
|
||||
|
||||
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
|
||||
profile.Branches = []auth.ProfileBranchDTO{}
|
||||
return profile, nil
|
||||
}
|
||||
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func (r *repository) UserExists(ctx context.Context, username, phone string) (bool, error) {
|
||||
|
||||
@@ -12,14 +12,34 @@ type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type ProfileRoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ProfileBranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
}
|
||||
|
||||
type UserProfileDTO struct {
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role *ProfileRoleDTO `json:"role"`
|
||||
Branches []ProfileBranchDTO `json:"branches"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UpdateProfileDTO struct {
|
||||
|
||||
@@ -242,7 +242,7 @@ func (h *handler) refreshToken(c *gin.Context) {
|
||||
|
||||
// getProfile godoc
|
||||
// @Summary Get profile
|
||||
// @Description Returns the authenticated user's profile
|
||||
// @Description Returns the authenticated user's profile with role and branches
|
||||
// @Tags auth
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package auth
|
||||
|
||||
import "testing"
|
||||
|
||||
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"},
|
||||
{"61929248", "+993 61 92 92 48"},
|
||||
{"8 61929248", "+993 61 92 92 48"},
|
||||
{"61 92 92 48", "+993 61 92 92 48"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got, err := NormalizePhone(tt.in)
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizePhone(%q) unexpected error: %v", tt.in, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("NormalizePhone(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type fakeRepo struct {
|
||||
exists bool
|
||||
usernameTaken bool
|
||||
verification Verification
|
||||
getErr error
|
||||
userID int
|
||||
userByName UserIdentity
|
||||
userByNameErr error
|
||||
loginUser UserCredentials
|
||||
loginErr error
|
||||
lastLogin LoginDTO
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
func (f *fakeRepo) GetProfile(context.Context, int) (UserProfileDTO, error) {
|
||||
return UserProfileDTO{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) UpdateProfile(context.Context, int, UpdateProfileDTO) (UserProfileDTO, error) {
|
||||
return UserProfileDTO{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) UserExists(context.Context, string, string) (bool, error) {
|
||||
return f.exists, nil
|
||||
}
|
||||
func (f *fakeRepo) UsernameTaken(context.Context, string, string) (bool, error) {
|
||||
return f.usernameTaken, nil
|
||||
}
|
||||
func (f *fakeRepo) UpsertVerification(_ context.Context, v Verification) error {
|
||||
f.verification = v
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) GetVerificationByPhone(context.Context, string) (Verification, error) {
|
||||
return f.verification, f.getErr
|
||||
}
|
||||
func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error {
|
||||
f.verification.Attempts++
|
||||
return nil
|
||||
}
|
||||
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
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSMS) Send(_ context.Context, phone, message string) error {
|
||||
f.phone = phone
|
||||
f.message = message
|
||||
return f.err
|
||||
}
|
||||
|
||||
func validRegisterDTO() RegisterDTO {
|
||||
return RegisterDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Phone: "+993 61 92 92 48",
|
||||
Username: "berdi",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "secret1",
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Register(context.Background(), dto)
|
||||
if !errors.Is(err, ErrPasswordMismatch) {
|
||||
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterConflict(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{exists: true}, &fakeSMS{}).Register(context.Background(), validRegisterDTO())
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("error = %v, want ErrConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterSendsSMS(t *testing.T) {
|
||||
repo := &fakeRepo{}
|
||||
sender := &fakeSMS{}
|
||||
result, err := NewService(repo, sender).Register(context.Background(), validRegisterDTO())
|
||||
if err != nil {
|
||||
t.Fatalf("Register: %v", err)
|
||||
}
|
||||
if result.Phone != "+993 61 92 92 48" {
|
||||
t.Errorf("phone = %q", result.Phone)
|
||||
}
|
||||
if result.ExpiresIn != 60 {
|
||||
t.Errorf("expiresIn = %d", result.ExpiresIn)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if repo.verification.Password == "secret1" {
|
||||
t.Fatal("password stored in plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyWrongCode(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &fakeRepo{verification: Verification{
|
||||
ID: 1,
|
||||
Phone: "+993 61 92 92 48",
|
||||
CodeHash: string(hash),
|
||||
ExpiresAt: time.Now().UTC().Add(time.Minute),
|
||||
}}
|
||||
_, err = NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
|
||||
Phone: "+993 61 92 92 48",
|
||||
Code: "000000",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
if repo.verification.Attempts != 1 {
|
||||
t.Errorf("attempts = %d, want 1", repo.verification.Attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExpiredCode(t *testing.T) {
|
||||
repo := &fakeRepo{verification: Verification{
|
||||
ExpiresAt: time.Now().UTC().Add(-time.Minute),
|
||||
}}
|
||||
_, err := NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
|
||||
Phone: "+993 61 92 92 48",
|
||||
Code: "123456",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user