Auth Request Handling and Service Boundary

Overview

AuthController exposes the authentication and verification entrypoints for Bank ASAP and delegates every request to AuthService. The controller does not branch on success or failure itself; it converts the returned message string into AuthResponse and sends it back with ResponseEntity.ok.

AuthService owns the actual sign-up, verification, login, resend, and account-lock behavior. It coordinates three boundaries: user persistence through UserRepository, password hashing and verification through PasswordEncoder, and email delivery through EmailService. The service also keeps transient sign-up state in memory with pendingSignUps.

Request Handling Boundary

Controller method Request type Service call Response shape
signUp SignUpRequest authService.signUp(request.getEmail(), request.getPassword(), request.getConfirmPassword()) ResponseEntity<AuthResponse>
verifySignUp VerifySignUpRequest authService.verifySignUp(request.getEmail(), request.getCode()) ResponseEntity<AuthResponse>
resendSignUpCode ResendSignUpCodeRequest authService.resendSignUpCode(request.getEmail()) ResponseEntity<AuthResponse>
login LoginRequest authService.login(request.getEmail(), request.getPassword()) ResponseEntity<AuthResponse>
verifyCode VerifyCodeRequest authService.verifyCode(request.getEmail(), request.getCode()) ResponseEntity<AuthResponse>
resendCode ResendCodeRequest authService.resendCode(request.getEmail()) ResponseEntity<AuthResponse>

Component Interaction Overview

flowchart TB
    subgraph httpLayer[HTTP Layer]
        c1[AuthController]
        r1[ResponseEntity]
        d1[AuthResponse]
    end

    subgraph serviceBoundary[Service Boundary]
        s1[AuthService]
        e1[EmailService]
    end

    subgraph persistenceBoundary[Persistence Boundary]
        u1[UserRepository]
        p1[PendingSignUp]
    end

    subgraph supportBoundary[Support Boundary]
        pe1[PasswordEncoder]
        m1[JavaMailSender]
    end

    c1 -->|signUp verifySignUp resendSignUpCode login verifyCode resendCode| s1
    s1 -->|sendTwoFactorCode sendAccountLockedEmail| e1
    s1 -->|save findAll| u1
    s1 -->|encode matches| pe1
    e1 -->|send| m1
    s1 -->|create update remove| p1
    c1 --> r1
    c1 --> d1

HTTP Endpoints

Sign Up

[!NOTE] Every controller method returns ResponseEntity.ok(new AuthResponse(message)), so both success paths and validation or state errors use the same HTTP 200 wrapper and differ only by the message value.

src/main/java/com/bankasap/controller/AuthController.java

AuthController.signUp accepts SignUpRequest, extracts email, password, and confirmPassword, and forwards them to AuthService.signUp. The service validates the input, creates a pending sign-up record, and sends a verification code by email.

Sign Up

{
    "title": "Sign Up",
    "description": "Creates a pending sign-up record, validates the submitted credentials, and sends a verification code to the supplied email address.",
    "method": "POST",
    "baseUrl": "",
    "endpoint": "/signup",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"password\": \"SecurePass1!\",\n    \"confirmPassword\": \"SecurePass1!\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Returns a message confirming that the verification code was sent or explaining why sign-up was rejected.",
            "body": "{\n    \"message\": \"Signup verification code sent to email\"\n}"
        }
    }
}

Verify Sign Up

src/main/java/com/bankasap/controller/AuthController.java

AuthController.verifySignUp forwards email and code to AuthService.verifySignUp. The service looks up the pending sign-up record, checks expiration, compares the code, and persists a new User when verification succeeds.

Verify Sign Up

{
    "title": "Verify Sign Up",
    "description": "Completes registration for a pending sign-up record after the submitted verification code is checked.",
    "method": "POST",
    "baseUrl": "",
    "endpoint": "/verify-signup",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"code\": \"A1B2C3D4E5\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Returns the verification outcome as a message.",
            "body": "{\n    \"message\": \"User registered successfully\"\n}"
        }
    }
}

