opt-cc/api/middleware/auth-middleware.js

45 lines
1.3 KiB
JavaScript

'use strict';
const jwt = require('jsonwebtoken');
const config = require('../config/config');
const AppUser = require('../models/app-user');
const apiAuthentication = (req, res, next) => {
// check header or url parameters or post parameters for token
const token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
const secret = process.env.NODE_ENV === config.prod.env ? process.env.JWS_SECRET : 'dev-secret';
// verifies secret and checks exp
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(403).json({success: false, message: 'Failed to authenticate token.'});
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
AppUser.findById(decoded.sub, (err, item) => {
if (err) {
return res.status(403).send({
success: false,
message: 'token is not associated to any actual user',
});
}
req.user = item;
next();
});
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.',
});
}
};
module.exports = apiAuthentication;