Files
whats-the-point/backend/src/middleware/auth.js

54 lines
1.4 KiB
JavaScript

import jwt from 'jsonwebtoken';
import { query } from '../db/index.js';
import { asyncHandler } from './errorHandler.js';
export const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.substring(7);
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; // { userId, email, username }
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
// Enhanced version that fetches user data including admin status
export const verifyToken = asyncHandler(async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.substring(7);
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Fetch full user data including admin status
const users = await query(
'SELECT id, email, username, is_admin FROM users WHERE id = ?',
[decoded.userId]
);
if (users.length === 0) {
return res.status(401).json({ error: 'User not found' });
}
req.user = {
userId: users[0].id,
email: users[0].email,
username: users[0].username,
is_admin: users[0].is_admin
};
next();
});