Backend Authentication Module
Relevant source files
The following files were used as context for generating this wiki page:
The Backend Authentication Module manages user identity, session persistence, and secure access to the marketplace platform. It handles user registration, login, logout, and token-based authentication using JSON Web Tokens (JWT).
The module integrates with MongoDB via Mongoose for data persistence and utilizes a caching layer to optimize user profile retrieval. It ensures security by hashing passwords with bcrypt and enforcing HTTP-only cookies for token storage.
Sources: marketplace-backend/app/src/modules/auth/auth.module.ts, marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:16-23
Core Architecture
The module follows a controller-service-repository pattern typical of NestJS applications. It registers dependencies for JWT handling, database interaction, and caching.
Module Configuration
The AuthModule configures the following global and local providers:
- JwtModule: Manages token signing and verification using a secret key and expiration settings from environment variables.
- CacheModule: Stores customer profile data to reduce database load.
- MongooseModule: Provides schemas for
CustomerandRoleentities. - Strategies: Implements
JwtStrategyfor protecting routes.
Sources: marketplace-backend/app/src/modules/auth/auth.module.ts:14-53
Authentication Components
The following table describes the primary components within the module:
| Component | Responsibility |
|---|---|
AuthController | Handles HTTP requests for registration, login, logout, and account info. |
AbstractTokensService | Interface for generating, decoding, and verifying JWTs. |
AbstractCustomersService | Manages business logic for customer entities and credential validation. |
CustomersRepository | Executes database operations and handles password hashing during creation. |
JwtStrategy | Validates tokens extracted from requests to authorize users. |
Sources: marketplace-backend/app/src/modules/auth/auth.module.ts:40-52, marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:26-31
Authentication Flow
The system uses a cookie-based JWT approach. When a user authenticates, the server generates a token and sets it as an HTTP-only cookie.
Login Sequence
This diagram illustrates the logic performed during a login request:
The sequence ensures that passwords are never stored or compared in plain text.
Sources: marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:60-72, marketplace-backend/app/src/repositories/impl/customers.repository.ts:20-30
API Endpoints
The AuthController exposes endpoints under the /api/v1/auth prefix.
| Method | Endpoint | Description |
|---|---|---|
GET | /account | Retrieves current user info from the JWT cookie. Uses cache for performance. |
POST | /register | Creates a new customer, hashes the password, and logs them in. |
POST | /login | Validates credentials and issues a JWT cookie. |
POST | /logout | Clears the JWT cookie and removes user data from cache. |
Sources: marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:34-85
Data Caching Logic
To minimize database lookups, the system caches CustomerDto objects using a key format: id_{customerId}.
- The
getAccountrequest first checks the cache. - If found, it returns the cached data.
- If not found, it queries the database and populates the cache.
- The cache is cleared upon logout.
Sources: marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:36-50, marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:77-83
Security Implementation
The module implements several security layers to protect user data:
Password Hashing
The CustomersRepository uses bcrypt with a salt factor of 10 to hash passwords before saving them to the database.
async createNewCustomer(registerRequest: RegisterRequestDto): Promise<Customer> {
const hashSalt: number = 10;
registerRequest.password = await hash(registerRequest.password, hashSalt);
// ... logic for roles and saving
}
Sources: marketplace-backend/app/src/repositories/impl/customers.repository.ts:20-25
Global Configuration
In main.ts, the application is configured to handle security headers and cookies:
- CORS: Enabled with
credentials: trueandexposedHeaders: 'Set-Cookie'to allow the frontend to receive and send the JWT cookie. - Cookie Parser: Middleware is registered to allow the controller to read
request.cookies. - HTTP-Only Cookies: Tokens are sent with the
httpOnly: trueflag to prevent client-side script access (XSS protection).
Sources: marketplace-backend/app/src/main.ts:25-33, marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:19-24
Data Dependencies
The module relies on the following external dependencies defined in package.json:
@nestjs/jwt&passport-jwt: For token generation and validation.bcrypt: For secure credential storage.cookie-parser: For handling authentication tokens in request headers.cache-manager: For the temporary storage of user sessions.
Sources: marketplace-backend/app/package.json:34-45
This authentication system provides a robust foundation for user management by combining secure storage, efficient data retrieval via caching, and industry-standard token-based session management.