2015-06-29 22:51:29 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies.
|
|
|
|
*/
|
|
|
|
var _ = require('lodash'),
|
|
|
|
mongoose = require('mongoose'),
|
2017-10-30 00:46:08 +00:00
|
|
|
User = mongoose.model('User'),
|
2017-10-30 01:17:20 +00:00
|
|
|
auth = require('../../../config/passport_helpers');
|
2015-06-29 22:51:29 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* User middleware
|
|
|
|
*/
|
2015-10-30 18:40:02 +00:00
|
|
|
exports.userByID = function (req, res, next, id) {
|
|
|
|
if (!mongoose.Types.ObjectId.isValid(id)) {
|
|
|
|
return res.status(400).send({
|
|
|
|
message: 'User is invalid'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
User.findOne({
|
|
|
|
_id: id
|
|
|
|
}).exec(function (err, user) {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
} else if (!user) {
|
2016-08-26 22:09:16 +00:00
|
|
|
return res.status(404).send({
|
|
|
|
message: 'User does not exist'
|
|
|
|
});
|
2015-10-30 18:40:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
req.profile = user;
|
|
|
|
next();
|
|
|
|
});
|
2015-06-29 22:51:29 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Require login routing middleware
|
|
|
|
*/
|
|
|
|
exports.requiresLogin = function(req, res, next) {
|
|
|
|
if (!req.isAuthenticated()) {
|
|
|
|
return res.status(401).send({
|
|
|
|
message: 'User is not logged in'
|
|
|
|
});
|
2016-03-30 03:45:16 +00:00
|
|
|
} else {
|
2015-11-06 01:22:16 +00:00
|
|
|
return next();
|
2015-06-29 22:51:29 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* User authorizations routing middleware
|
|
|
|
*/
|
|
|
|
exports.hasAuthorization = function(roles) {
|
|
|
|
var _this = this;
|
|
|
|
|
|
|
|
return function(req, res, next) {
|
2017-10-30 00:46:08 +00:00
|
|
|
auth.isAuthenticatedOrApiKey(req, res, function() {
|
2015-06-29 22:51:29 +00:00
|
|
|
if (_.intersection(req.user.roles, roles).length) {
|
|
|
|
return next();
|
|
|
|
} else {
|
|
|
|
return res.status(403).send({
|
|
|
|
message: 'User is not authorized'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
};
|