2018-03-12 09:26:44 +01:00
|
|
|
'use strict';
|
2017-05-10 11:04:06 +02:00
|
|
|
|
|
|
|
const jwt = require('jsonwebtoken');
|
2017-05-11 18:36:32 +02:00
|
|
|
const config = require('../config/config');
|
2017-06-08 13:14:53 +02:00
|
|
|
const AppUser = require('../models/app-user');
|
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) {
|
2018-02-04 16:36:42 +01:00
|
|
|
const secret = process.env.NODE_ENV === config.prod.env ? process.env.JWS_SECRET : 'dev-secret';
|
|
|
|
|
2017-05-10 11:04:06 +02:00
|
|
|
// verifies secret and checks exp
|
2018-02-04 16:36:42 +01:00
|
|
|
jwt.verify(token, secret, (err, decoded) => {
|
2017-05-10 11:04:06 +02:00
|
|
|
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;
|
2017-06-08 13:14:53 +02:00
|
|
|
AppUser.findById(decoded.sub, (err, item) => {
|
|
|
|
if (err) {
|
|
|
|
return res.status(403).send({
|
|
|
|
success: false,
|
2018-03-12 09:26:44 +01:00
|
|
|
message: 'token is not associated to any actual user',
|
2017-06-08 13:14:53 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
req.user = item;
|
|
|
|
next();
|
|
|
|
});
|
2017-05-10 11:04:06 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// if there is no token
|
|
|
|
// return an error
|
|
|
|
return res.status(403).send({
|
|
|
|
success: false,
|
2018-03-12 09:26:44 +01:00
|
|
|
message: 'No token provided.',
|
2017-05-10 11:04:06 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = apiAuthentication;
|