This documents all authentication flows in Backstory. Here are the key flows explained: # 🔐 Core Authentication Flows 1. Registration & Email Verification `Registration → Email Sent → Email Verification → Account Activation → Login` Includes resend verification with rate limiting Handles expired tokens and error cases 2. Login on Trusted Device `Login → Credentials Check → Device Trust Check → Immediate Access` Fastest path with access/refresh tokens issued immediately 3. Login on New Device (MFA) `Login → Credentials Check → New Device Detected → Auto-send MFA Email → MFA Dialog → Code Verification → Access Granted` Optional device trust for future logins 4. App Initialization & Token Management `App Start → Check Tokens → Auto-refresh if needed → Load Dashboard` Handles expired tokens gracefully # 🛡️ Security Features Covered ## Rate Limiting & Protection * Login attempt limiting * MFA resend limiting (max 3) * Verification email rate limiting * Account lockout for abuse ## Token Management * Access token expiration handling * Refresh token rotation * Token blacklisting on logout * Force logout on revoked tokens ## Device Security * Device fingerprinting * Trusted device management * MFA for new devices * Device removal capabilities # 🔄 Key Decision Points 1. Has Valid Tokens? → Dashboard vs Login 2. Trusted Device? → Immediate access vs MFA 3. Account Active? → Login vs Error message 4. MFA Code Valid? → Success vs Retry/Lock 5. Token Expired? → Refresh vs Re-login # 📱 User Experience Flows ## Happy Path (Returning User) `App Start → Valid Tokens → Dashboard (2 steps)` ## New User Journey `Registration → Email Verification → Login → Dashboard (4 steps)` ## New Device Login `Login → MFA Email → Code Entry → Dashboard (3 steps)` ## 🔧 Implementation Notes **Background Tasks**: Email sending doesn't block user flow **Error Recovery**: Clear paths back to working states **Admin Features**: User management and security monitoring **Future Features**: Password reset flow is mapped out # Flow Diagram This diagram serves as the complete authentication architecture reference, showing every possible user journey and system state transition. ``` flowchart TD %% ================================ %% REGISTRATION FLOWS %% ================================ Start([User Visits App]) --> CheckTokens{Has Valid Tokens?} CheckTokens -->|Yes| LoadUser[Load User Profile] CheckTokens -->|No| LandingPage[Landing Page] LandingPage --> RegisterChoice{Registration Type} RegisterChoice --> CandidateReg[Candidate Registration Form] RegisterChoice --> EmployerReg[Employer Registration Form] RegisterChoice --> LoginPage[Login Page] %% Candidate Registration Flow CandidateReg --> CandidateValidation{Form Valid?} CandidateValidation -->|No| CandidateReg CandidateValidation -->|Yes| CandidateSubmit[POST /candidates] CandidateSubmit --> CandidateCheck{User Exists?} CandidateCheck -->|Yes| CandidateError[Show Error: User Exists] CandidateError --> CandidateReg CandidateCheck -->|No| CandidateEmailSent[Auto-send Verification Email] CandidateEmailSent --> CandidateSuccess[Show Success Dialog] %% Employer Registration Flow EmployerReg --> EmployerValidation{Form Valid?} EmployerValidation -->|No| EmployerReg EmployerValidation -->|Yes| EmployerSubmit[POST /employers] EmployerSubmit --> EmployerCheck{User Exists?} EmployerCheck -->|Yes| EmployerError[Show Error: User Exists] EmployerError --> EmployerReg EmployerCheck -->|No| EmployerEmailSent[Auto-send Verification Email] EmployerEmailSent --> EmployerSuccess[Show Success Dialog] %% Email Verification Flow CandidateSuccess --> CheckEmail[User Checks Email] EmployerSuccess --> CheckEmail CheckEmail --> ClickLink[Click Verification Link] ClickLink --> VerifyEmail[GET /verify-email?token=xxx] VerifyEmail --> TokenValid{Token Valid & Not Expired?} TokenValid -->|No| VerifyError[Show Error: Invalid/Expired Token] TokenValid -->|Yes| ActivateAccount[Activate Account in DB] ActivateAccount --> VerifySuccess[Show Success: Account Activated] VerifySuccess --> RedirectLogin[Redirect to Login] %% Resend Verification VerifyError --> ResendOption{Resend Verification?} ResendOption -->|Yes| ResendEmail[POST /auth/resend-verification] ResendEmail --> RateLimitCheck{Within Rate Limits?} RateLimitCheck -->|No| ResendError[Show Rate Limit Error] RateLimitCheck -->|Yes| FindPending{Pending Verification Found?} FindPending -->|No| ResendGeneric[Generic Success Message] FindPending -->|Yes| ResendSuccess[New Email Sent] ResendSuccess --> CheckEmail ResendGeneric --> CheckEmail ResendOption -->|No| RegisterChoice %% ================================ %% LOGIN FLOWS %% ================================ RedirectLogin --> LoginPage LoginPage --> LoginForm[Enter Email/Password] LoginForm --> LoginSubmit[POST /auth/login] LoginSubmit --> CredentialsValid{Credentials Valid?} CredentialsValid -->|No| LoginError[Show Login Error] LoginError --> LoginForm CredentialsValid -->|Yes| AccountActive{Account Active?} AccountActive -->|No| AccountError[Show Account Status Error] AccountError --> LoginForm AccountActive -->|Yes| DeviceCheck{Trusted Device?} %% Trusted Device Flow DeviceCheck -->|Yes| TrustedLogin[Update Last Login] TrustedLogin --> IssueTokens[Issue Access + Refresh Tokens] IssueTokens --> LoginSuccess[Store Tokens Locally] LoginSuccess --> LoadUser %% New Device Flow (MFA Required) DeviceCheck -->|No| NewDevice[Detect New Device] NewDevice --> GenerateMFA[Generate 6-digit MFA Code] GenerateMFA --> SendMFAEmail[Auto-send MFA Email] SendMFAEmail --> MFAResponse[Return MFA Required Response] MFAResponse --> ShowMFADialog[Show MFA Input Dialog] ShowMFADialog --> MFAInput[User Enters 6-digit Code] MFAInput --> MFASubmit[POST /auth/mfa/verify] MFASubmit --> MFAValid{Code Valid & Not Expired?} MFAValid -->|No| MFAError[Show MFA Error] MFAError --> MFARetry{Attempts < 5?} MFARetry -->|Yes| MFAInput MFARetry -->|No| MFALocked[Lock MFA Session] MFALocked --> LoginForm MFAValid -->|Yes| RememberDevice{Remember Device?} RememberDevice -->|Yes| AddTrustedDevice[Add to Trusted Devices] RememberDevice -->|No| SkipTrust[Skip Adding Device] AddTrustedDevice --> MFASuccess[Update Last Login] SkipTrust --> MFASuccess MFASuccess --> IssueTokens %% MFA Resend Flow ShowMFADialog --> MFAResend{Need Resend?} MFAResend -->|Yes| ResendMFA[POST /auth/mfa/resend] ResendMFA --> ResendLimit{< 3 Resends?} ResendLimit -->|No| ResendLocked[Max Resends Reached] ResendLocked --> LoginForm ResendLimit -->|Yes| NewMFACode[Generate New Code] NewMFACode --> SendNewMFA[Send New Email] SendNewMFA --> ShowMFADialog %% ================================ %% APP INITIALIZATION & TOKEN MANAGEMENT %% ================================ LoadUser --> TokenExpired{Access Token Expired?} TokenExpired -->|No| Dashboard[Load Dashboard] TokenExpired -->|Yes| RefreshCheck{Has Refresh Token?} RefreshCheck -->|No| ClearTokens[Clear Local Storage] ClearTokens --> LandingPage RefreshCheck -->|Yes| RefreshAttempt[POST /auth/refresh] RefreshAttempt --> RefreshValid{Refresh Token Valid?} RefreshValid -->|No| ClearTokens RefreshValid -->|Yes| NewTokens[Issue New Access Token] NewTokens --> UpdateStorage[Update Local Storage] UpdateStorage --> Dashboard %% ================================ %% LOGOUT FLOWS %% ================================ Dashboard --> LogoutChoice{Logout Type} LogoutChoice --> SingleLogout[Logout This Device] LogoutChoice --> LogoutAll[Logout All Devices] SingleLogout --> LogoutRequest[POST /auth/logout] LogoutRequest --> BlacklistTokens[Blacklist Tokens] BlacklistTokens --> LogoutComplete[Clear Local Storage] LogoutAll --> LogoutAllRequest[POST /auth/logout-all] LogoutAllRequest --> RevokeAllTokens[Revoke All User Tokens] RevokeAllTokens --> LogoutComplete LogoutComplete --> LandingPage %% ================================ %% ERROR HANDLING & EDGE CASES %% ================================ Dashboard --> TokenRevoked{Token Blacklisted?} TokenRevoked -->|Yes| ForceLogout[Force Logout] ForceLogout --> ClearTokens %% Rate Limiting LoginForm --> RateLimit{Too Many Attempts?} RateLimit -->|Yes| AccountLock[Temporary Account Lock] AccountLock --> LockMessage[Show Lockout Message] LockMessage --> WaitPeriod[Wait for Unlock] WaitPeriod --> LoginForm %% Network Errors LoginSubmit --> NetworkError{Network Error?} NetworkError -->|Yes| RetryLogin[Show Retry Option] RetryLogin --> LoginForm %% ================================ %% ADMIN FLOWS (Optional) %% ================================ Dashboard --> AdminCheck{Is Admin?} AdminCheck -->|Yes| AdminPanel[Admin Panel] AdminPanel --> ManageVerifications[Manage Pending Verifications] AdminPanel --> ViewSecurityLogs[View Security Logs] AdminPanel --> ManageUsers[Manage User Accounts] AdminCheck -->|No| Dashboard %% ================================ %% PASSWORD RESET FLOW (Future) %% ================================ LoginForm --> ForgotPassword[Forgot Password Link] ForgotPassword --> ResetEmail[Enter Email for Reset] ResetEmail --> ResetRequest[POST /auth/password-reset/request] ResetRequest --> ResetEmailSent[Password Reset Email Sent] ResetEmailSent --> ResetLink[Click Reset Link in Email] ResetLink --> ResetForm[Enter New Password] ResetForm --> ResetSubmit[POST /auth/password-reset/confirm] ResetSubmit --> ResetSuccess[Password Reset Successfully] ResetSuccess --> LoginForm %% ================================ %% DEVICE MANAGEMENT %% ================================ Dashboard --> DeviceSettings[Device Settings] DeviceSettings --> ViewDevices[View Trusted Devices] ViewDevices --> RemoveDevice[Remove Trusted Device] RemoveDevice --> DeviceRemoved[Device Removed Successfully] DeviceRemoved --> ViewDevices %% ================================ %% STYLING %% ================================ classDef startEnd fill:#e1f5fe classDef process fill:#f3e5f5 classDef decision fill:#fff3e0 classDef error fill:#ffebee classDef success fill:#e8f5e8 classDef security fill:#fce4ec class Start,LandingPage startEnd class LoginSuccess,VerifySuccess,MFASuccess,Dashboard success class LoginError,VerifyError,MFAError,AccountError error class DeviceCheck,TokenValid,CredentialsValid,MFAValid decision class GenerateMFA,SendMFAEmail,BlacklistTokens security ```