39 lines
1.3 KiB
JavaScript
39 lines
1.3 KiB
JavaScript
/* eslint-disable no-undef */
|
|
import jwt from 'jsonwebtoken';
|
|
import { respondWithStatus } from './requestHandler.js';
|
|
import { pool } from './database.js';
|
|
|
|
// Generate a new JWT
|
|
const generateToken = async (userId, password) => {
|
|
return await jwt.sign({ userId: userId, password: password }, process.env.JWT_SECRET, { expiresIn: '7d' });
|
|
};
|
|
|
|
// Middleware to verify the JWT and set req.userId
|
|
const verifyToken = async (req, res, next) => {
|
|
const token = req.headers.authorization;
|
|
if (!token) return await respondWithStatus(res, 401, 'No token provided');
|
|
|
|
try {
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
req.userId = decoded.userId;
|
|
|
|
const [rows] = await pool.execute(
|
|
'SELECT * FROM users WHERE id = ? LIMIT 1', [req.userId],
|
|
);
|
|
if (!rows.length) return await respondWithStatus(res, 404, 'User not found!');
|
|
const passwordMatch = await Bun.password.verify(decoded.password, rows[0].password);
|
|
if (!passwordMatch) return await respondWithStatus(res, 401, 'Token is invalid');
|
|
|
|
const now = Date.now().valueOf() / 1000;
|
|
if (decoded.exp - now <= 0) {
|
|
return await respondWithStatus(res, 401, 'Token is invalid');
|
|
}
|
|
req.username = rows[0].username;
|
|
next();
|
|
}
|
|
catch (error) {
|
|
return await respondWithStatus(res, 401, 'Invalid user');
|
|
}
|
|
};
|
|
|
|
export { generateToken, verifyToken }; |