Skip to content

Commit

Permalink
Merge pull request #211 from sayinmehmet47/cookie-based-auth
Browse files Browse the repository at this point in the history
Refactor logoutController in user.controller.ts
  • Loading branch information
sayinmehmet47 authored Apr 1, 2024
2 parents 0e042d0 + accf8e5 commit d4e2078
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions backend/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,26 @@ export const authController = async (req: Request, res: Response) => {

export const logoutController = async (req: Request, res: Response) => {
try {
await logoutUser(req.body.user._id);
const userId = req.body.user?._id;
if (!userId) {
return res.status(400).json({ message: 'User ID is required' });
}

await logoutUser(userId);

res.clearCookie('accessToken', { path: '/' });
res.clearCookie('refreshToken', { path: '/' });

res.cookie('accessToken', '', { expires: new Date(0) });
res.cookie('refreshToken', '', { expires: new Date(0) });
res.status(200).json({ message: 'Logged out successfully' });
} catch (err) {
if (err instanceof CustomError) {
return res
.status(err.statusCode)
.json({ message: err.serializeErrors() });
}

// Handle any other errors
return res.status(500).json({ message: 'An error occurred during logout' });
}
};

Expand Down

0 comments on commit d4e2078

Please sign in to comment.