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:
@@ -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 {
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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".
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user