Added liking and security measures

This commit is contained in:
Sven laptop
2026-07-31 15:11:57 +02:00
parent 494b583cbc
commit ab73eecfec
25 changed files with 1095 additions and 91 deletions
+33 -2
View File
@@ -1,4 +1,5 @@
const crypto = require('crypto');
const pool = require('../db');
const DEFAULT_TOKEN_LIFETIME_SECONDS = 60 * 60;
@@ -14,7 +15,7 @@ function getJwtSecret() {
return secret;
}
function signToken(userId) {
function signToken(userId, { jti, tokenVersion } = {}) {
const now = Math.floor(Date.now() / 1000);
const configuredLifetime = Number.parseInt(process.env.JWT_EXPIRES_IN, 10);
const lifetime = Number.isInteger(configuredLifetime) && configuredLifetime > 0
@@ -25,6 +26,8 @@ function signToken(userId) {
iat: now,
exp: now + lifetime,
};
if (jti) payload.jti = jti;
if (tokenVersion !== undefined) payload.tvr = tokenVersion;
const encodedHeader = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
const encodedPayload = base64url(JSON.stringify(payload));
const content = `${encodedHeader}.${encodedPayload}`;
@@ -57,7 +60,7 @@ function getTokenFromRequest(req) {
return null;
}
function authenticateToken(req, res, next) {
async function authenticateToken(req, res, next) {
const token = getTokenFromRequest(req);
if (!token) {
@@ -92,6 +95,34 @@ function authenticateToken(req, res, next) {
}
req.user = { id: payload.user_id };
if (payload.jti || payload.tvr !== undefined) {
const { rows } = await pool.query(
'SELECT token_version FROM people WHERE id = $1',
[payload.user_id],
);
if (rows.length === 0 || rows[0].token_version !== payload.tvr) {
return res.status(401).send('Session has been invalidated');
}
if (payload.jti) {
const sessionCheck = await pool.query(
'SELECT 1 FROM sessions WHERE id = $1 AND user_id = $2',
[payload.jti, payload.user_id],
);
if (sessionCheck.rowCount === 0) {
return res.status(401).send('Session has been revoked');
}
}
req.user.session_id = payload.jti || null;
}
if (payload.jti) {
pool.query('UPDATE sessions SET last_used_at = NOW() WHERE id = $1', [payload.jti])
.catch(() => {});
}
next();
} catch (err) {
if (err.message.startsWith('JWT_SECRET')) {