Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
830 B
2
Indexable
Never
const jsonToken = require('jsonwebtoken');

const authToken = (auth) => {
  if (!auth) return null;

  const tokenA = auth.split(' ');
  if (tokenA.length === 2 && /Bearer$/i.test(tokenA[0])) return tokenA[1];
  return auth;
};
const verifyToken = (validToken) => {
  const secret = process.env.JWT_SECRET || 'raisfonogreis';
  try {
    jsonToken.verify(validToken, secret);
    return jsonToken.decode(validToken);
  } catch (error) {
    return null;
  }
};
const authMiddleware = (req, res, next) => {
  const tokenB = authToken(req.headers.authorization);
  if (!tokenB) return res.status(401).json({ message: 'Token not found' });

  const userA = verifyToken(tokenB);
  if (!userA) return res.status(401).json({ message: 'Expired or invalid token' });

  req.user = userA;
  next();
};

module.exports = { authMiddleware };
Leave a Comment