-
-
Notifications
You must be signed in to change notification settings - Fork 103
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implemented session management #421
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -51,13 +51,17 @@ async function loginCustomer(req, res) { | |||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
try { | ||||||||||||||||||||||||||||||||||||||||||
const customer = await Customer.findOne({ email: req.body.email }); | ||||||||||||||||||||||||||||||||||||||||||
console.log("1"); | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
if (!customer) { | ||||||||||||||||||||||||||||||||||||||||||
return res.status(401).json({ error: "Invalid email or password" }); | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
const validPassword = await bcrypt.compare( | ||||||||||||||||||||||||||||||||||||||||||
req.body.password, | ||||||||||||||||||||||||||||||||||||||||||
customer.password | ||||||||||||||||||||||||||||||||||||||||||
); | ||||||||||||||||||||||||||||||||||||||||||
console.log("2"); | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
if (!validPassword) { | ||||||||||||||||||||||||||||||||||||||||||
return res.status(401).json({ error: "Invalid email or password" }); | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -67,12 +71,29 @@ async function loginCustomer(req, res) { | |||||||||||||||||||||||||||||||||||||||||
role: "customer", // Optional | ||||||||||||||||||||||||||||||||||||||||||
email: customer.email, // Optional | ||||||||||||||||||||||||||||||||||||||||||
}; | ||||||||||||||||||||||||||||||||||||||||||
console.log("3"); | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
const token = jwt.sign( | ||||||||||||||||||||||||||||||||||||||||||
payload, | ||||||||||||||||||||||||||||||||||||||||||
process.env.JWT_SECRET, | ||||||||||||||||||||||||||||||||||||||||||
{ expiresIn: "1h" } // Expires in 1 hour | ||||||||||||||||||||||||||||||||||||||||||
); | ||||||||||||||||||||||||||||||||||||||||||
res.json({ | ||||||||||||||||||||||||||||||||||||||||||
console.log("4"); | ||||||||||||||||||||||||||||||||||||||||||
console.log(req.session); | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
req.session.user = { | ||||||||||||||||||||||||||||||||||||||||||
id: customer._id, | ||||||||||||||||||||||||||||||||||||||||||
name: customer.name, | ||||||||||||||||||||||||||||||||||||||||||
}; | ||||||||||||||||||||||||||||||||||||||||||
console.log("5"); | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
res.cookie("authToken", token, { | ||||||||||||||||||||||||||||||||||||||||||
maxAge: 1000 * 60 * 60, | ||||||||||||||||||||||||||||||||||||||||||
httpOnly: true, | ||||||||||||||||||||||||||||||||||||||||||
secure: true, | ||||||||||||||||||||||||||||||||||||||||||
}); | ||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+132
to
+136
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Enhance cookie security settings. While the current cookie settings include basic security measures, they could be strengthened further. Consider adding these additional security options: res.cookie("authToken", token, {
maxAge: 1000 * 60 * 60,
httpOnly: true,
secure: true,
+ sameSite: 'strict',
+ path: '/',
}); 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
return res.json({ | ||||||||||||||||||||||||||||||||||||||||||
message: "Login successful", | ||||||||||||||||||||||||||||||||||||||||||
token, | ||||||||||||||||||||||||||||||||||||||||||
role: "customer", | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -83,6 +104,8 @@ async function loginCustomer(req, res) { | |||||||||||||||||||||||||||||||||||||||||
}, | ||||||||||||||||||||||||||||||||||||||||||
}); | ||||||||||||||||||||||||||||||||||||||||||
} catch (error) { | ||||||||||||||||||||||||||||||||||||||||||
console.log(error); | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
res.status(500).json({ error: "Internal server error" }); | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -112,8 +135,18 @@ async function resetPassword(req, res) { | |||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
async function logout(req, res){ | ||||||||||||||||||||||||||||||||||||||||||
req.session.destroy((err) => { | ||||||||||||||||||||||||||||||||||||||||||
if (err) { | ||||||||||||||||||||||||||||||||||||||||||
return res.status(500).send("Failed to log out."); | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
res.send("Logged out successfully!"); | ||||||||||||||||||||||||||||||||||||||||||
}); | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+181
to
+188
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add session validation before logout. The current implementation doesn't verify if a user is actually logged in before attempting to destroy the session. This could lead to unnecessary session operations and unclear error states. Apply this diff to enhance the logout implementation: async function logout(req, res){
+ if (!req.session.user) {
+ return res.status(401).send("No active session");
+ }
req.session.destroy((err) => {
if (err) {
+ console.error('Session destruction failed:', err);
return res.status(500).send("Failed to log out.");
}
res.send("Logged out successfully!");
});
} 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
module.exports = { | ||||||||||||||||||||||||||||||||||||||||||
createCustomer, | ||||||||||||||||||||||||||||||||||||||||||
loginCustomer, | ||||||||||||||||||||||||||||||||||||||||||
resetPassword, | ||||||||||||||||||||||||||||||||||||||||||
logout | ||||||||||||||||||||||||||||||||||||||||||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,6 +9,8 @@ const passport = require("passport"); | |
const { handleGoogleOAuth } = require("./controller/googleOAuth.controller"); | ||
const app = express(); | ||
const port = process.env.PORT || 3000; | ||
const session = require("express-session"); | ||
const MongoStore = require("connect-mongo"); | ||
|
||
// CORS configuration | ||
const corsOptions = { | ||
|
@@ -42,6 +44,21 @@ mongoose | |
// Initialize passport middleware | ||
app.use(passport.initialize()); | ||
|
||
app.use( | ||
session({ | ||
secret: process.env.SECRET_KEY, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Codebase verification Environment variables need validation at startup The application uses several critical environment variables (SECRET_KEY, MONGO_URI, JWT_SECRET, etc.) but lacks proper validation at startup. While dotenv is configured, there's no explicit validation to ensure required variables are present before the application starts. Key locations requiring attention:
Example validation to add at application startup: const requiredEnvVars = ['SECRET_KEY', 'MONGO_URI', 'JWT_SECRET'];
for (const envVar of requiredEnvVars) {
if (!process.env[envVar]) {
throw new Error(`Missing required environment variable: ${envVar}`);
}
} 🔗 Analysis chainVerify required environment variables The session configuration depends on Let me gather more information about how SECRET_KEY is used and if there's any validation. 🏁 Scripts executedThe following scripts were executed for the analysis: Script: #!/bin/bash
# Description: Check if required environment variables are documented
# Test: Check if SECRET_KEY is documented in .env.example
if [ -f .env.example ]; then
echo "Checking .env.example for SECRET_KEY..."
grep "SECRET_KEY" .env.example
fi
# Test: Look for environment variable validation
echo "Checking for environment variable validation..."
rg -l "SECRET_KEY" --type js
Length of output: 176 Script: #!/bin/bash
# Check the context around SECRET_KEY usage and look for validation patterns
rg "SECRET_KEY" -B 3 -A 3 --type js
# Look for common environment variable validation patterns
rg "(process\.env\.|dotenv|envalid|env\.required)" --type js -B 2 -A 2
Length of output: 8630 |
||
resave: false, | ||
saveUninitialized: false, | ||
cookie: { | ||
maxAge: 1000 * 60 * 60 * 24, | ||
secure: false, | ||
}, | ||
store: MongoStore.create({ | ||
mongoUrl: process.env.MONGO_URI, | ||
}), | ||
}) | ||
); | ||
Comment on lines
+47
to
+60
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Enhance session security configuration The current session configuration needs several security improvements:
Apply these security enhancements: app.use(
session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
- secure: false,
+ secure: process.env.NODE_ENV === 'production',
+ httpOnly: true,
+ sameSite: process.env.NODE_ENV === 'production' ? 'strict' : 'lax'
},
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI,
+ ttl: 24 * 60 * 60, // Session TTL in seconds
+ autoRemove: 'native',
+ touchAfter: 24 * 3600, // Refresh session only once per 24 hours
+ crypto: {
+ secret: process.env.SECRET_KEY
+ },
+ onError: function(error) {
+ logger.error('Session store error:', error);
+ }
}),
+ name: 'sessionId', // Change default cookie name
+ rolling: true, // Refresh cookie on each response
})
);
|
||
|
||
// API routes | ||
app.use("/api", require("./routes/index")); | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
const sessionMiddleware = async (req, res, next)=>{ | ||
console.log(req.session.user); | ||
|
||
|
||
Comment on lines
+1
to
+4
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove unnecessary async keyword and improve logging The current implementation has several issues:
Apply this diff to improve the implementation: -const sessionMiddleware = async (req, res, next)=>{
- console.log(req.session.user);
-
-
+const sessionMiddleware = (req, res, next) => {
+ req.log.debug('Session user:', req.session.user); Consider using a proper logging library like Winston or Pino for structured logging in production.
|
||
if (req.session.user !== undefined) { | ||
next(); | ||
} else { | ||
res.status(401).send("Invalid session. Please log in again."); | ||
} | ||
Comment on lines
+5
to
+9
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Codebase verification Based on the gathered information, I can now provide the final response: Session security improvements needed, but with modified recommendations The current session setup already includes several security measures:
However, the original review's suggested changes should be modified: - if (req.session.user !== undefined) {
+ if (!req.session) {
+ return res.status(500).json({
+ error: 'Session middleware not properly configured'
+ });
+ }
+
+ if (req.session.user &&
+ typeof req.session.user === 'object' &&
+ req.session.cookie.expires > Date.now()) {
next();
} else {
- res.status(401).send("Invalid session. Please log in again.");
+ res.status(401).json({
+ error: 'Authentication required',
+ message: 'Please log in to continue'
+ });
} Additional recommendations:
🔗 Analysis chainEnhance session validation security and error handling The current session validation could be more robust and secure. Apply this diff to improve security and error handling: - if (req.session.user !== undefined) {
+ if (!req.session) {
+ return res.status(500).json({
+ error: 'Session middleware not properly configured'
+ });
+ }
+
+ if (req.session.user && typeof req.session.user === 'object') {
next();
} else {
- res.status(401).send("Invalid session. Please log in again.");
+ res.status(401).json({
+ error: 'Authentication required',
+ message: 'Please log in to continue'
+ });
} Consider implementing these additional security measures:
Let's verify if CSRF protection is implemented elsewhere: Let me gather more information about the session configuration and CSRF protection. 🏁 Scripts executedThe following scripts were executed for the analysis: Script: #!/bin/bash
# Check for CSRF middleware or protection
rg -i "csrf|csurf" --type js
Length of output: 4524 Script: #!/bin/bash
# Check for session configuration and security middleware
echo "Checking for session configuration..."
rg -A 5 "express-session|cookie|csrf" --type js
echo -e "\nChecking main application setup..."
rg -A 10 "const express|const app" --type js
Length of output: 9913 |
||
} | ||
|
||
module.exports = sessionMiddleware; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,9 +16,11 @@ | |
"description": "", | ||
"dependencies": { | ||
"bcrypt": "^5.1.1", | ||
"connect-mongo": "^5.1.0", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Codebase verification Session configuration is missing or incomplete While the required dependencies (
🔗 Analysis chainLGTM! Session management dependencies are properly configured. The addition of Ensure the session configuration in
Let's verify the session configuration: Also applies to: 23-23 Let me gather more information about the session configuration. Let me try a different search pattern to locate the session configuration. 🏁 Scripts executedThe following scripts were executed for the analysis: Script: #!/bin/bash
# Description: Check session configuration in index.js
# Expected: Should find session middleware setup with security options
# Test: Look for session configuration
rg -A 10 "express-session|connect-mongo" "backend/index.js"
Length of output: 349 Script: #!/bin/bash
# Search for session middleware configuration after the imports
rg -A 20 "app\.use\(session\(" backend/index.js
Length of output: 49 Script: #!/bin/bash
# Search for any session-related configuration with more context
rg -U -A 30 "MongoStore.*session" backend/index.js
Length of output: 52 |
||
"cors": "^2.8.5", | ||
"dotenv": "^16.4.5", | ||
"express": "^4.21.0", | ||
"express-session": "^1.18.1", | ||
"jsonwebtoken": "^9.0.2", | ||
"mongoose": "^8.7.0", | ||
"nodemailer": "^6.9.15", | ||
|
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -3,6 +3,7 @@ const { | |||||
loginCustomer, | ||||||
createCustomer, | ||||||
resetPassword, | ||||||
logout, | ||||||
} = require("../controller/customer.controller"); | ||||||
const authenticateCustomer = require("../middlewares/authCustomer"); | ||||||
const passport = require("../config/passport.config"); | ||||||
|
@@ -27,6 +28,9 @@ router.get( | |||||
); | ||||||
|
||||||
router.post("/register", createCustomer); | ||||||
|
||||||
router.post("/logout", logout) | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add authentication middleware to protect the logout route. The logout route should be protected with the Apply this diff to secure the route: -router.post("/logout", logout)
+router.post("/logout", authenticateCustomer, logout) 📝 Committable suggestion
Suggested change
|
||||||
|
||||||
router.get( | ||||||
"/auth/google", | ||||||
passport.authenticate("google", { scope: ["email"] }) | ||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,8 +3,9 @@ const { createFeedback } = require("../controller/feedback.controller"); | |
const router = express.Router(); | ||
const apiInfo = require("../config/api.info"); | ||
const logger = require("../config/logger"); // Import your logger | ||
const sessionMiddleware = require("../middlewares/sessionMiddleware"); | ||
|
||
router.post("/create", createFeedback); | ||
router.post("/create", sessionMiddleware, createFeedback); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Codebase verification Session middleware inconsistency detected across sensitive routes Several routes handling sensitive operations are missing session validation:
Only the following routes implement proper session validation:
🔗 Analysis chainLGTM! Verify consistent session handling across routes. Good security practice to protect feedback submission with session validation. Let's verify consistent session protection across similar routes: 🏁 Scripts executedThe following scripts were executed for the analysis: Script: #!/bin/bash
# Description: Check for consistent session middleware usage across routes
# Expected: All sensitive routes should use sessionMiddleware
# Check routes files for sessionMiddleware usage
echo "Checking routes for sessionMiddleware usage:"
rg -A 1 "router\.(post|put|delete)" backend/routes/
Length of output: 1822 |
||
|
||
router.get("/", (req, res) => { | ||
try { | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,12 @@ | ||
const express = require("express"); | ||
const { createOrder, getOrders, deleteOrder } = require("../controller/order.controller.js"); | ||
const sessionMiddleware = require("../middlewares/sessionMiddleware.js"); | ||
|
||
const router = express.Router(); | ||
|
||
|
||
router.post("/create/:id", createOrder); | ||
router.get("/get/:id", getOrders); | ||
router.delete("/delete/:id", deleteOrder); | ||
router.post("/create/:id", sessionMiddleware, createOrder); | ||
router.get("/get/:id", sessionMiddleware, getOrders); | ||
router.delete("/delete/:id", sessionMiddleware, deleteOrder); | ||
Comment on lines
+8
to
+10
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Codebase verification Additional security measures needed for order operations Based on the code analysis, while there are some security measures in place, important improvements are needed:
Recommended actions:
🔗 Analysis chainConsider additional security measures for order operations. While session validation is good, consider these additional security measures:
Let's check if other routes in the application implement similar security measures: Let's check the implementation of these order operations to verify if they include ownership validation and request validation. Let's check the actual implementation of these order operations by looking for their definitions in the controllers, and also examine any existing validation patterns in the codebase. Let's examine the content of the order controller file to see the actual implementation of these operations. Let's check the session middleware to understand the current authentication implementation. 🏁 Scripts executedThe following scripts were executed for the analysis: Script: #!/bin/bash
# Search for routes using :id parameter to compare security implementations
rg -A 3 "router\.(post|get|delete).*/:id" backend/routes/
Length of output: 411 Script: #!/bin/bash
# Search for the implementation of order operations
ast-grep --pattern 'const createOrder = async (req, res) {
$$$
}'
ast-grep --pattern 'const getOrders = async (req, res) {
$$$
}'
ast-grep --pattern 'const deleteOrder = async (req, res) {
$$$
}'
# Also check if there's any validation middleware
rg -l "validator|validate|check" backend/
Length of output: 403 Script: #!/bin/bash
# Find and show the order controller file
fd "order.*controller" backend/
# Look for order operation implementations with context
rg -A 10 "^(const|async function) (createOrder|getOrders|deleteOrder)" backend/
# Check validation patterns in existing files
rg -A 5 "validate|check" backend/models/
Length of output: 973 Script: #!/bin/bash
# Show the content of the order controller file
cat backend/controller/order.controller.js
# Also check for any middleware files that might contain validation
fd "middleware" backend/
Length of output: 2115 Script: #!/bin/bash
# Show the content of the session middleware
cat backend/middlewares/sessionMiddleware.js
# Check the order model for any validation schemas
cat backend/models/order.model.js
Length of output: 1113 |
||
|
||
module.exports = router; |
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -13,6 +13,7 @@ const Navbar = () => { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const [token, setToken] = useState(Cookies.get('authToken')); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const location = useLocation(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const navigate = useNavigate(); // Correctly initialize useNavigate | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const API_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Consider improving the API URL configuration. While the implementation works, consider these improvements for better maintainability and security:
Example implementation: // config.js
export const getApiUrl = () => {
const url = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000';
try {
new URL(url);
return url;
} catch (e) {
console.error('Invalid VITE_BACKEND_URL:', e);
return 'http://localhost:3000';
}
}; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const menuItems = [ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
{ name: 'HOME', path: '/' }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
@@ -43,9 +44,16 @@ const Navbar = () => { | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
setIsMenuOpen(!isMenuOpen); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
}; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const handleLogout = () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const handleLogout = async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// setisloggedIn(false); // Set isLoggedIn to false on confirmation | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
//managing log in , logout using jwt tokens | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
const response = await fetch(`${API_URL}/api/user/logout`, { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Codebase verification Backend logout endpoint exists but path mismatch detected The frontend is using
This path mismatch needs to be fixed either by:
🔗 Analysis chainVerify backend logout endpoint configuration. Let's ensure the logout endpoint matches the backend route configuration. 🏁 Scripts executedThe following scripts were executed for the analysis: Script: #!/bin/bash
# Search for the logout route definition in backend files
rg -l "router\.(post|all)\(['\"]\/api\/user\/logout" .
Length of output: 192 Script: #!/bin/bash
# Search for logout route definition with proper escaping
rg -l "router\.(post|all)\(.*?['\"]\/api\/user\/logout['\"]" .
# Also search for any file containing logout route pattern
rg -l "\/api\/user\/logout" .
# Search for Express router definitions related to user/logout
ast-grep --pattern 'router.$_("/api/user/logout"'
Length of output: 382 Script: #!/bin/bash
# Search for logout route without escaping
rg -l "router\.(post|get|all)\(.*?'/api/user/logout'" .
# Search for any file containing the logout endpoint
rg -l "/api/user/logout" .
# Search for Express router files
fd "routes?.js|routes?.ts"
Length of output: 197 Script: #!/bin/bash
# Let's check the content of the routes file
cat backend/routes/newsletterRoute.js
# Search for other potential route files in backend
fd . backend --type f -e js -e ts | rg -i "(route|api)"
# Search for auth or user related files
fd . backend --type f | rg -i "(auth|user)"
Length of output: 880 Script: #!/bin/bash
# Check content of auth middleware and OAuth files
cat backend/middlewares/authCustomer.js
cat backend/config/oauth.config.js
cat backend/controller/googleOAuth.controller.js
# Check content of potential user-related routers
cat backend/routes/adminRouter.js
cat backend/routes/customerRouter.js
Length of output: 4974 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
method: 'POST', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
headers: { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
'Content-Type': 'application/json', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
}, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
}) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+47
to
+56
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add error handling and cleanup commented code. The logout implementation needs improvements in error handling and cleanup:
Here's the suggested implementation: const handleLogout = async () => {
- // setisloggedIn(false); // Set isLoggedIn to false on confirmation
- //managing log in , logout using jwt tokens
- const response = await fetch(`${API_URL}/api/user/logout`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- })
-
- Cookies.remove('authToken');
- setToken(null);
- setIsModalOpen(false); // Close the modal
- setIsMenuOpen(false); // after getting logged out close the menu if it is open
- navigate('/login'); //navigate to login after get logged out
+ try {
+ const response = await fetch(`${API_URL}/api/user/logout`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'include', // Important for cookies
+ });
+
+ if (!response.ok) {
+ throw new Error('Logout failed');
+ }
+
+ Cookies.remove('authToken');
+ setToken(null);
+ setIsModalOpen(false);
+ setIsMenuOpen(false);
+ navigate('/login');
+ } catch (error) {
+ console.error('Logout error:', error);
+ // Consider showing an error message to the user
+ }
}; 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Cookies.remove('authToken'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
setToken(null); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
setIsModalOpen(false); // Close the modal | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Configure session expiry to match token expiry.
The JWT token expires in 1 hour, but the session doesn't have an explicit expiry. Consider adding session expiry configuration to maintain consistency with token lifetime.
Add this before setting the session:
+ req.session.cookie.expires = new Date(Date.now() + 60 * 60 * 1000); // 1 hour req.session.user = { id: customer._id, name: customer.name, };
📝 Committable suggestion
💡 Codebase verification
Session middleware integration is properly configured but needs security enhancements
The session middleware is correctly integrated with proper MongoStore configuration for persistence, but there are a few security concerns:
sessionMiddleware.js
lacks proper type checking for user sessionsession: false
)Recommended fixes:
🔗 Analysis chain
Verify session middleware integration.
Let's ensure that the session middleware is properly configured and applied to the routes.
Let me gather more information about the session middleware configuration and implementation.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
Length of output: 1255
Script:
Length of output: 1852