Skip to content

Commit 6629834

Browse files
committed
Docker compose build works. Just debugging functionality and fix bugs
1 parent 828a620 commit 6629834

6 files changed

Lines changed: 33 additions & 31 deletions

File tree

src/api/v1/controllers/user-controller.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const expressAsyncHandler = require("express-async-handler");
22
const { sendSuccessResponse } = require("../../../utils/helpers");
33
const { registerUserService, loginUserService, getCurrentUserService, refreshAccessTokenService } = require("../../../services/users/user-service");
44
const { StatusCodes } = require("http-status-codes");
5+
const logger = require("../../../utils/logger");
56

67
/**
78
* Handles an HTTP POST request to register a new user.
@@ -31,11 +32,16 @@ const registerUser = expressAsyncHandler(async (request, response) => {
3132
* Handles an HTTP POST request to authenticate and log in an existing user.
3233
*/
3334
const loginUser = expressAsyncHandler(async (request, response) => {
34-
// Extract email and password from the request body.
35-
const userCredentials = request.body;
36-
3735
// Generate tokens after authentication
38-
const { userDB, accessToken } = await loginUserService(userCredentials);
36+
const { userDB, accessToken, refreshToken } = await loginUserService(request.body);
37+
38+
// Set the refresh token as an HTTP-only cookie for secure storage on the client side.
39+
response.cookie("refreshToken", refreshToken, {
40+
httpOnly: true, // Prevents client-side JavaScript access to the cookie.
41+
secure: process.env.NODE_ENV === "production", // Only send over HTTPS in production.
42+
sameSite: "strict", // Protects against CSRF attacks.
43+
maxAge: 7 * 24 * 60 * 60 * 1000 // Cookie expiration in 7 days.
44+
});
3945

4046
sendSuccessResponse(
4147
response,
@@ -93,6 +99,14 @@ const logoutUser = expressAsyncHandler(async (request, response) => {
9399
// Invalidate the user's refresh token
94100
await loginUserService(request.cookies.refreshToken);
95101

102+
// Clear the 'refreshToken' cookie from the client's browser.
103+
// The options must match those used when setting the cookie during login.
104+
response.clearCookie("refreshToken", {
105+
httpOnly: true, // Must match the `httpOnly` setting used when the cookie was set.
106+
secure: process.env.NODE_ENV === "production", // Must match `secure` setting.
107+
sameSite: "Strict" // Must match `sameSite` setting.
108+
});
109+
96110
sendSuccessResponse(
97111
response,
98112
StatusCodes.OK,

src/docs/swagger.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@ const logger = require("../utils/logger");
2525
*/
2626
const setupSwaggerDocs = async (app) => {
2727
// Load the OpenAPI definition from the YAML file.
28-
const swaggerPath = path.join(__dirname, "swagger.yml");
29-
const swaggerDocument = YAML.load('');
28+
const swaggerDocument = YAML.load('src/docs/swagger.yml');
3029

3130
// Serve Swagger UI at /api-docs with the loaded document.
3231
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));

src/middleware/api-rate-limiter.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ const rateLimit = require('express-rate-limit');
22

33
// Apply to all requests
44
const limiter = rateLimit({
5-
windowMs: 15 * 60 * 1000, // 15 minutes
6-
max: 100, // limit each IP to 100 requests per windowMs
7-
message: 'Too many requests, please try again later.',
8-
standardHeaders: true,
9-
legacyHeaders: false,
5+
windowMs: 15 * 60 * 1000, // 15 minutes
6+
max: 100, // limit each IP to 100 requests per windowMs
7+
message: 'Too many requests, please try again later.',
8+
standardHeaders: true,
9+
legacyHeaders: false,
1010
});
1111

1212
module.exports = limiter;

src/middleware/authorize-routes.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const ApiError = require("../utils/api-error");
44
const expressAsyncHandler = require("express-async-handler");
55
const { StatusCodes } = require("http-status-codes");
66
const { findUserById } = require("../database/models/user-model");
7+
const User = require("../database/schemas/user-schema");
78

89
/**
910
* Checks if a request has a valid authorization header and verifies its value (the acess token).
@@ -22,7 +23,7 @@ const authRouteProtection = expressAsyncHandler(async (request, response, next)
2223
logger.info(`Token verified for user ID: ${decoded.id}`);
2324

2425
// Get user from token without password
25-
request.user = await findUserById(decoded.id).select("-password");
26+
request.user = await User.findById(decoded.id).select("-password");
2627

2728
if (!request.user) {
2829
logger.error(`User not found for with the id: ${decoded.id}`);

src/middleware/error-handler.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ const COMMON_ERRORS_MAP = {
5858
* @returns {void}
5959
*/
6060
const errorHandler = (error, request, response, next) => {
61+
if (response.headersSent) {
62+
return next(error); // Delegate to Express's built-in error handler
63+
}
64+
6165
// Ensure response status is an error, defaulting to 500
6266
const statusCode = error.status >= 400 && error.status < 500 ? error.status: 500;
6367

src/services/users/user-service.js

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,7 @@ async function registerUserService(userData) {
6767
const userObj = {
6868
username,
6969
email,
70-
password: hashedPassword,
71-
role: "role"
70+
password: hashedPassword
7271
}
7372

7473
const userDB = await createUser(userObj);
@@ -154,17 +153,10 @@ async function loginUserService(userCredentials) {
154153
userDB.refreshToken = refreshToken;
155154
await userDB.save();
156155

157-
// Set the refresh token as an HTTP-only cookie for secure storage on the client side.
158-
response.cookie("refreshToken", refreshToken, {
159-
httpOnly: true, // Prevents client-side JavaScript access to the cookie.
160-
secure: process.env.NODE_ENV === "production", // Only send over HTTPS in production.
161-
sameSite: "strict", // Protects against CSRF attacks.
162-
maxAge: 7 * 24 * 60 * 60 * 1000 // Cookie expiration in 7 days.
163-
});
164-
165156
return {
166157
userDB,
167-
accessToken
158+
accessToken,
159+
refreshToken
168160
}
169161
}
170162

@@ -289,14 +281,6 @@ async function logoutUserService(token) {
289281
user.refreshToken = null; // Set the refresh token to null to invalidate it.
290282
await user.save(); // Save the updated user document.
291283

292-
// Clear the 'refreshToken' cookie from the client's browser.
293-
// The options must match those used when setting the cookie during login.
294-
response.clearCookie("refreshToken", {
295-
httpOnly: true, // Must match the `httpOnly` setting used when the cookie was set.
296-
secure: process.env.NODE_ENV === "production", // Must match `secure` setting.
297-
sameSite: "Strict" // Must match `sameSite` setting.
298-
});
299-
300284
logger.debug(`The refresh token: ${token} has been invalidated.`);
301285
}
302286

0 commit comments

Comments
 (0)