2017-05-10 11:04:06 +02:00
|
|
|
"use strict"
|
|
|
|
|
|
|
|
const jwt = require('jsonwebtoken');
|
2017-05-11 18:36:32 +02:00
|
|
|
const config = require('../config/config');
|
2017-05-10 11:04:06 +02:00
|
|
|
|
|
|
|
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) {
|
|
|
|
|
|
|
|
// verifies secret and checks exp
|
|
|
|
jwt.verify(token, config.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;
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
// if there is no token
|
|
|
|
// return an error
|
|
|
|
return res.status(403).send({
|
|
|
|
success: false,
|
|
|
|
message: 'No token provided.'
|
|
|
|
});
|
|
|
|
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = apiAuthentication;
|