Resend Sign Up Code

src/main/java/com/bankasap/controller/AuthController.java

AuthController.resendSignUpCode passes email to AuthService.resendSignUpCode. The service requires an existing pending sign-up record, generates a replacement code, refreshes the expiration timestamp, and sends the new code by email.

Resend Sign Up Code

{
    "title": "Resend Sign Up Code",
    "description": "Issues a new verification code for an existing pending sign-up request and refreshes the pending expiration time.",
    "method": "POST",
    "baseUrl": "",
    "endpoint": "/resend-signup-code",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Returns the resend outcome as a message.",
            "body": "{\n    \"message\": \"New signup verification code sent to email\"\n}"
        }
    }
}

Login

src/main/java/com/bankasap/controller/AuthController.java

AuthController.login forwards email and password to AuthService.login. The service looks up the stored User, enforces lock state, checks the password with PasswordEncoder, updates failed-attempt counters, and sends a two-factor code after a successful password match.

Login

{
    "title": "Login",
    "description": "Verifies credentials, updates failed login state, and sends a two-factor code when the password is accepted.",
    "method": "POST",
    "baseUrl": "",
    "endpoint": "/login",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"password\": \"SecurePass1!\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Returns the login outcome as a message.",
            "body": "{\n    \"message\": \"2FA code sent to email\"\n}"
        }
    }
}

Verify Code

src/main/java/com/bankasap/controller/AuthController.java

AuthController.verifyCode sends email and code to AuthService.verifyCode. The service checks the stored two-factor code, validates expiration, clears the code fields on success, and returns the login result message.

Verify Code

{
    "title": "Verify Code",
    "description": "Confirms the login two-factor code for an existing user and clears the stored code state after success.",
    "method": "POST",
    "baseUrl": "",
    "endpoint": "/verify-code",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"code\": \"A1B2C3D4E5\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Returns the verification outcome as a message.",
            "body": "{\n    \"message\": \"Login successful\"\n}"
        }
    }
}

Resend Login Code

src/main/java/com/bankasap/controller/AuthController.java

AuthController.resendCode passes email to AuthService.resendCode. The service checks the user record, honors the current lock state, generates a replacement two-factor code, refreshes its expiration, and emails the new code.

Resend Login Code

{
    "title": "Resend Login Code",
    "description": "Sends a new two-factor login code for an existing user record and refreshes the code expiration time.",
    "method": "POST",
    "baseUrl": "",
    "endpoint": "/resend-login-code",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Returns the resend outcome as a message.",
            "body": "{\n    \"message\": \"New 2FA code sent to email\"\n}"
        }
    }
}

Service Workflows

Sign Up and Verification Flow

AuthService.signUp, verifySignUp, and resendSignUpCode manage a temporary in-memory sign-up state before persistence happens. The service stores a PendingSignUp object with the email, hashed password, code, and expiration time, then removes that entry after successful verification or after expiration is detected.

sequenceDiagram
    participant u as User
    participant c as AuthController
    participant s as AuthService
    participant e as EmailService
    participant r as UserRepository

    u->>c: signUp
    c->>s: signUp
    s->>r: findAll
    s->>s: isValidEmail
    s->>s: isValidPassword
    s->>s: generateTwoFactorCode
    s->>e: sendTwoFactorCode
    c-->>u: AuthResponse

    u->>c: verifySignUp
    c->>s: verifySignUp
    s->>s: findPendingSignUpByEmail
    alt code valid and not expired
        s->>r: save
        s->>s: remove pendingSignUp
        c-->>u: AuthResponse
    else expired or invalid
        s-->>c: message
        c-->>u: AuthResponse
    end

    u->>c: resendSignUpCode
    c->>s: resendSignUpCode
    s->>s: findPendingSignUpByEmail
    s->>s: setCode
    s->>s: setCodeExpiresAt
    s->>e: sendTwoFactorCode
    c-->>u: AuthResponse

