var jwt = require('jsonwebtoken');

var protect = function(req, res, next) {
  var header = req.headers.authorization || '';
  var token = header.startsWith('Bearer ') ? header.split(' ')[1] : '';

  if (!token) {
    return res.status(401).json({ message: 'Please login first' });
  }

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (error) {
    res.status(401).json({ message: 'Invalid or expired login' });
  }
};

module.exports = protect;
