Skip to content

Commit 96bf90a

Browse files
committed
refactor: Update logout functionality to include API call and error handling; adjust route method to POST
1 parent a71f148 commit 96bf90a

File tree

9 files changed

+58
-25
lines changed

9 files changed

+58
-25
lines changed

client-test/src/components/Admin/Dashboard.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ export default function Dashboard() {
112112
// Calculate weekly user registration data from actual database
113113
useEffect(() => {
114114
if (users.length > 0) {
115-
console.log("Processing weekly user data...", users);
115+
// console.log("Processing weekly user data...", users);
116116

117117
// Get the last 7 days
118118
const today = new Date();
@@ -142,7 +142,7 @@ export default function Dashboard() {
142142
});
143143
}
144144

145-
console.log("Weekly user data calculated:", weeklyData);
145+
// console.log("Weekly user data calculated:", weeklyData);
146146
setUserWeeklyData(weeklyData);
147147
}
148148
}, [users]);
@@ -152,7 +152,7 @@ export default function Dashboard() {
152152
if (users.length > 0) {
153153
// Create college distribution data
154154
const collegeDistribution: Record<string, number> = {};
155-
console.log(users, "users data in dashboard")
155+
// console.log(users, "users data in dashboard")
156156

157157
users.forEach(user => {
158158
if (user.collegeName) {

client-test/src/components/ErrorBoundary.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import React, { Component, ErrorInfo, ReactNode } from 'react';
22
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
33
import { Button } from '@/components/ui/button';
44
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
5+
import { navigateTo } from '../lib/axios';
56

67
interface Props {
78
children: ReactNode;
@@ -58,7 +59,7 @@ export class ErrorBoundary extends Component<Props, State> {
5859
};
5960

6061
handleGoHome = () => {
61-
window.location.href = '/';
62+
navigateTo('/');
6263
};
6364

6465
render() {

client-test/src/context/AdminContext.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,15 @@ export const useAdminStore = create<AdminState>((set, get) => {
209209
set({ token, isAdminAuthenticated: true });
210210
},
211211

212-
// Logout function to remove token from local storage
213-
logout: () => {
212+
logout: async () => {
213+
try {
214+
await axios.post(`${import.meta.env.VITE_API_BASE_URL}/auth/admin/logout`, {}, {
215+
withCredentials: true,
216+
});
217+
} catch (error) {
218+
console.error('Admin logout API call failed:', error);
219+
}
220+
214221
localStorage.removeItem("Admintoken");
215222
set({ token: null, isAdminAuthenticated: false, users: [], pagination: null, filterOptions: null });
216223
},

client-test/src/context/AuthContext.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
/* eslint-disable @typescript-eslint/no-unused-vars */
33
import React, { createContext, useState, useEffect, ReactNode } from "react";
44
import axios from "axios";
5+
import { navigateTo } from "../lib/axios";
56
// Define the user type
67
interface User {
78
_id: string;
@@ -85,11 +86,15 @@ const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
8586
setUser(null);
8687
setIsAuthenticated(false);
8788
setToken(null);
88-
// localStorage.removeItem('auth_token');
8989

90-
window.location.href = "/";
90+
navigateTo("/");
9191
} catch (error) {
9292
console.error("Logout failed:", error);
93+
// Even if API call fails, clear local state and redirect
94+
setUser(null);
95+
setIsAuthenticated(false);
96+
setToken(null);
97+
navigateTo("/");
9398
}
9499
};
95100

client-test/src/lib/axios.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ const navigateTo = (path: string) => {
1818
}
1919
};
2020

21+
export { navigateTo };
22+
2123
// API Error Response interface
2224
interface ApiErrorResponse {
2325
message: string;

server/controllers/adminAuthController.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,11 @@ export const adminLogout = async (req, res) => {
9696
ip: req.ip
9797
});
9898

99-
res.cookie('Admintoken', "").json({ message: "Logged out" });
99+
res.clearCookie('Admintoken', {
100+
httpOnly: true,
101+
secure: process.env.NODE_ENV === "production",
102+
sameSite: process.env.NODE_ENV === "production" ? "Strict" : "Lax",
103+
}).status(200).json({ message: "Logged out successfully" });
100104
} catch (err) {
101105
auditService.error('Admin logout error', err, {
102106
requestId: req.auditContext?.requestId,

server/controllers/authController.js

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -417,23 +417,37 @@ export const githubAuthCallback = (req, res) => {
417417

418418

419419
export const logoutUser = async (req, res) => {
420-
// console.log("Logout API hit"); // Debugging log
420+
try {
421+
auditService.userAction('user_logout', {
422+
requestId: req.auditContext?.requestId,
423+
userId: req.user?._id?.toString(),
424+
email: req.user?.email,
425+
ip: req.ip
426+
});
421427

422-
// Clear JWT cookie
423-
res.clearCookie("jwt", {
424-
httpOnly: true,
425-
secure: process.env.NODE_ENV === "production",
426-
sameSite: process.env.NODE_ENV === "production" ? "None" : "Lax",
427-
});
428+
// Clear JWT cookie
429+
res.clearCookie("jwt", {
430+
httpOnly: true,
431+
secure: process.env.NODE_ENV === "production",
432+
sameSite: process.env.NODE_ENV === "production" ? "Strict" : "Lax",
433+
});
428434

429-
// Clear user cookie
430-
res.clearCookie("user", {
431-
httpOnly: true,
432-
secure: process.env.NODE_ENV === "production",
433-
sameSite: process.env.NODE_ENV === "production" ? "None" : "Lax",
434-
});
435+
// Clear user cookie
436+
res.clearCookie("user", {
437+
httpOnly: true,
438+
secure: process.env.NODE_ENV === "production",
439+
sameSite: process.env.NODE_ENV === "production" ? "Strict" : "Lax",
440+
});
435441

436-
res.status(200).json({ message: "Logged out successfully" });
442+
res.status(200).json({ message: "Logged out successfully" });
443+
} catch (error) {
444+
auditService.error('User logout error', error, {
445+
requestId: req.auditContext?.requestId,
446+
userId: req.user?._id?.toString(),
447+
ip: req.ip
448+
});
449+
res.status(500).json({ error: "Server error during logout" });
450+
}
437451
};
438452

439453

server/routes/adminAuthRoutes.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ router.get('/',(req,res)=>{
88
res.send("Admin Route");
99
});
1010
router.post('/login', adminLogin);
11-
router.get('/logout', protectAdmin, adminLogout);
11+
router.post('/logout', protectAdmin, adminLogout);
1212

1313
export default router;

server/routes/authRoutes.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ router.get("/github", passport.authenticate("github", { scope: ["user:email"], s
1616
router.get("/google/callback", handleGoogleCallback, googleAuthCallback);
1717
router.get("/github/callback", handleGithubCallback, githubAuthCallback);
1818

19-
router.post("/logout", logoutUser);
19+
router.post("/logout", protect, logoutUser);
2020
router.post("/forgot-password", forgotPassword);
2121
router.post("/reset-password/:token", resetPassword);
2222
router.get("/me", protect, getCurrentUser);

0 commit comments

Comments
 (0)