| const jwt = require('jsonwebtoken');
|
| const User = require('../models/User');
|
|
|
| const auth = async (req, res, next) => {
|
| try {
|
| let token;
|
|
|
|
|
| if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
| token = req.headers.authorization.split(' ')[1];
|
| }
|
|
|
| else if (req.cookies?.token) {
|
| token = req.cookies.token;
|
| }
|
|
|
| if (!token) {
|
| return res.status(401).json({ error: 'No token provided, authorization denied' });
|
| }
|
|
|
|
|
| const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
|
|
|
| const user = await User.findById(decoded.userId).select('-password');
|
| if (!user) {
|
| return res.status(401).json({ error: 'User no longer exists' });
|
| }
|
|
|
| req.user = decoded;
|
| next();
|
| } catch (error) {
|
| console.error('Auth middleware error:', error);
|
| res.status(401).json({ error: 'Token is not valid' });
|
| }
|
| };
|
|
|
| module.exports = auth; |