2017-06-23 17:54:28 +00:00
|
|
|
'use strict';
|
2016-08-26 00:54:16 +00:00
|
|
|
|
2017-06-23 17:54:28 +00:00
|
|
|
var passport = require('passport');
|
2016-08-26 00:54:16 +00:00
|
|
|
|
|
|
|
module.exports.isAuthenticatedOrApiKey = function isAuthenticated(req, res, next) {
|
|
|
|
if (req.isAuthenticated()) {
|
|
|
|
return next();
|
2017-04-23 19:46:15 +00:00
|
|
|
}
|
2017-10-30 02:02:01 +00:00
|
|
|
|
2017-04-21 05:02:05 +00:00
|
|
|
// Try authenticate with API KEY
|
|
|
|
if (req.headers.apikey || req.query.apikey || req.body.apikey) {
|
2017-10-30 04:32:02 +00:00
|
|
|
if(!req.body.apikey && req.headers.apikey){
|
|
|
|
req.body.apikey = req.headers.apikey;
|
|
|
|
} else if(!req.query.apikey && req.headers.apikey){
|
|
|
|
req.query.apikey = req.headers.apikey;
|
|
|
|
}
|
|
|
|
|
2017-06-23 17:54:28 +00:00
|
|
|
passport.authenticate('localapikey', function (err, user, info) {
|
2017-10-30 04:32:02 +00:00
|
|
|
if (err) {
|
|
|
|
return res.status(500).send('Internal Server Error with API. Sorry about that!');
|
|
|
|
}
|
2017-04-21 05:02:05 +00:00
|
|
|
|
2017-10-30 04:32:02 +00:00
|
|
|
if (!user) {
|
|
|
|
console.log('no user for apikey');
|
2017-06-23 17:54:28 +00:00
|
|
|
return res.status(401).send(info.message || '');
|
2017-10-30 04:32:02 +00:00
|
|
|
}
|
2017-04-21 05:02:05 +00:00
|
|
|
|
|
|
|
req.login(user, function(loginErr) {
|
|
|
|
if (loginErr) return res.sendStatus(500);
|
|
|
|
|
|
|
|
req.user = user;
|
|
|
|
return next();
|
|
|
|
});
|
|
|
|
|
|
|
|
})(req, res, next);
|
2017-04-23 19:46:15 +00:00
|
|
|
} else {
|
|
|
|
return res.sendStatus(401);
|
|
|
|
}
|
2016-08-26 00:54:16 +00:00
|
|
|
};
|
|
|
|
|