66 lines
1.2 KiB
JavaScript
Executable file
66 lines
1.2 KiB
JavaScript
Executable file
'use strict';
|
|
|
|
/**
|
|
* Module dependencies.
|
|
*/
|
|
var _ = require('lodash'),
|
|
mongoose = require('mongoose'),
|
|
User = mongoose.model('User');
|
|
|
|
/**
|
|
* User middleware
|
|
*/
|
|
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) {
|
|
return next(new Error('Failed to load User ' + id));
|
|
}
|
|
|
|
req.profile = user;
|
|
next();
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Require login routing middleware
|
|
*/
|
|
exports.requiresLogin = function(req, res, next) {
|
|
if (!req.isAuthenticated()) {
|
|
console.log('\n\nSENDING 401 STATUS\n\n');
|
|
return res.status(401).send({
|
|
message: 'User is not logged in'
|
|
});
|
|
} else {
|
|
return next();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* User authorizations routing middleware
|
|
*/
|
|
exports.hasAuthorization = function(roles) {
|
|
var _this = this;
|
|
|
|
return function(req, res, next) {
|
|
_this.requiresLogin(req, res, function() {
|
|
if (_.intersection(req.user.roles, roles).length) {
|
|
return next();
|
|
} else {
|
|
return res.status(403).send({
|
|
message: 'User is not authorized'
|
|
});
|
|
}
|
|
});
|
|
};
|
|
};
|