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 <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-21 03:03:39 -07:00
parent d6e727152a
commit dd802aca37
7 changed files with 97 additions and 30 deletions

View File

@ -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

View File

@ -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)
}
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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",

View File

@ -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 {