Workflow details:

  • signUp rejects duplicate emails before any other checks.
  • signUp validates email syntax through isValidEmail.
  • signUp validates password content through isValidPassword.
  • signUp requires password and confirmPassword to match.
  • signUp hashes the password with passwordEncoder.encode(password).
  • signUp replaces any previous pending record for the same email.
  • verifySignUp removes expired pending records before returning.
  • verifySignUp creates User with the pending email and hashed password.
  • resendSignUpCode only works when a pending record already exists.

Login and Two Factor Flow

AuthService.login, verifyCode, and resendCode control the login path after a user record exists. The service stores the current two-factor code and expiration on the User record, while failed password attempts increment a counter and can lock the account.

sequenceDiagram
    participant u as User
    participant c as AuthController
    participant s as AuthService
    participant e as EmailService
    participant r as UserRepository

    u->>c: login
    c->>s: login
    s->>r: findAll
    alt user locked
        s-->>c: message
        c-->>u: AuthResponse
    else password mismatch
        s->>s: setFailedLoginAttempts
        alt attempts reached threshold
            s->>s: setLockedUntil
            s-->>c: message
            c-->>u: AuthResponse
        else attempts below threshold
            s-->>c: message
            c-->>u: AuthResponse
        end
    else password matches
        s->>s: setFailedLoginAttempts
        s->>s: setLockedUntil
        s->>s: generateTwoFactorCode
        s->>s: setTwoFactorCode
        s->>s: setTwoFactorCodeExpiresAt
        s->>e: sendTwoFactorCode
        c-->>u: AuthResponse
    end

    u->>c: verifyCode
    c->>s: verifyCode
    s->>s: findUserByEmail
    alt code valid and not expired
        s->>s: setTwoFactorCode
        s->>s: setTwoFactorCodeExpiresAt
        c-->>u: AuthResponse
    else invalid or expired
        s-->>c: message
        c-->>u: AuthResponse
    end

    u->>c: resendCode
    c->>s: resendCode
    s->>s: findUserByEmail
    s->>s: setTwoFactorCode
    s->>s: setTwoFactorCodeExpiresAt
    s->>e: sendTwoFactorCode
    c-->>u: AuthResponse

Validation and State Rules

Area Implemented rule Code path
Email validation Requires a non-null value containing one @ and at least one . isValidEmail
Password validation [REDACTED] isValidPassword
Sign-up code generation Produces a 10-character code from uppercase letters and digits generateTwoFactorCode
Sign-up code lifetime Set to 10 minutes from creation or resend signUp, resendSignUpCode
Login code lifetime Set to 10 minutes from generation or resend login, resendCode
Login failure tracking Increments failed attempts and locks the account on the third failure login
Code cleanup Clears two-factor code fields after successful verification or after expiry verifyCode

Email Service

EmailService

[!WARNING] login sets lockedUntil with LocalDateTime.now().plusSeconds(15), but the returned message says Account locked for 15 minutes. The stored lock duration and the text returned to the client do not match. [!IMPORTANT] EmailService.sendAccountLockedEmail exists, but AuthService.login does not call it. The lock branch updates the User record and returns a message without sending a lock notification email.

src/main/java/com/bankasap/service/EmailService.java

EmailService is the email delivery boundary used by AuthService. It constructs SimpleMailMessage instances and sends them through JavaMailSender for two-factor delivery and lock notifications.

Constructor Dependencies

Type Description
JavaMailSender Sends the built SimpleMailMessage objects.

Properties

Property Type Description
mailSender JavaMailSender Transport used to send the generated mail messages.

Public Methods

Method Description
sendTwoFactorCode Creates a message with subject Bank ASAP - 2FA Code and text Your Bank ASAP authentication code is: plus the generated code, then sends it to the supplied recipient.
sendAccountLockedEmail Creates a message with subject Bank ASAP - Account Locked and the fixed lock notice body, then sends it to the supplied recipient.

