Skip to content

Commit

Permalink
fix(auth): update JWT handling to use user ID as subject and remove i…
Browse files Browse the repository at this point in the history
…d from token payload
  • Loading branch information
chimpdev committed Dec 18, 2024
1 parent 840f00e commit b3704f1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
3 changes: 1 addition & 2 deletions server/src/routes/auth/callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,14 @@ module.exports = {

const token = jwt.sign(
{
id: user.id,
iat: currentDate.getTime()
},
process.env.JWT_SECRET,
{
expiresIn: '30d',
issuer: 'api.discord.place',
audience: 'discord.place',
subject: 'user'
subject: user.id
}
);

Expand Down
16 changes: 9 additions & 7 deletions server/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,21 +95,23 @@ module.exports = class Server {
const token = request.cookies.token;

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
const decoded = jwt.decode(token, { complete: true });
if (!decoded || !decoded.payload?.sub) throw new Error('Token invalid.');

const verified = jwt.verify(token, process.env.JWT_SECRET, {
issuer: 'api.discord.place',
audience: 'discord.place',
subject: 'user'
subject: decoded.payload.sub,
complete: true
});

if (!decoded) throw new Error('Token invalid.');

const user = await User.findOne({ id: decoded.id }).select('lastLogoutAt').lean();
const user = await User.findOne({ id: verified.payload.sub }).select('lastLogoutAt').lean();
if (!user) throw new Error('User not found.');

if (decoded.iat < new Date(user.lastLogoutAt).getTime()) throw new Error('Token expired.');
if (verified.iat < new Date(user.lastLogoutAt).getTime()) throw new Error('Token expired.');

request.user = {
id: decoded.id
id: verified.payload.sub
};

const guild = client.guilds.cache.get(config.guildId);
Expand Down

0 comments on commit b3704f1

Please sign in to comment.