auth.js 534 B

1234567891011121314151617181920
  1. const jwt = require('jsonwebtoken')
  2. const config = require('config')
  3. module.exports = (req, res, next) => {
  4. if (req.method === 'OPTIONS') {
  5. return next()
  6. }
  7. try {
  8. const token = req.headers.authorization.split(' ')[1]
  9. if (!token) {
  10. return res.status(401).json({message: 'Auth error'})
  11. }
  12. const decoded = jwt.verify(token, config.get('jwtKey'))
  13. req.user = decoded
  14. next()
  15. } catch (e) {
  16. return res.status(401).json({message: 'Auth error'})
  17. }
  18. }