From dd802aca376fe497e049aa87262290ae428c3e9a Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Tue, 21 Jul 2026 03:03:39 -0700 Subject: [PATCH] Block deactivated and suspended learners from all auth paths. Enforce account status on email, phone OTP, social login, token refresh, and authenticated learner requests. Co-authored-by: Cursor --- internal/domain/user.go | 28 +++++++++++++++----- internal/domain/user_auth_status_test.go | 22 +++++++++++++++ internal/services/authentication/apple.go | 8 ++---- internal/services/authentication/google.go | 8 ++---- internal/services/authentication/impl.go | 15 ++++++----- internal/web_server/handlers/auth_handler.go | 19 ++++++++++--- internal/web_server/middleware.go | 27 +++++++++++++++++++ 7 files changed, 97 insertions(+), 30 deletions(-) create mode 100644 internal/domain/user_auth_status_test.go diff --git a/internal/domain/user.go b/internal/domain/user.go index 51a52bd0..3710acad 100644 --- a/internal/domain/user.go +++ b/internal/domain/user.go @@ -19,6 +19,7 @@ const ( var ( ErrUserNotVerified = errors.New("user not verified") + ErrUserAccountLocked = errors.New("user account is locked") ErrUserNotFound = errors.New("user not found") ErrEmailAlreadyRegistered = errors.New("email is already registered") ErrPhoneAlreadyRegistered = errors.New("phone number is already registered") @@ -39,6 +40,19 @@ const ( UserStatusDeactivated UserStatus = "DEACTIVATED" ) +// ValidateUserCanAuthenticate reports whether a platform user may sign in or use auth tokens. +// PENDING users must complete verification; SUSPENDED and DEACTIVATED accounts are locked. +func ValidateUserCanAuthenticate(status UserStatus) error { + switch status { + case UserStatusPending: + return ErrUserNotVerified + case UserStatusSuspended, UserStatusDeactivated: + return ErrUserAccountLocked + default: + return nil + } +} + type UpdateKnowledgeLevelReq struct { UserID int64 `json:"user_id"` KnowledgeLevel string `json:"knowledge_level"` // BEGINNER, INTERMEDIATE, ADVANCED @@ -123,8 +137,8 @@ type UserProfileResponse struct { CreatedAt time.Time `json:"created_at"` UpdatedAt *time.Time `json:"updated_at,omitempty"` - SubscriptionStatus string `json:"subscription_status"` - ActiveSubscriptions []UserProfileSubscription `json:"active_subscriptions"` + SubscriptionStatus string `json:"subscription_status"` + ActiveSubscriptions []UserProfileSubscription `json:"active_subscriptions"` } // UserProfileSubscription is an active subscription summary embedded in user profile responses. @@ -145,11 +159,11 @@ type UserProfileSubscription struct { } type UserFilter struct { - Role string - Status string - Country string - Region string - SubscriptionStatus string // display filter: ACTIVE, PENDING, Unsubscribed (same as API subscription_status values) + Role string + Status string + Country string + Region string + SubscriptionStatus string // display filter: ACTIVE, PENDING, Unsubscribed (same as API subscription_status values) Page int64 PageSize int64 diff --git a/internal/domain/user_auth_status_test.go b/internal/domain/user_auth_status_test.go new file mode 100644 index 00000000..231e5ec4 --- /dev/null +++ b/internal/domain/user_auth_status_test.go @@ -0,0 +1,22 @@ +package domain + +import "testing" + +func TestValidateUserCanAuthenticate(t *testing.T) { + cases := []struct { + status UserStatus + want error + }{ + {UserStatusActive, nil}, + {UserStatusPending, ErrUserNotVerified}, + {UserStatusSuspended, ErrUserAccountLocked}, + {UserStatusDeactivated, ErrUserAccountLocked}, + } + + for _, tc := range cases { + got := ValidateUserCanAuthenticate(tc.status) + if got != tc.want { + t.Fatalf("ValidateUserCanAuthenticate(%q)=%v, want %v", tc.status, got, tc.want) + } + } +} diff --git a/internal/services/authentication/apple.go b/internal/services/authentication/apple.go index 5fe1fa27..0a027de3 100644 --- a/internal/services/authentication/apple.go +++ b/internal/services/authentication/apple.go @@ -165,12 +165,8 @@ func (s *Service) LoginWithApple( return domain.LoginSuccess{}, err } - if user.Status == domain.UserStatusPending { - return domain.LoginSuccess{}, domain.ErrUserNotVerified - } - - if user.Status == domain.UserStatusSuspended { - return domain.LoginSuccess{}, ErrUserSuspended + if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil { + return domain.LoginSuccess{}, err } oldToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID) diff --git a/internal/services/authentication/google.go b/internal/services/authentication/google.go index 71487651..836d14d6 100644 --- a/internal/services/authentication/google.go +++ b/internal/services/authentication/google.go @@ -148,12 +148,8 @@ func (s *Service) LoginWithGoogle( return domain.LoginSuccess{}, err } - if user.Status == domain.UserStatusPending { - return domain.LoginSuccess{}, domain.ErrUserNotVerified - } - - if user.Status == domain.UserStatusSuspended { - return domain.LoginSuccess{}, ErrUserSuspended + if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil { + return domain.LoginSuccess{}, err } oldToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID) diff --git a/internal/services/authentication/impl.go b/internal/services/authentication/impl.go index 31705f5e..b44ef64a 100644 --- a/internal/services/authentication/impl.go +++ b/internal/services/authentication/impl.go @@ -17,7 +17,8 @@ var ( ErrUserNotFound = errors.New("user not found") ErrExpiredToken = errors.New("token expired") ErrRefreshTokenNotFound = errors.New("refresh token not found") // i.e login again - ErrUserSuspended = errors.New("user has been suspended") + // ErrUserSuspended is kept for backward compatibility with existing handlers. + ErrUserSuspended = domain.ErrUserAccountLocked ) func (s *Service) Login( @@ -30,12 +31,8 @@ func (s *Service) Login( return domain.LoginSuccess{}, err } - if user.Status == domain.UserStatusPending { - return domain.LoginSuccess{}, domain.ErrUserNotVerified - } - - if user.Status == domain.UserStatusSuspended { - return domain.LoginSuccess{}, ErrUserSuspended + if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil { + return domain.LoginSuccess{}, err } // Email + password login @@ -95,6 +92,10 @@ func (s *Service) VerifyOtp( return domain.LoginSuccess{}, err } + if user.Status == domain.UserStatusSuspended || user.Status == domain.UserStatusDeactivated { + return domain.LoginSuccess{}, domain.ErrUserAccountLocked + } + // 1. Retrieve OTP row matching submitted code. // This avoids false positives when another OTP row exists for the same user. storedOtp, err := s.otpStore.GetOtpByCode(ctx, user.ID, otpCode) diff --git a/internal/web_server/handlers/auth_handler.go b/internal/web_server/handlers/auth_handler.go index fdff70a8..9ddb4d75 100644 --- a/internal/web_server/handlers/auth_handler.go +++ b/internal/web_server/handlers/auth_handler.go @@ -101,10 +101,10 @@ func (h *Handler) GoogleAndroidLogin(c *fiber.Ctx) error { // @Router /api/v1/auth/apple [post] func (h *Handler) AppleLogin(c *fiber.Ctx) error { var req struct { - IDToken string `json:"id_token" validate:"required"` - Email string `json:"email"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` + IDToken string `json:"id_token" validate:"required"` + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` } if err := c.BodyParser(&req); err != nil { @@ -681,6 +681,17 @@ func (h *Handler) RefreshToken(c *fiber.Ctx) error { return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve user information:"+err.Error()) } + if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil { + switch { + case errors.Is(err, domain.ErrUserAccountLocked): + return fiber.NewError(fiber.StatusUnauthorized, "User login has been locked") + case errors.Is(err, domain.ErrUserNotVerified): + return fiber.NewError(fiber.StatusUnauthorized, "User account is not verified") + default: + return fiber.NewError(fiber.StatusUnauthorized, err.Error()) + } + } + accessToken, err := jwtutil.CreateJwt(user.ID, user.Role, h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry) if err != nil { h.mongoLoggerSvc.Error("Failed to create new access token", diff --git a/internal/web_server/middleware.go b/internal/web_server/middleware.go index 4433629a..53db3e54 100644 --- a/internal/web_server/middleware.go +++ b/internal/web_server/middleware.go @@ -107,6 +107,33 @@ func (a *App) authMiddleware(c *fiber.Ctx) error { // }) c.Locals("refresh_token", refreshToken) + userRole := claim.Role + if userRole.IsCustomerLearnerRole() { + user, err := a.userSvc.GetUserByID(c.Context(), claim.UserId) + if err != nil { + if errors.Is(err, domain.ErrUserNotFound) { + return fiber.NewError(fiber.StatusUnauthorized, "Invalid access token") + } + a.mongoLoggerSvc.Error("Failed to load user during auth", + zap.Int64("userID", claim.UserId), + zap.Int("status_code", fiber.StatusInternalServerError), + zap.Error(err), + zap.Time("timestamp", time.Now()), + ) + return fiber.NewError(fiber.StatusInternalServerError, "Failed to validate user account") + } + if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil { + switch { + case errors.Is(err, domain.ErrUserAccountLocked): + return fiber.NewError(fiber.StatusForbidden, "Account is locked") + case errors.Is(err, domain.ErrUserNotVerified): + return fiber.NewError(fiber.StatusForbidden, "Account is not verified") + default: + return fiber.NewError(fiber.StatusForbidden, err.Error()) + } + } + } + // var branchID domain.ValidInt64 if claim.Role == domain.RoleAdmin {