Skip to content
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

Handling expired token #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions api/src/models/Blacklist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');

const blacklistSchema = new mongoose.Schema({
user_id: { type: String },
blacklistToken: { type: String },
time: { type: Date, default: Date.now },
});

module.exports = mongoose.model('Blacklist', blacklistSchema);
35 changes: 33 additions & 2 deletions api/src/routes/auth/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const express = require('express');
const User = require('../../models/User');
const Blacklist = require('../../models/Blacklist');
const jwt = require('jsonwebtoken');

const router = express.Router();
Expand Down Expand Up @@ -107,8 +108,38 @@ router.get('/callback', async (req, res) => {
.redirect(DASHBOARD_URL);
});

router.get('/signout', (req, res) => {
res.clearCookie('token').sendStatus(200);
router.get('/signout', async (req, res) => {
const token = req.cookies.token;

// Clear cookie regardless of token presence
if (!token) {
res.clearCookie('token', { httpOnly: true, secure: true });
return res.status(200).json({ message: 'Successfully logged out. No active session found.' });
}

try {
// Verify the token
const savedToken = await Blacklist.findOne({ blacklistToken: token });
if (savedToken) {
res.clearCookie('token', { httpOnly: true, secure: true });
return res.status(200).json({ message: 'Successfully logged out. Active session found and already blocked.' });
}
const decodedToken = jwt.verify(token, process.env.JWT_SECRET);

// Add token to blacklist
await Blacklist.create({ blacklistToken: token, user_id: decodedToken.id });

res.clearCookie('token', { httpOnly: true, secure: true });
return res.status(200).json({ message: 'Successfully logged out.' });
} catch (err) {
// Handle invalid token or verification errors
if (err) {
res.clearCookie('token', { httpOnly: true, secure: true });
return res.status(200).json({ message: 'Successfully logged out. Invalid or expired session token.' });
}

return res.status(500).json({ message: 'Error during logout. Please try again later.' });
}
});

module.exports = router;