Authentication Flow
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The Authentication Flow in this project provides a secure mechanism for user identity management, encompassing registration, login, token-based session handling, and logout procedures. It utilizes a JSON Web Token (JWT) architecture with a dual-token system (Access and Refresh tokens) to balance security and user experience.
The system is split between a React-based frontend that interacts with a Node.js/Express backend. The backend persists user data using Mongoose/MongoDB, ensuring passwords are encrypted via bcrypt before storage.
Sources: BACKEND/src/controllers/user.controller.js, BACKEND/src/models/User.model.js, frontend/front/src/services/api.js
Data Models and Security
The core of the authentication system is the User model, which defines the schema for user credentials and security tokens.
User Schema
| Field | Type | Description | Constraints |
|---|---|---|---|
| username | String | Unique identifier for the user | Required, Unique, Lowercase, Indexed |
| String | User's electronic mail address | Required, Unique, Lowercase | |
| fullName | String | Full name of the user | Required, Indexed |
| password | String | Hashed user password | Required |
| refreshToken | String | Token used to generate new access tokens | Optional |
Sources: BACKEND/src/models/User.model.js:5-40
Password Handling
Passwords are never stored in plain text. A pre-save hook in the Mongoose schema automatically hashes the password using bcrypt with a salt factor of 10 whenever the password field is modified.
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});
Sources: BACKEND/src/models/User.model.js:42-47
Registration Flow
The registration process creates a new user entity in the database. The system checks for existing users with the same email or username to prevent duplicates.
Registration Sequence
The following diagram illustrates the interaction between the frontend, API service, and backend controller during registration.
Login and Token Management
The login flow validates credentials and issues two types of JWTs: an Access Token for short-term authorization and a Refresh Token for session persistence.
Token Generation Logic
Tokens are generated using instance methods on the User model. The Access Token contains user metadata (id, email, username), while the Refresh Token contains only the user ID.
| Token Type | Secret Key | Lifetime Configuration |
|---|---|---|
| Access Token | ACCESS_TOKEN_SECRET | ACCESS_TOKEN_EXPIRY |
| Refresh Token | REFRESH_TOKEN_SECRET | REFRESH_TOKEN_EXPIRY |
Sources: BACKEND/src/models/User.model.js:52-78
Login Flow Diagram
This flowchart describes the logic within the loginUser controller.
Session Maintenance
The frontend maintains the session by storing the access token in localStorage and attaching it to subsequent requests via an Axios interceptor.
API Interceptor
The api.js service configures a global interceptor that automatically injects the Authorization header.
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
Sources: frontend/front/src/services/api.js:14-21
Token Refreshing
When an access token expires, the client can call the /refreshtoken endpoint. The backend verifies the incoming refresh token against the one stored in the database for that user before issuing a new pair.
Sources: BACKEND/src/controllers/user.controller.js:203-247, BACKEND/src/routes/user.routes.js:27
Logout and Security Middleware
Logout is a secured operation that clears the user's refresh token from the database and deletes the cookies from the client browser.
Secured Route Configuration
Routes like /logout and /changepassword are protected by the verifyJWT middleware, which ensures the requester has a valid access token.
| Endpoint | Method | Middleware | Controller |
|---|---|---|---|
/register | POST | registerRateLimiter | registerUser |
/login | POST | None | loginUser |
/logout | POST | logoutRateLimiter, verifyJWT | logoutUser |
/refreshtoken | POST | None | refreshAccessToken |
Sources: BACKEND/src/routes/user.routes.js:16-31
Conclusion
The authentication flow implements a robust JWT-based system. By utilizing bcrypt for hashing, HttpOnly cookies for token delivery, and rate limiting on sensitive routes, the architecture provides a secure foundation for user interactions. The separation of concerns between the Mongoose model (security logic), Express controllers (business logic), and React services (API consumption) ensures the system remains maintainable.