Injection and Call Sites

Injected by Usage
AuthService Sends verification codes during signUp, resendSignUpCode, login, and resendCode.
sequenceDiagram
    participant s as AuthService
    participant e as EmailService
    participant m as JavaMailSender
    participant msg as SimpleMailMessage

    s->>e: sendTwoFactorCode
    e->>msg: setTo
    e->>msg: setSubject
    e->>msg: setText
    e->>m: send

    s->>e: sendAccountLockedEmail
    e->>msg: setTo
    e->>msg: setSubject
    e->>msg: setText
    e->>m: send

Auth Controller

src/main/java/com/bankasap/controller/AuthController.java

AuthController is the REST boundary for the authentication workflow. It groups the endpoints under @RequestMapping("/auth"), injects AuthService, and exposes six POST handlers that return AuthResponse payloads.

Constructor Dependencies

Type Description
AuthService Handles sign-up, verification, login, and resend logic for every controller method.

Properties

Property Type Description
authService AuthService Service boundary used by every endpoint handler.

Public Methods

Method Description
signUp Reads SignUpRequest, calls authService.signUp, and wraps the returned message in AuthResponse.
verifySignUp Reads VerifySignUpRequest, calls authService.verifySignUp, and wraps the returned message in AuthResponse.
resendSignUpCode Reads ResendSignUpCodeRequest, calls authService.resendSignUpCode, and wraps the returned message in AuthResponse.
login Reads LoginRequest, calls authService.login, and wraps the returned message in AuthResponse.
verifyCode Reads VerifyCodeRequest, calls authService.verifyCode, and wraps the returned message in AuthResponse.
resendCode Reads ResendCodeRequest, calls authService.resendCode, and wraps the returned message in AuthResponse.

Auth Service

src/main/java/com/bankasap/service/AuthService.java

AuthService contains the full sign-up, verification, login, and 2FA logic. It bridges the controller to persistence and email delivery, and it also keeps temporary sign-up records in the private pendingSignUps list.

Constructor Dependencies

Type Description
EmailService Sends sign-up and login verification codes.
PasswordEncoder [REDACTED]
UserRepository Loads existing users and saves new users after sign-up verification.

Properties

Property Type Description
emailService EmailService Email boundary used for code delivery.
passwordEncoder PasswordEncoder Password hashing and matching boundary.
pendingSignUps List<PendingSignUp> In-memory pending sign-up records awaiting verification.
userRepository UserRepository Persistence boundary for User records.
formatter DateTimeFormatter Formats the lockedUntil timestamp in lock messages.

Public Methods

Method Description
signUp Validates the supplied email and password, creates or replaces a pending sign-up record, and sends a verification code.
verifySignUp Checks a pending sign-up code, expires invalid records, and persists a new User on success.
resendSignUpCode Requires an existing pending sign-up record, regenerates the code, refreshes expiration, and sends a replacement email.
login Checks the stored password, manages failed-attempt state and lock state, and sends a two-factor code when the password matches.
verifyCode Checks the stored login two-factor code, expires invalid codes, and clears the code state on success.
resendCode Requires an existing user, respects lock state, regenerates the login two-factor code, and sends a replacement email.

State Management

State holder Fields or methods involved Lifecycle
pendingSignUps add, remove, findPendingSignUpByEmail, setCode, setCodeExpiresAt Created by signUp, updated by resendSignUpCode, removed by verifySignUp after success or expiration.
Pending sign-up record email, hashedPassword, code, codeExpiresAt Holds registration state until verification is complete.
Persisted user record findUserByEmail, setFailedLoginAttempts, setLockedUntil, setTwoFactorCode, setTwoFactorCodeExpiresAt Holds login and 2FA state across login, resend, verification, and lock behavior.