From 5e3c46da832a3d7edab3fb19c9df28bc771fc438 Mon Sep 17 00:00:00 2001 From: GuwandykA Date: Thu, 13 Aug 2026 14:43:33 +0500 Subject: [PATCH] Add phone registration with SMS verification and regenerate Swagger docs. Co-authored-by: Cursor --- ...141500_registration_verifications.down.sql | 3 + ...13141500_registration_verifications.up.sql | 21 +++ docs/docs.go | 136 ++++++++++++++++ docs/swagger.json | 136 ++++++++++++++++ docs/swagger.yaml | 92 +++++++++++ internal/appresult/error.go | 13 +- internal/identity/auth/db/postgresql.go | 112 ++++++++++++- internal/identity/auth/dto.go | 29 ++++ internal/identity/auth/handler.go | 85 +++++++++- internal/identity/auth/phone.go | 34 ++++ internal/identity/auth/phone_test.go | 29 ++++ internal/identity/auth/service.go | 138 +++++++++++++++- internal/identity/auth/service_test.go | 149 ++++++++++++++++++ internal/identity/auth/storage.go | 6 + internal/identity/router.go | 5 +- pkg/sms/sender.go | 30 ++++ pkg/utils/utils.go | 10 +- 17 files changed, 1008 insertions(+), 20 deletions(-) create mode 100644 db/migrations/20260813141500_registration_verifications.down.sql create mode 100644 db/migrations/20260813141500_registration_verifications.up.sql create mode 100644 internal/identity/auth/phone.go create mode 100644 internal/identity/auth/phone_test.go create mode 100644 internal/identity/auth/service_test.go create mode 100644 pkg/sms/sender.go diff --git a/db/migrations/20260813141500_registration_verifications.down.sql b/db/migrations/20260813141500_registration_verifications.down.sql new file mode 100644 index 0000000..b28a4b8 --- /dev/null +++ b/db/migrations/20260813141500_registration_verifications.down.sql @@ -0,0 +1,3 @@ +DROP INDEX IF EXISTS users_phone_unique; +DROP INDEX IF EXISTS users_username_unique; +DROP TABLE IF EXISTS registration_verifications; diff --git a/db/migrations/20260813141500_registration_verifications.up.sql b/db/migrations/20260813141500_registration_verifications.up.sql new file mode 100644 index 0000000..dfbcf5d --- /dev/null +++ b/db/migrations/20260813141500_registration_verifications.up.sql @@ -0,0 +1,21 @@ +CREATE TABLE IF NOT EXISTS registration_verifications ( + id bigserial PRIMARY KEY, + name character varying(255) NOT NULL DEFAULT '', + username character varying(250) NOT NULL DEFAULT '', + phone character varying(250) NOT NULL, + password character varying(250) NOT NULL DEFAULT '', + code_hash character varying(250) NOT NULL DEFAULT '', + attempts integer NOT NULL DEFAULT 0, + expires_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT registration_verifications_phone_key UNIQUE (phone) +); + +CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique + ON users (LOWER(username)) + WHERE username <> ''; + +CREATE UNIQUE INDEX IF NOT EXISTS users_phone_unique + ON users (phone) + WHERE phone <> ''; diff --git a/docs/docs.go b/docs/docs.go index 334333e..7272f0b 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4658,6 +4658,98 @@ const docTemplate = `{ } } }, + "/register": { + "post": { + "description": "Starts registration and sends an SMS verification code. Replace sms.LogSender with your SMS client.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Register", + "parameters": [ + { + "description": "Registration payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.RegisterDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/register/verify": { + "post": { + "description": "Confirms the SMS code and creates the user account", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Verify phone", + "parameters": [ + { + "description": "Verification payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.VerifyDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/role-users": { "get": { "security": [ @@ -5523,6 +5615,35 @@ const docTemplate = `{ } } }, + "auth.RegisterDTO": { + "type": "object", + "required": [ + "name", + "password", + "passwordConfirm", + "phone", + "username" + ], + "properties": { + "name": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 6 + }, + "passwordConfirm": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "username": { + "type": "string", + "minLength": 3 + } + } + }, "auth.UpdateProfileDTO": { "type": "object", "required": [ @@ -5546,6 +5667,21 @@ const docTemplate = `{ } } }, + "auth.VerifyDTO": { + "type": "object", + "required": [ + "code", + "phone" + ], + "properties": { + "code": { + "type": "string" + }, + "phone": { + "type": "string" + } + } + }, "branches.CreateBranchDTO": { "type": "object", "required": [ diff --git a/docs/swagger.json b/docs/swagger.json index b2e603a..6fd1f92 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -4652,6 +4652,98 @@ } } }, + "/register": { + "post": { + "description": "Starts registration and sends an SMS verification code. Replace sms.LogSender with your SMS client.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Register", + "parameters": [ + { + "description": "Registration payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.RegisterDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/register/verify": { + "post": { + "description": "Confirms the SMS code and creates the user account", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Verify phone", + "parameters": [ + { + "description": "Verification payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.VerifyDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/role-users": { "get": { "security": [ @@ -5517,6 +5609,35 @@ } } }, + "auth.RegisterDTO": { + "type": "object", + "required": [ + "name", + "password", + "passwordConfirm", + "phone", + "username" + ], + "properties": { + "name": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 6 + }, + "passwordConfirm": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "username": { + "type": "string", + "minLength": 3 + } + } + }, "auth.UpdateProfileDTO": { "type": "object", "required": [ @@ -5540,6 +5661,21 @@ } } }, + "auth.VerifyDTO": { + "type": "object", + "required": [ + "code", + "phone" + ], + "properties": { + "code": { + "type": "string" + }, + "phone": { + "type": "string" + } + } + }, "branches.CreateBranchDTO": { "type": "object", "required": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 6c1256d..85a05e1 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -36,6 +36,27 @@ definitions: required: - refreshToken type: object + auth.RegisterDTO: + properties: + name: + type: string + password: + minLength: 6 + type: string + passwordConfirm: + type: string + phone: + type: string + username: + minLength: 3 + type: string + required: + - name + - password + - passwordConfirm + - phone + - username + type: object auth.UpdateProfileDTO: properties: avatar: @@ -51,6 +72,16 @@ definitions: required: - name type: object + auth.VerifyDTO: + properties: + code: + type: string + phone: + type: string + required: + - code + - phone + type: object branches.CreateBranchDTO: properties: active: @@ -4194,6 +4225,67 @@ paths: summary: Update reason card tags: - reason-card + /register: + post: + consumes: + - application/json + description: Starts registration and sends an SMS verification code. Replace + sms.LogSender with your SMS client. + parameters: + - description: Registration payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/auth.RegisterDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' + summary: Register + tags: + - auth + /register/verify: + post: + consumes: + - application/json + description: Confirms the SMS code and creates the user account + parameters: + - description: Verification payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/auth.VerifyDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' + summary: Verify phone + tags: + - auth /role-users: get: description: Returns the authenticated user's role-user assignments with the diff --git a/internal/appresult/error.go b/internal/appresult/error.go index 62b29ee..6f126d3 100755 --- a/internal/appresult/error.go +++ b/internal/appresult/error.go @@ -3,11 +3,14 @@ package appresult import "encoding/json" var ( - ErrMissingParam = NewAppError(nil, "Required parameter is missing or invalid.", "SE-00001") - ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002") - ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003") - ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004") - ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007") + ErrMissingParam = NewAppError(nil, "Required parameter is missing or invalid.", "SE-00001") + ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002") + ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003") + ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004") + ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007") + ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008") + ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009") + ErrPasswordMismatch = NewAppError(nil, "Password confirmation does not match.", "SE-00010") ) type AppError struct { diff --git a/internal/identity/auth/db/postgresql.go b/internal/identity/auth/db/postgresql.go index 7da9fd0..963fc90 100755 --- a/internal/identity/auth/db/postgresql.go +++ b/internal/identity/auth/db/postgresql.go @@ -3,11 +3,14 @@ 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" ) @@ -24,9 +27,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi } const ( - loginQuery = `SELECT id, password FROM users WHERE email = $1` + loginQuery = `SELECT id, password FROM users WHERE email = $1` userByIDQuery = `SELECT id, password FROM users WHERE id = $1` - profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at + profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at FROM users WHERE id = $1` ) @@ -81,3 +84,108 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP } 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 digitString(s string) string { + var b strings.Builder + for _, r := range s { + if unicode.IsDigit(r) { + b.WriteRune(r) + } + } + return b.String() +} diff --git a/internal/identity/auth/dto.go b/internal/identity/auth/dto.go index 886284b..350210b 100755 --- a/internal/identity/auth/dto.go +++ b/internal/identity/auth/dto.go @@ -33,3 +33,32 @@ type UserCredentials struct { Id int Password string } + +type RegisterDTO struct { + Name string `json:"name" binding:"required"` + Phone string `json:"phone" binding:"required"` + Username string `json:"username" binding:"required,min=3"` + Password string `json:"password" binding:"required,min=6"` + PasswordConfirm string `json:"passwordConfirm" binding:"required"` +} + +type VerifyDTO struct { + Phone string `json:"phone" binding:"required"` + Code string `json:"code" binding:"required,len=6"` +} + +type RegisterResult struct { + Phone string `json:"phone"` + ExpiresIn int `json:"expiresIn"` +} + +type Verification struct { + ID int64 + Name string + Username string + Phone string + Password string + CodeHash string + Attempts int + ExpiresAt time.Time +} diff --git a/internal/identity/auth/handler.go b/internal/identity/auth/handler.go index ddc3b79..9e2e0b7 100755 --- a/internal/identity/auth/handler.go +++ b/internal/identity/auth/handler.go @@ -8,15 +8,18 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/pkg/logging" + "online-back/pkg/sms" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v4" ) const ( - loginURL = "/login" - tokenURL = "/token" - profileURL = "/profile" + loginURL = "/login" + tokenURL = "/token" + profileURL = "/profile" + registerURL = "/register" + verifyURL = "/register/verify" ) type handler struct { @@ -25,13 +28,15 @@ type handler struct { service *Service } -func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { - return &handler{logger: logger, repository: repository, service: NewService(repository)} +func NewHandler(logger *logging.Logger, repository Repository, sender sms.Sender) handlers.Handler { + return &handler{logger: logger, repository: repository, service: NewService(repository, sender)} } func (h *handler) Register(router *gin.RouterGroup) { router.POST(loginURL, h.login) router.POST(tokenURL, h.refreshToken) + router.POST(registerURL, h.register) + router.POST(verifyURL, h.verify) protected := router.Group("", appresult.JwtTokenCheck()) protected.GET(profileURL, h.getProfile) @@ -69,6 +74,76 @@ func (h *handler) login(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) } +// register godoc +// @Summary Register +// @Description Starts registration and sends an SMS verification code. Replace sms.LogSender with your SMS client. +// @Tags auth +// @Accept json +// @Produce json +// @Param body body RegisterDTO true "Registration payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 409 {object} appresult.AppError +// @Router /register [post] +func (h *handler) register(c *gin.Context) { + var dto RegisterDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + result, err := h.service.Register(c.Request.Context(), dto) + if err != nil { + h.respondRegisterError(c, err) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// verify godoc +// @Summary Verify phone +// @Description Confirms the SMS code and creates the user account +// @Tags auth +// @Accept json +// @Produce json +// @Param body body VerifyDTO true "Verification payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 409 {object} appresult.AppError +// @Router /register/verify [post] +func (h *handler) verify(c *gin.Context) { + var dto VerifyDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + tokenPair, err := h.service.Verify(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, ErrConflict): + c.JSON(http.StatusConflict, appresult.ErrConflict) + case errors.Is(err, ErrInvalidCode): + c.JSON(http.StatusBadRequest, appresult.ErrInvalidCode) + default: + h.logger.Errorf("register/verify failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + } +} + // refreshToken godoc // @Summary Refresh tokens // @Description Issues a new access and refresh token pair diff --git a/internal/identity/auth/phone.go b/internal/identity/auth/phone.go new file mode 100644 index 0000000..95acf76 --- /dev/null +++ b/internal/identity/auth/phone.go @@ -0,0 +1,34 @@ +package auth + +import ( + "fmt" + "strings" + "unicode" +) + +func onlyDigits(s string) string { + var b strings.Builder + for _, r := range s { + if unicode.IsDigit(r) { + b.WriteRune(r) + } + } + return b.String() +} + +// NormalizePhone accepts Turkmen numbers in common local forms and +// returns +993 6X XX XX XX. +func NormalizePhone(raw string) (string, error) { + digits := onlyDigits(raw) + switch { + case strings.HasPrefix(digits, "993") && len(digits) == 11: + digits = digits[3:] + case len(digits) == 9 && digits[0] == '8': + digits = digits[1:] + } + + if len(digits) != 8 { + return "", ErrInvalidPhone + } + return fmt.Sprintf("+993 %s %s %s %s", digits[0:2], digits[2:4], digits[4:6], digits[6:8]), nil +} diff --git a/internal/identity/auth/phone_test.go b/internal/identity/auth/phone_test.go new file mode 100644 index 0000000..6c8018a --- /dev/null +++ b/internal/identity/auth/phone_test.go @@ -0,0 +1,29 @@ +package auth + +import "testing" + +func TestNormalizePhone(t *testing.T) { + tests := []struct { + in, want string + }{ + {"+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) + } +} diff --git a/internal/identity/auth/service.go b/internal/identity/auth/service.go index 7d516c0..ddf6087 100644 --- a/internal/identity/auth/service.go +++ b/internal/identity/auth/service.go @@ -3,23 +3,40 @@ package auth import ( "context" "errors" + "fmt" + "strings" + "time" + "online-back/pkg/sms" "online-back/pkg/utils" "golang.org/x/crypto/bcrypt" ) -// ErrInvalidCredentials covers both "no such user" and "wrong password" for -// login, and any refresh-token validation failure — callers map it to 401. -// Any other error from these methods (token generation failure) maps to 400. -var ErrInvalidCredentials = errors.New("invalid credentials") +const ( + otpTTL = 1 * time.Minute + maxVerifyTries = 5 + otpMessageTm = "Onlaýn kabulhana tassyklaýyş belgiňiz: %s" + // localOTP is a fixed code for local testing. Switch to generateOTP() in production. + localOTP = "123456" +) + +var ( + ErrInvalidCredentials = errors.New("invalid credentials") + ErrPasswordMismatch = errors.New("password confirmation does not match") + ErrConflict = errors.New("user already exists") + ErrInvalidPhone = errors.New("invalid phone number") + ErrInvalidCode = errors.New("invalid or expired verification code") + ErrInvalidInput = errors.New("required parameter is missing or invalid") +) type Service struct { repository Repository + sms sms.Sender } -func NewService(repository Repository) *Service { - return &Service{repository: repository} +func NewService(repository Repository, sender sms.Sender) *Service { + return &Service{repository: repository, sms: sender} } func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) { @@ -53,3 +70,112 @@ func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (map[st return utils.GenerateTokenPair(id) } + +func (s *Service) Register(ctx context.Context, dto RegisterDTO) (RegisterResult, error) { + if dto.Password != dto.PasswordConfirm { + return RegisterResult{}, ErrPasswordMismatch + } + + phone, err := NormalizePhone(dto.Phone) + if err != nil { + return RegisterResult{}, err + } + + username := strings.TrimSpace(dto.Username) + name := strings.TrimSpace(dto.Name) + if name == "" || username == "" { + return RegisterResult{}, ErrInvalidInput + } + + exists, err := s.repository.UserExists(ctx, username, phone) + if err != nil { + return RegisterResult{}, err + } + if exists { + return RegisterResult{}, ErrConflict + } + + taken, err := s.repository.UsernameTaken(ctx, username, phone) + if err != nil { + return RegisterResult{}, err + } + if taken { + return RegisterResult{}, ErrConflict + } + + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost) + if err != nil { + 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, + }); 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) Verify(ctx context.Context, dto VerifyDTO) (map[string]string, error) { + phone, err := NormalizePhone(dto.Phone) + if err != nil { + return nil, err + } + + v, err := s.repository.GetVerificationByPhone(ctx, 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 + } + + userID, err := s.repository.CompleteRegistration(ctx, v) + if err != nil { + return nil, err + } + + return utils.GenerateUserTokenPair(userID) +} + +// Production: uncomment generateOTP and add imports "crypto/rand" and "math/big". +// func generateOTP() (string, error) { +// max := big.NewInt(1_000_000) +// n, err := rand.Int(rand.Reader, max) +// if err != nil { +// return "", err +// } +// return fmt.Sprintf("%06d", n.Int64()), nil +// } diff --git a/internal/identity/auth/service_test.go b/internal/identity/auth/service_test.go new file mode 100644 index 0000000..7eeb16e --- /dev/null +++ b/internal/identity/auth/service_test.go @@ -0,0 +1,149 @@ +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 +} + +func (f *fakeRepo) Login(context.Context, LoginDTO) (UserCredentials, error) { + return UserCredentials{}, errors.New("not implemented") +} +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 +} + +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 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) + } +} diff --git a/internal/identity/auth/storage.go b/internal/identity/auth/storage.go index 5049f5d..2f05968 100755 --- a/internal/identity/auth/storage.go +++ b/internal/identity/auth/storage.go @@ -7,4 +7,10 @@ type Repository interface { GetUserByID(ctx context.Context, id int) (UserCredentials, error) GetProfile(ctx context.Context, id int) (UserProfileDTO, error) UpdateProfile(ctx context.Context, id int, dto UpdateProfileDTO) (UserProfileDTO, error) + UserExists(ctx context.Context, username, phone string) (bool, error) + UsernameTaken(ctx context.Context, username, exceptPhone string) (bool, error) + UpsertVerification(ctx context.Context, v Verification) error + GetVerificationByPhone(ctx context.Context, phone string) (Verification, error) + IncrementVerifyAttempts(ctx context.Context, id int64) error + CompleteRegistration(ctx context.Context, v Verification) (int, error) } diff --git a/internal/identity/router.go b/internal/identity/router.go index 2c4c928..3423e14 100644 --- a/internal/identity/router.go +++ b/internal/identity/router.go @@ -23,6 +23,7 @@ import ( userbranchdb "online-back/internal/identity/userbranch/db" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/sms" "github.com/gin-gonic/gin" ) @@ -37,7 +38,9 @@ func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler { return []handlers.Handler{ activitylog.NewHandler(logger, activitylogdb.NewRepository(client, logger)), - auth.NewHandler(logger, authdb.NewRepository(client, logger)), + // Swap sms.NewLogSender for your SMS provider: it only needs to + // implement sms.Sender (Send(ctx, phone, message)). + auth.NewHandler(logger, authdb.NewRepository(client, logger), sms.NewLogSender(logger)), user.NewHandler(logger, userdb.NewRepository(client, logger)), role.NewHandler(logger, roledb.NewRepository(client, logger)), permission.NewHandler(logger, permissiondb.NewRepository(client, logger)), diff --git a/pkg/sms/sender.go b/pkg/sms/sender.go new file mode 100644 index 0000000..45cdd38 --- /dev/null +++ b/pkg/sms/sender.go @@ -0,0 +1,30 @@ +package sms + +import ( + "context" + + "online-back/pkg/logging" +) + +// Sender delivers an SMS. Plug your provider in by implementing this +// interface and passing it to auth.NewHandler. +type Sender interface { + Send(ctx context.Context, phone, message string) error +} + +// LogSender is a stand-in used until a real SMS client is wired in. +// It logs the message (including the OTP) so local testing still works. +type LogSender struct { + logger *logging.Logger +} + +func NewLogSender(logger *logging.Logger) *LogSender { + return &LogSender{logger: logger} +} + +func (s *LogSender) Send(_ context.Context, phone, message string) error { + if s.logger != nil { + s.logger.Infof("sms to %s: %s", phone, message) + } + return nil +} diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index f72b024..b30ddd4 100755 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -21,12 +21,20 @@ func DoWithTries(fn func() error, attempts int, delay time.Duration) error { } func GenerateTokenPair(id int) (map[string]string, error) { + return generateTokenPair(id, true) +} + +func GenerateUserTokenPair(id int) (map[string]string, error) { + return generateTokenPair(id, false) +} + +func generateTokenPair(id int, admin bool) (map[string]string, error) { cfg := config.GetConfig() secret := []byte(cfg.JwtKey) accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "id": id, - "admin": true, + "admin": admin, "exp": time.Now().Add(time.Hour).Unix(), })