Skip to content

Commit

Permalink
users progress
Browse files Browse the repository at this point in the history
  • Loading branch information
tjmehta committed Jan 27, 2014
1 parent d59ee5a commit f9c2c80
Show file tree
Hide file tree
Showing 37 changed files with 416 additions and 288 deletions.
2 changes: 1 addition & 1 deletion configs/testing.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"harbourmaster": "http://localhost:3033",
"runnable_access_timeout": "5 seconds",
"logExpress": false,
"logErrorStack": true,
"logErrorStack": false,
"throwErrors": true,
"adminToken": "e6f5a32a-4be0-4d84-91cb-782c65ae320f",
"cleanInterval": "2 minutes",
Expand Down
1 change: 1 addition & 0 deletions lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ app.all('*', function (req, res) {
});
app.use(function mongooseErrorHandler (err, req, res, next) {
if (err.name === 'MongoError') {
console.log('MONGO ERORR', err);
if (err.code === 11000) {
var message = /\$([^_]+)_/.exec(err.err)[1] + ' already exists';
err = error(409, message);
Expand Down
6 changes: 5 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ App.prototype.create = function () {
message: err.msg,
stack: configs.throwErrors ? err.stack : undefined
});
} else {
}
else {
res.json(500, {
message: 'something bad happened :(',
stack: configs.throwErrors ? err.stack : undefined
Expand All @@ -85,6 +86,9 @@ App.prototype.create = function () {
self.cleanup();
});
}
if (configs.logErrorStack) {
console.error(err);
}
}
};
App.prototype.cleanup = function () {
Expand Down
2 changes: 1 addition & 1 deletion lib/middleware/containers.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var containers = module.exports = createModelMiddleware(Container, {
owner: 'user_id'
}, {
$set: {
owner: 'user._id'
owner: 'me._id'
}
})(req, res, next);
}
Expand Down
26 changes: 21 additions & 5 deletions lib/middleware/createModelMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function getModelMiddlewareClass() {
req.domain.run(function () {
Model[method].apply(Model, localArgs);
});
req.lastQuery = localArgs[0];
req[self.key+'LastQuery'] = localArgs[0];
};
};
});
Expand Down Expand Up @@ -70,13 +70,13 @@ function getModelMiddlewareClass() {
req.domain.run(function () {
model[method].apply(model, localArgs);
});
req.lastQuery = localArgs[0];
req[self.key+'LastQuery'] = localArgs[0];
};
};
self.model.if = function (key /*, middlewares*/) {
var middlewares = Array.prototype.slice.call(arguments, 1);
return function (req, res, next) {
if (req[key]) {
if (req[self.key][key]) {
return series.apply(utils, middlewares)(req, res, next);
}
next();
Expand All @@ -85,7 +85,7 @@ function getModelMiddlewareClass() {
self.model.unless = function (key /*, middlewares*/) {
var middlewares = Array.prototype.slice.call(arguments, 1);
return function (req, res, next) {
if (!req[key]) {
if (!req[self.key][key]) {
return series.apply(utils, middlewares)(req, res, next);
}
next();
Expand Down Expand Up @@ -118,6 +118,10 @@ function getModelMiddlewareClass() {
findConflict: function (query) {
return series(
self.findOne(query, { _id:1 }),
function (req, res, next) {
console.log(req.user);
next();
},
self.checkConflict
);
},
Expand Down Expand Up @@ -165,9 +169,21 @@ function getModelMiddlewareClass() {
if (paramId && utils.equalObjectIds(paramId, conflictId)) {
return next(); // ignore the conflict if it is itself
}
var keys = Object.keys(req.lastQuery).join(',');
var keys = getLastQueryKeys();
// TODO fix this message for $or queries
var message = [self.key, 'with', keys, 'already exists'].join(' ');
utils.conflict(self.key, message)(req, res, next);
function getLastQueryKeys() {
var lastQuery = req[self.key+'LastQuery'] || {};
var keys;
if (utils.isObjectId(lastQuery)) {
keys = ['_id'];
}
else {
keys = Object.keys(lastQuery || {}).join(',');
}
return keys;
}
}
};
}
Expand Down
97 changes: 85 additions & 12 deletions lib/middleware/me.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
var bcrypt = require('bcrypt');
var configs = require('configs');
var User = require('models/users');
var users = require('middleware/users');
var containers = require('./containers');
var body = require('./body');
var createModelMiddleware = require('./createModelMiddleware');
var error = require('error');
var utils = require('./utils');
var series = utils.series;
var reqUnless = utils.reqUnless;
Expand All @@ -15,37 +21,37 @@ var me = module.exports = createModelMiddleware(User, {
)(req, res, next);
},
isUser: function (req, res, next) {
if (req.user_id !== req.params.userId) {
return next(error(403, 'access denied'));
if (!utils.equalObjectIds(req.user_id, req.params.userId)) {
return next(error(403, 'access denied (!user)'));
}
next();
},
isOwnerOf: function (key) {
return function (req, res, next) {
var model = req[key];
if (!model || !utils.equalObjectIds(model.owner, req.user_id)){
return next(error(403, 'access denied'));
return next(error(403, 'access denied (!owner)'));
}
};
},
isRegistered: function (req, res, next) {
this.permission('registered')(req, res, next);
},
isVerified: function (req, res, next) {
this.is('verified')(req, res, next);
this.permission('isVerified')(req, res, next);
},
isModerator: function (req, res, next) {
this.is('moderator')(req, res, next);
this.permission('isModerator')(req, res, next);
},
is: function (role) {
var capital = utils.capitalize(role);
permission: function (attr) {
return series(
utils.log('hello'),
reqUnless('me',
this.findMe),
utils.log('foundme?', 'me'),
this.model.unless('is'+capital,
utils.message(403, 'access denied')));
this.model.unless(attr,
utils.error(403, 'access denied (!'+attr+')'))
);
},
respond: function (req, res, next) {
console.log('RESPOND');
series(
addAccessToken,
this.super.respond
Expand All @@ -59,5 +65,72 @@ var me = module.exports = createModelMiddleware(User, {
}
next();
}
},
register: function (req, res, next) {
series(
body.require('email', 'username', 'password'),
this.findConflictEmailOrUsername,
body.pick('email', 'username', 'password'),
registeredFields,
this.findMe,
this.model.set('body'),
utils.log('MEMEME', 'me'),
this.model.save()
)(req, res, next);
function registeredFields (req, res, next) {
bcrypt.hash(req.body.password + configs.passwordSalt, 10,
req.domain.intercept(function (hashedPassword) {
req.body.password = hashedPassword;
req.body.permission_level = 1;
next();
}));
}
},
findConflictEmailOrUsername: function (req, res, next) {
var query = { // used users here so not override the session user
$or: [
{ email: req.body.email },
{ lower_username: req.body.username.toLowerCase() }
]
};
User.findOne(query, { _id:1, email:1, lower_username:1 }, req.domain.intercept(function (user) {
if (user) {
if (utils.equalObjectIds(user._id, req.user_id)) {
next(400, 'already registered');
}
else {
var field = (user.email === req.body.email) ? 'email' : 'username';
next(error(409, 'user with '+field+' already exists'));
}
}
else {
next();
}
}));
},
login: function (loginData) {
return series(
body.requireOne('username', 'email'),
body.require('password'),
body.pick('username', 'email', 'password'),
this.find({
$or: [
{ email: 'body.email' },
{ username: 'body.username' }
]
}),
this.checkFound,
this.checkUserPassword('me', 'body.password'),
containers.authChangeUpdateOwners);
},
checkUserPassword: function (user, password) {
return function (req, res, next) {
user.checkPassword(password, req.domain.intercept(function (matches) {
if (!matches) {
return next(error(403, 'invalid password'));
}
next();
}));
};
}
}, 'me');
42 changes: 2 additions & 40 deletions lib/middleware/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,9 @@ var bcrypt = require('bcrypt');
var error = require('error');
var containers = require('middleware/containers');
var utils = require('middleware/utils');
var body = require('middleware/body');
var series = utils.series;
var ternary = utils.ternary;
var createModelMiddleware = require('./createModelMiddleware');

var users = module.exports = createModelMiddleware(User, {
register: function (req, res, next) {
series(
body.requireOne('email', 'username'),
body.require('password'),
this.findConflict({
$or: [
{ email: 'body.email' },
{ username: 'body.username' }
]
}),
this.create,
this.model.set('body'),
this.model.save(),
containers.authChangeUpdateOwners
)(req, res, next);
},
login: function (loginData) {
return series(
users.find({
$or: [
{ email: 'body.email' },
{ username: 'body.username' }
]
}),
users.checkFound,
users.checkUserPassword('user', 'body.password'),
containers.authChangeUpdateOwners);
},
checkUserPassword: function (user, password) {
return function (req, res, next) {
user.checkPassword(password, req.domain.intercept(function (matches) {
if (!matches) {
return next(error(403, 'invalid password'));
}
next();
}));
};
}
});
var users = module.exports = createModelMiddleware(User);
Loading

0 comments on commit f9c2c80

Please sign in to comment.