2014-02-19 17:57:26 +04:00
|
|
|
var _ = require('lodash'),
|
2014-08-17 10:17:23 +04:00
|
|
|
Promise = require('bluebird'),
|
2014-05-09 14:11:29 +04:00
|
|
|
errors = require('../errors'),
|
2014-12-01 18:59:49 +03:00
|
|
|
utils = require('../utils'),
|
2016-02-12 23:04:26 +03:00
|
|
|
gravatar = require('../utils/gravatar'),
|
2013-10-23 17:00:28 +04:00
|
|
|
bcrypt = require('bcryptjs'),
|
2013-09-23 02:20:08 +04:00
|
|
|
ghostBookshelf = require('./base'),
|
2014-01-30 16:27:29 +04:00
|
|
|
crypto = require('crypto'),
|
2014-02-19 21:32:23 +04:00
|
|
|
validator = require('validator'),
|
2014-08-07 21:50:23 +04:00
|
|
|
validation = require('../data/validation'),
|
2015-03-24 23:23:23 +03:00
|
|
|
events = require('../events'),
|
2015-11-12 15:29:45 +03:00
|
|
|
i18n = require('../i18n'),
|
2016-06-02 16:38:02 +03:00
|
|
|
toString = require('lodash.tostring'),
|
2014-01-30 16:27:29 +04:00
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
bcryptGenSalt = Promise.promisify(bcrypt.genSalt),
|
|
|
|
bcryptHash = Promise.promisify(bcrypt.hash),
|
|
|
|
bcryptCompare = Promise.promisify(bcrypt.compare),
|
|
|
|
|
2014-02-19 17:57:26 +04:00
|
|
|
tokenSecurity = {},
|
2014-08-05 22:11:17 +04:00
|
|
|
activeStates = ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked'],
|
|
|
|
invitedStates = ['invited', 'invited-pending'],
|
2014-02-19 17:57:26 +04:00
|
|
|
User,
|
|
|
|
Users;
|
2013-06-25 15:43:15 +04:00
|
|
|
|
2013-08-20 22:52:44 +04:00
|
|
|
function validatePasswordLength(password) {
|
2014-12-17 18:36:08 +03:00
|
|
|
return validator.isLength(password, 8);
|
2013-08-20 22:52:44 +04:00
|
|
|
}
|
|
|
|
|
2013-11-22 07:17:38 +04:00
|
|
|
function generatePasswordHash(password) {
|
|
|
|
// Generate a new salt
|
2014-08-17 10:17:23 +04:00
|
|
|
return bcryptGenSalt().then(function (salt) {
|
2013-11-22 07:17:38 +04:00
|
|
|
// Hash the provided password with bcrypt
|
2014-08-17 10:17:23 +04:00
|
|
|
return bcryptHash(password, salt);
|
2013-11-22 07:17:38 +04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2013-09-23 02:20:08 +04:00
|
|
|
User = ghostBookshelf.Model.extend({
|
2013-06-25 15:43:15 +04:00
|
|
|
|
|
|
|
tableName: 'users',
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
emitChange: function emitChange(event) {
|
2015-03-24 23:23:23 +03:00
|
|
|
events.emit('user' + '.' + event, this);
|
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
initialize: function initialize() {
|
2014-10-28 03:41:18 +03:00
|
|
|
ghostBookshelf.Model.prototype.initialize.apply(this, arguments);
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
this.on('created', function onCreated(model) {
|
2015-03-24 23:23:23 +03:00
|
|
|
model.emitChange('added');
|
|
|
|
|
|
|
|
// active is the default state, so if status isn't provided, this will be an active user
|
|
|
|
if (!model.get('status') || _.contains(activeStates, model.get('status'))) {
|
|
|
|
model.emitChange('activated');
|
|
|
|
}
|
2014-10-28 03:41:18 +03:00
|
|
|
});
|
2015-06-14 18:58:49 +03:00
|
|
|
this.on('updated', function onUpdated(model) {
|
2015-03-24 23:23:23 +03:00
|
|
|
model.statusChanging = model.get('status') !== model.updated('status');
|
|
|
|
model.isActive = _.contains(activeStates, model.get('status'));
|
|
|
|
|
|
|
|
if (model.statusChanging) {
|
|
|
|
model.emitChange(model.isActive ? 'activated' : 'deactivated');
|
|
|
|
} else {
|
|
|
|
if (model.isActive) {
|
|
|
|
model.emitChange('activated.edited');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
model.emitChange('edited');
|
2014-10-28 03:41:18 +03:00
|
|
|
});
|
2015-06-14 18:58:49 +03:00
|
|
|
this.on('destroyed', function onDestroyed(model) {
|
2015-03-24 23:23:23 +03:00
|
|
|
if (_.contains(activeStates, model.previous('status'))) {
|
|
|
|
model.emitChange('deactivated');
|
|
|
|
}
|
|
|
|
|
|
|
|
model.emitChange('deleted');
|
2014-10-28 03:41:18 +03:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
saving: function saving(newPage, attr, options) {
|
2014-07-08 20:00:59 +04:00
|
|
|
/*jshint unused:false*/
|
2014-03-25 14:59:15 +04:00
|
|
|
|
2013-09-14 23:01:46 +04:00
|
|
|
var self = this;
|
2013-08-25 14:49:31 +04:00
|
|
|
|
2014-02-19 17:57:26 +04:00
|
|
|
ghostBookshelf.Model.prototype.saving.apply(this, arguments);
|
2013-09-14 23:01:46 +04:00
|
|
|
|
2014-03-25 14:59:15 +04:00
|
|
|
if (this.hasChanged('slug') || !this.get('slug')) {
|
2013-09-14 23:01:46 +04:00
|
|
|
// Generating a slug requires a db call to look for conflicting slugs
|
2014-03-25 14:59:15 +04:00
|
|
|
return ghostBookshelf.Model.generateSlug(User, this.get('slug') || this.get('name'),
|
2015-01-16 09:56:53 +03:00
|
|
|
{status: 'all', transacting: options.transacting, shortSlug: !this.get('slug')})
|
2015-06-14 18:58:49 +03:00
|
|
|
.then(function then(slug) {
|
2013-09-14 23:01:46 +04:00
|
|
|
self.set({slug: slug});
|
|
|
|
});
|
|
|
|
}
|
2013-10-07 21:02:57 +04:00
|
|
|
},
|
|
|
|
|
2014-08-07 21:50:23 +04:00
|
|
|
// For the user model ONLY it is possible to disable validations.
|
|
|
|
// This is used to bypass validation during the credential check, and must never be done with user-provided data
|
|
|
|
// Should be removed when #3691 is done
|
2015-06-14 18:58:49 +03:00
|
|
|
validate: function validate() {
|
2016-02-18 02:02:16 +03:00
|
|
|
var opts = arguments[1],
|
|
|
|
userData;
|
|
|
|
|
2014-08-07 21:50:23 +04:00
|
|
|
if (opts && _.has(opts, 'validate') && opts.validate === false) {
|
|
|
|
return;
|
|
|
|
}
|
2016-02-18 02:02:16 +03:00
|
|
|
|
|
|
|
// use the base toJSON since this model's overridden toJSON
|
|
|
|
// removes fields and we want everything to run through the validator.
|
|
|
|
userData = ghostBookshelf.Model.prototype.toJSON.call(this);
|
|
|
|
|
|
|
|
return validation.validateSchema(this.tableName, userData);
|
2014-08-07 21:50:23 +04:00
|
|
|
},
|
|
|
|
|
2014-07-15 15:03:12 +04:00
|
|
|
// Get the user from the options object
|
2015-06-14 18:58:49 +03:00
|
|
|
contextUser: function contextUser(options) {
|
2014-07-15 15:03:12 +04:00
|
|
|
// Default to context user
|
|
|
|
if (options.context && options.context.user) {
|
|
|
|
return options.context.user;
|
|
|
|
// Other wise use the internal override
|
|
|
|
} else if (options.context && options.context.internal) {
|
|
|
|
return 1;
|
|
|
|
// This is the user object, so try using this user's id
|
|
|
|
} else if (this.get('id')) {
|
|
|
|
return this.get('id');
|
|
|
|
} else {
|
2015-11-12 15:29:45 +03:00
|
|
|
errors.logAndThrowError(new errors.NotFoundError(i18n.t('errors.models.user.missingContext')));
|
2014-07-15 15:03:12 +04:00
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
toJSON: function toJSON(options) {
|
2015-07-04 21:27:23 +03:00
|
|
|
options = options || {};
|
|
|
|
|
2014-05-06 14:14:58 +04:00
|
|
|
var attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options);
|
|
|
|
// remove password hash for security reasons
|
|
|
|
delete attrs.password;
|
2014-05-06 05:45:08 +04:00
|
|
|
|
2015-04-18 00:27:04 +03:00
|
|
|
if (!options || !options.context || (!options.context.user && !options.context.internal)) {
|
|
|
|
delete attrs.email;
|
|
|
|
}
|
|
|
|
|
2014-05-06 14:14:58 +04:00
|
|
|
return attrs;
|
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
format: function format(options) {
|
2014-11-17 07:35:32 +03:00
|
|
|
if (!_.isEmpty(options.website) &&
|
|
|
|
!validator.isURL(options.website, {
|
|
|
|
require_protocol: true,
|
|
|
|
protocols: ['http', 'https']})) {
|
|
|
|
options.website = 'http://' + options.website;
|
|
|
|
}
|
2015-03-25 07:11:25 +03:00
|
|
|
return ghostBookshelf.Model.prototype.format.call(this, options);
|
2014-11-17 07:35:32 +03:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
posts: function posts() {
|
2014-07-13 15:17:18 +04:00
|
|
|
return this.hasMany('Posts', 'created_by');
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
roles: function roles() {
|
2014-07-13 15:17:18 +04:00
|
|
|
return this.belongsToMany('Role');
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
permissions: function permissions() {
|
2014-07-13 15:17:18 +04:00
|
|
|
return this.belongsToMany('Permission');
|
2014-07-24 13:46:05 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
hasRole: function hasRole(roleName) {
|
2014-07-24 13:46:05 +04:00
|
|
|
var roles = this.related('roles');
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return roles.some(function getRole(role) {
|
2014-07-24 13:46:05 +04:00
|
|
|
return role.get('name') === roleName;
|
|
|
|
});
|
2015-11-11 20:52:44 +03:00
|
|
|
},
|
2016-04-14 18:54:49 +03:00
|
|
|
|
2015-11-11 20:52:44 +03:00
|
|
|
enforcedFilters: function enforcedFilters() {
|
2016-04-14 18:54:49 +03:00
|
|
|
if (this.isInternalContext()) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2015-11-11 20:52:44 +03:00
|
|
|
return this.isPublicContext() ? 'status:[' + activeStates.join(',') + ']' : null;
|
|
|
|
},
|
2016-04-14 18:54:49 +03:00
|
|
|
|
2015-11-11 20:52:44 +03:00
|
|
|
defaultFilters: function defaultFilters() {
|
|
|
|
return this.isPublicContext() ? null : 'status:[' + activeStates.join(',') + ']';
|
2013-06-25 15:43:15 +04:00
|
|
|
}
|
|
|
|
}, {
|
2015-06-17 16:55:39 +03:00
|
|
|
orderDefaultOptions: function orderDefaultOptions() {
|
|
|
|
return {
|
|
|
|
last_login: 'DESC',
|
|
|
|
name: 'ASC',
|
|
|
|
created_at: 'DESC'
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
2015-11-11 22:31:52 +03:00
|
|
|
/**
|
|
|
|
* @deprecated in favour of filter
|
|
|
|
*/
|
|
|
|
processOptions: function processOptions(options) {
|
|
|
|
if (!options.status) {
|
|
|
|
return options;
|
|
|
|
}
|
|
|
|
|
|
|
|
// This is the only place that 'options.where' is set now
|
|
|
|
options.where = {statements: []};
|
|
|
|
|
|
|
|
var allStates = activeStates.concat(invitedStates),
|
|
|
|
value;
|
2015-06-17 16:55:39 +03:00
|
|
|
|
|
|
|
// Filter on the status. A status of 'all' translates to no filter since we want all statuses
|
2015-11-11 22:31:52 +03:00
|
|
|
if (options.status !== 'all') {
|
2015-06-17 16:55:39 +03:00
|
|
|
// make sure that status is valid
|
2015-11-11 22:31:52 +03:00
|
|
|
options.status = allStates.indexOf(options.status) > -1 ? options.status : 'active';
|
2015-06-17 16:55:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (options.status === 'active') {
|
2015-11-11 22:31:52 +03:00
|
|
|
value = activeStates;
|
2015-06-17 16:55:39 +03:00
|
|
|
} else if (options.status === 'invited') {
|
2015-11-11 22:31:52 +03:00
|
|
|
value = invitedStates;
|
|
|
|
} else if (options.status === 'all') {
|
|
|
|
value = allStates;
|
|
|
|
} else {
|
|
|
|
value = options.status;
|
2015-06-17 16:55:39 +03:00
|
|
|
}
|
|
|
|
|
2015-11-11 22:31:52 +03:00
|
|
|
options.where.statements.push({prop: 'status', op: 'IN', value: value});
|
|
|
|
delete options.status;
|
|
|
|
|
2015-06-17 16:55:39 +03:00
|
|
|
return options;
|
|
|
|
},
|
|
|
|
|
2014-05-06 05:45:08 +04:00
|
|
|
/**
|
|
|
|
* Returns an array of keys permitted in a method's `options` hash, depending on the current method.
|
|
|
|
* @param {String} methodName The name of the method to check valid options for.
|
|
|
|
* @return {Array} Keys allowed in the `options` hash of the model's method.
|
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
permittedOptions: function permittedOptions(methodName) {
|
2014-05-06 05:45:08 +04:00
|
|
|
var options = ghostBookshelf.Model.permittedOptions(),
|
|
|
|
|
|
|
|
// whitelists for the `options` hash argument on methods, by method name.
|
|
|
|
// these are the only options that can be passed to Bookshelf / Knex.
|
|
|
|
validOptions = {
|
2014-08-05 22:11:17 +04:00
|
|
|
findOne: ['withRelated', 'status'],
|
2014-07-15 15:03:12 +04:00
|
|
|
setup: ['id'],
|
2014-07-20 20:42:03 +04:00
|
|
|
edit: ['withRelated', 'id'],
|
2016-04-14 18:54:49 +03:00
|
|
|
findPage: ['page', 'limit', 'columns', 'filter', 'order', 'status'],
|
|
|
|
findAll: ['filter']
|
2014-05-06 05:45:08 +04:00
|
|
|
};
|
|
|
|
|
|
|
|
if (validOptions[methodName]) {
|
|
|
|
options = options.concat(validOptions[methodName]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return options;
|
|
|
|
},
|
2013-06-25 15:43:15 +04:00
|
|
|
|
2014-07-08 20:00:59 +04:00
|
|
|
/**
|
|
|
|
* ### Find One
|
|
|
|
* @extends ghostBookshelf.Model.findOne to include roles
|
|
|
|
* **See:** [ghostBookshelf.Model.findOne](base.js.html#Find%20One)
|
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
findOne: function findOne(data, options) {
|
2014-08-05 22:11:17 +04:00
|
|
|
var query,
|
2015-01-20 20:40:25 +03:00
|
|
|
status,
|
2015-11-24 17:31:28 +03:00
|
|
|
optInc,
|
2015-01-20 20:40:25 +03:00
|
|
|
lookupRole = data.role;
|
|
|
|
|
|
|
|
delete data.role;
|
2014-08-05 22:11:17 +04:00
|
|
|
|
2015-06-25 21:56:27 +03:00
|
|
|
data = _.defaults(data || {}, {
|
2014-08-05 22:11:17 +04:00
|
|
|
status: 'active'
|
2015-06-25 21:56:27 +03:00
|
|
|
});
|
2014-08-05 22:11:17 +04:00
|
|
|
|
|
|
|
status = data.status;
|
|
|
|
delete data.status;
|
|
|
|
|
2014-07-08 20:00:59 +04:00
|
|
|
options = options || {};
|
2015-11-24 17:31:28 +03:00
|
|
|
optInc = options.include;
|
2014-11-27 03:28:29 +03:00
|
|
|
options.withRelated = _.union(options.withRelated, options.include);
|
2015-06-15 19:45:58 +03:00
|
|
|
data = this.filterData(data);
|
2014-07-08 20:00:59 +04:00
|
|
|
|
2014-07-15 15:03:12 +04:00
|
|
|
// Support finding by role
|
2015-01-20 20:40:25 +03:00
|
|
|
if (lookupRole) {
|
|
|
|
options.withRelated = _.union(options.withRelated, ['roles']);
|
|
|
|
options.include = _.union(options.include, ['roles']);
|
2014-07-15 15:03:12 +04:00
|
|
|
|
2015-01-20 20:40:25 +03:00
|
|
|
query = this.forge(data, {include: options.include});
|
|
|
|
|
2016-05-22 11:37:44 +03:00
|
|
|
query.query('join', 'roles_users', 'users.id', '=', 'roles_users.user_id');
|
2015-01-20 20:40:25 +03:00
|
|
|
query.query('join', 'roles', 'roles_users.role_id', '=', 'roles.id');
|
|
|
|
query.query('where', 'roles.name', '=', lookupRole);
|
|
|
|
} else {
|
|
|
|
// We pass include to forge so that toJSON has access
|
|
|
|
query = this.forge(data, {include: options.include});
|
|
|
|
}
|
2014-08-05 22:11:17 +04:00
|
|
|
|
|
|
|
if (status === 'active') {
|
|
|
|
query.query('whereIn', 'status', activeStates);
|
|
|
|
} else if (status === 'invited') {
|
|
|
|
query.query('whereIn', 'status', invitedStates);
|
|
|
|
} else if (status !== 'all') {
|
2014-09-10 08:06:24 +04:00
|
|
|
query.query('where', {status: options.status});
|
2014-07-31 08:25:42 +04:00
|
|
|
}
|
|
|
|
|
2014-08-05 22:11:17 +04:00
|
|
|
options = this.filterOptions(options, 'findOne');
|
|
|
|
delete options.include;
|
2015-11-24 17:31:28 +03:00
|
|
|
options.include = optInc;
|
2014-08-05 22:11:17 +04:00
|
|
|
|
|
|
|
return query.fetch(options);
|
2014-07-08 20:00:59 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ### Edit
|
|
|
|
* @extends ghostBookshelf.Model.edit to handle returning the full object
|
|
|
|
* **See:** [ghostBookshelf.Model.edit](base.js.html#edit)
|
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
edit: function edit(data, options) {
|
2014-07-22 00:50:43 +04:00
|
|
|
var self = this,
|
2014-07-24 12:17:10 +04:00
|
|
|
roleId;
|
2014-07-22 00:50:43 +04:00
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
if (data.roles && data.roles.length > 1) {
|
|
|
|
return Promise.reject(
|
2015-11-12 15:29:45 +03:00
|
|
|
new errors.ValidationError(i18n.t('errors.models.user.onlyOneRolePerUserSupported'))
|
2014-12-17 18:36:08 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2014-07-08 20:00:59 +04:00
|
|
|
options = options || {};
|
2014-11-27 03:28:29 +03:00
|
|
|
options.withRelated = _.union(options.withRelated, options.include);
|
2014-07-08 20:00:59 +04:00
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return ghostBookshelf.Model.edit.call(this, data, options).then(function then(user) {
|
2014-12-17 18:36:08 +03:00
|
|
|
if (!data.roles) {
|
|
|
|
return user;
|
|
|
|
}
|
|
|
|
|
|
|
|
roleId = parseInt(data.roles[0].id || data.roles[0], 10);
|
2014-07-22 00:50:43 +04:00
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return user.roles().fetch().then(function then(roles) {
|
2014-12-17 18:36:08 +03:00
|
|
|
// return if the role is already assigned
|
|
|
|
if (roles.models[0].id === roleId) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
return ghostBookshelf.model('Role').findOne({id: roleId});
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(roleToAssign) {
|
2014-12-17 18:36:08 +03:00
|
|
|
if (roleToAssign && roleToAssign.get('name') === 'Owner') {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(
|
2015-11-12 15:29:45 +03:00
|
|
|
new errors.ValidationError(i18n.t('errors.models.user.methodDoesNotSupportOwnerRole'))
|
2014-07-24 13:46:05 +04:00
|
|
|
);
|
2014-12-17 18:36:08 +03:00
|
|
|
} else {
|
|
|
|
// assign all other roles
|
|
|
|
return user.roles().updatePivot({role_id: roleId});
|
2014-07-22 00:50:43 +04:00
|
|
|
}
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then() {
|
2014-12-17 18:36:08 +03:00
|
|
|
options.status = 'all';
|
|
|
|
return self.findOne({id: user.id}, options);
|
|
|
|
});
|
2014-07-22 00:50:43 +04:00
|
|
|
});
|
2014-07-08 20:00:59 +04:00
|
|
|
},
|
|
|
|
|
2013-06-25 15:43:15 +04:00
|
|
|
/**
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
* ## Add
|
2013-06-25 15:43:15 +04:00
|
|
|
* Naive user add
|
|
|
|
* Hashes the password provided before saving to the database.
|
Refactor API arguments
closes #2610, refs #2697
- cleanup API index.js, and add docs
- all API methods take consistent arguments: object & options
- browse, read, destroy take options, edit and add take object and options
- the context is passed as part of options, meaning no more .call
everywhere
- destroy expects an object, rather than an id all the way down to the model layer
- route params such as :id, :slug, and :key are passed as an option & used
to perform reads, updates and deletes where possible - settings / themes
may need work here still
- HTTP posts api can find a post by slug
- Add API utils for checkData
2014-05-08 16:41:19 +04:00
|
|
|
*
|
|
|
|
* @param {object} data
|
|
|
|
* @param {object} options
|
|
|
|
* @extends ghostBookshelf.Model.add to manage all aspects of user signup
|
|
|
|
* **See:** [ghostBookshelf.Model.add](base.js.html#Add)
|
2013-06-25 15:43:15 +04:00
|
|
|
*/
|
2015-06-14 18:58:49 +03:00
|
|
|
add: function add(data, options) {
|
2013-08-16 03:22:08 +04:00
|
|
|
var self = this,
|
2014-07-24 13:46:05 +04:00
|
|
|
userData = this.filterData(data),
|
2014-07-30 19:40:30 +04:00
|
|
|
roles;
|
2014-05-06 05:45:08 +04:00
|
|
|
|
2016-06-02 16:38:02 +03:00
|
|
|
userData.password = toString(userData.password);
|
2016-03-27 13:19:32 +03:00
|
|
|
|
2014-05-06 05:45:08 +04:00
|
|
|
options = this.filterOptions(options, 'add');
|
2014-11-27 03:28:29 +03:00
|
|
|
options.withRelated = _.union(options.withRelated, options.include);
|
2014-07-31 23:53:55 +04:00
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
// check for too many roles
|
|
|
|
if (data.roles && data.roles.length > 1) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.onlyOneRolePerUserSupported')));
|
2014-12-17 18:36:08 +03:00
|
|
|
}
|
2014-07-31 04:15:34 +04:00
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
if (!validatePasswordLength(userData.password)) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.passwordDoesNotComplyLength')));
|
2014-12-17 18:36:08 +03:00
|
|
|
}
|
2014-05-06 05:45:08 +04:00
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
function getAuthorRole() {
|
2015-06-14 18:58:49 +03:00
|
|
|
return ghostBookshelf.model('Role').findOne({name: 'Author'}, _.pick(options, 'transacting')).then(function then(authorRole) {
|
2014-12-17 18:36:08 +03:00
|
|
|
return [authorRole.get('id')];
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
roles = data.roles || getAuthorRole();
|
|
|
|
delete data.roles;
|
|
|
|
|
2015-08-28 00:28:29 +03:00
|
|
|
return generatePasswordHash(userData.password).then(function then(hash) {
|
2013-08-16 03:22:08 +04:00
|
|
|
// Assign the hashed password
|
2015-08-28 00:28:29 +03:00
|
|
|
userData.password = hash;
|
2013-11-11 23:55:22 +04:00
|
|
|
// LookupGravatar
|
2016-02-12 23:04:26 +03:00
|
|
|
return gravatar.lookup(userData);
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(userData) {
|
2013-08-16 03:22:08 +04:00
|
|
|
// Save the user with the hashed password
|
2014-04-03 17:03:09 +04:00
|
|
|
return ghostBookshelf.Model.add.call(self, userData, options);
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(addedUser) {
|
2013-08-16 03:22:08 +04:00
|
|
|
// Assign the userData to our created user so we can pass it back
|
|
|
|
userData = addedUser;
|
2014-09-10 08:06:24 +04:00
|
|
|
// if we are given a "role" object, only pass in the role ID in place of the full object
|
2015-06-14 18:58:49 +03:00
|
|
|
return Promise.resolve(roles).then(function then(roles) {
|
|
|
|
roles = _.map(roles, function mapper(role) {
|
2014-12-17 18:36:08 +03:00
|
|
|
if (_.isString(role)) {
|
|
|
|
return parseInt(role, 10);
|
|
|
|
} else if (_.isNumber(role)) {
|
|
|
|
return role;
|
|
|
|
} else {
|
|
|
|
return parseInt(role.id, 10);
|
|
|
|
}
|
|
|
|
});
|
2014-07-24 13:46:05 +04:00
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
return addedUser.roles().attach(roles, options);
|
|
|
|
});
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then() {
|
2014-04-29 00:42:38 +04:00
|
|
|
// find and return the added user
|
2014-08-05 22:11:17 +04:00
|
|
|
return self.findOne({id: userData.id, status: 'all'}, options);
|
2013-08-19 01:50:42 +04:00
|
|
|
});
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
setup: function setup(data, options) {
|
2014-07-10 21:29:51 +04:00
|
|
|
var self = this,
|
|
|
|
userData = this.filterData(data);
|
2014-07-11 16:17:09 +04:00
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
if (!validatePasswordLength(userData.password)) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.passwordDoesNotComplyLength')));
|
2014-12-17 18:36:08 +03:00
|
|
|
}
|
|
|
|
|
2014-07-10 21:29:51 +04:00
|
|
|
options = this.filterOptions(options, 'setup');
|
2014-11-27 03:28:29 +03:00
|
|
|
options.withRelated = _.union(options.withRelated, options.include);
|
2014-09-30 02:45:58 +04:00
|
|
|
options.shortSlug = true;
|
2014-07-11 16:17:09 +04:00
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return generatePasswordHash(data.password).then(function then(hash) {
|
2014-07-10 21:29:51 +04:00
|
|
|
// Assign the hashed password
|
|
|
|
userData.password = hash;
|
2014-12-17 18:36:08 +03:00
|
|
|
|
2016-02-12 23:04:26 +03:00
|
|
|
return Promise.join(
|
|
|
|
gravatar.lookup(userData),
|
|
|
|
ghostBookshelf.Model.generateSlug.call(this, User, userData.name, options)
|
|
|
|
);
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(results) {
|
2014-12-17 18:36:08 +03:00
|
|
|
userData = results[0];
|
|
|
|
userData.slug = results[1];
|
|
|
|
|
2014-07-10 21:29:51 +04:00
|
|
|
return self.edit.call(self, userData, options);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
permissible: function permissible(userModelOrId, action, context, loadedPermissions, hasUserPermission, hasAppPermission) {
|
2014-04-08 17:40:33 +04:00
|
|
|
var self = this,
|
2014-05-14 05:49:07 +04:00
|
|
|
userModel = userModelOrId,
|
|
|
|
origArgs;
|
2014-04-08 17:40:33 +04:00
|
|
|
|
2014-11-27 03:28:29 +03:00
|
|
|
// If we passed in a model without its related roles, we need to fetch it again
|
|
|
|
if (_.isObject(userModelOrId) && !_.isObject(userModelOrId.related('roles'))) {
|
|
|
|
userModelOrId = userModelOrId.id;
|
|
|
|
}
|
|
|
|
// If we passed in an id instead of a model get the model first
|
2014-04-08 17:40:33 +04:00
|
|
|
if (_.isNumber(userModelOrId) || _.isString(userModelOrId)) {
|
2014-05-14 05:49:07 +04:00
|
|
|
// Grab the original args without the first one
|
|
|
|
origArgs = _.toArray(arguments).slice(1);
|
2015-12-02 10:28:36 +03:00
|
|
|
// Get the actual user model
|
2015-06-14 18:58:49 +03:00
|
|
|
return this.findOne({id: userModelOrId, status: 'all'}, {include: ['roles']}).then(function then(foundUserModel) {
|
2014-05-14 05:49:07 +04:00
|
|
|
// Build up the original args but substitute with actual model
|
|
|
|
var newArgs = [foundUserModel].concat(origArgs);
|
|
|
|
|
2014-07-23 22:17:29 +04:00
|
|
|
return self.permissible.apply(self, newArgs);
|
2014-04-08 17:40:33 +04:00
|
|
|
}, errors.logAndThrowError);
|
|
|
|
}
|
|
|
|
|
2014-07-24 13:46:05 +04:00
|
|
|
if (action === 'edit') {
|
2015-07-09 00:07:09 +03:00
|
|
|
// Owner can only be editted by owner
|
2015-10-22 16:28:47 +03:00
|
|
|
if (loadedPermissions.user && userModel.hasRole('Owner')) {
|
2015-07-09 00:07:09 +03:00
|
|
|
hasUserPermission = _.any(loadedPermissions.user.roles, {name: 'Owner'});
|
|
|
|
}
|
2014-07-24 13:46:05 +04:00
|
|
|
// Users with the role 'Editor' and 'Author' have complex permissions when the action === 'edit'
|
|
|
|
// We now have all the info we need to construct the permissions
|
2015-10-22 16:28:47 +03:00
|
|
|
if (loadedPermissions.user && _.any(loadedPermissions.user.roles, {name: 'Author'})) {
|
2015-05-01 00:14:19 +03:00
|
|
|
// If this is the same user that requests the operation allow it.
|
2014-07-24 13:46:05 +04:00
|
|
|
hasUserPermission = hasUserPermission || context.user === userModel.get('id');
|
|
|
|
}
|
|
|
|
|
2015-10-22 16:28:47 +03:00
|
|
|
if (loadedPermissions.user && _.any(loadedPermissions.user.roles, {name: 'Editor'})) {
|
2014-07-24 13:46:05 +04:00
|
|
|
// If this is the same user that requests the operation allow it.
|
|
|
|
hasUserPermission = context.user === userModel.get('id');
|
|
|
|
|
|
|
|
// Alternatively, if the user we are trying to edit is an Author, allow it
|
|
|
|
hasUserPermission = hasUserPermission || userModel.hasRole('Author');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (action === 'destroy') {
|
|
|
|
// Owner cannot be deleted EVER
|
2015-10-22 16:28:47 +03:00
|
|
|
if (loadedPermissions.user && userModel.hasRole('Owner')) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NoPermissionError(i18n.t('errors.models.user.notEnoughPermission')));
|
2014-07-24 13:46:05 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Users with the role 'Editor' have complex permissions when the action === 'destroy'
|
2015-10-22 16:28:47 +03:00
|
|
|
if (loadedPermissions.user && _.any(loadedPermissions.user.roles, {name: 'Editor'})) {
|
2015-05-01 00:14:19 +03:00
|
|
|
// If this is the same user that requests the operation allow it.
|
2014-07-24 13:46:05 +04:00
|
|
|
hasUserPermission = context.user === userModel.get('id');
|
|
|
|
|
|
|
|
// Alternatively, if the user we are trying to edit is an Author, allow it
|
|
|
|
hasUserPermission = hasUserPermission || userModel.hasRole('Author');
|
|
|
|
}
|
2014-05-14 05:49:07 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (hasUserPermission && hasAppPermission) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.resolve();
|
2014-04-08 17:40:33 +04:00
|
|
|
}
|
2014-05-14 05:49:07 +04:00
|
|
|
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NoPermissionError(i18n.t('errors.models.user.notEnoughPermission')));
|
2014-04-08 17:40:33 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
setWarning: function setWarning(user, options) {
|
2013-11-29 04:28:01 +04:00
|
|
|
var status = user.get('status'),
|
|
|
|
regexp = /warn-(\d+)/i,
|
|
|
|
level;
|
|
|
|
|
|
|
|
if (status === 'active') {
|
|
|
|
user.set('status', 'warn-1');
|
|
|
|
level = 1;
|
|
|
|
} else {
|
|
|
|
level = parseInt(status.match(regexp)[1], 10) + 1;
|
2015-03-03 00:58:00 +03:00
|
|
|
if (level > 4) {
|
2013-11-29 04:28:01 +04:00
|
|
|
user.set('status', 'locked');
|
|
|
|
} else {
|
|
|
|
user.set('status', 'warn-' + level);
|
|
|
|
}
|
|
|
|
}
|
2015-06-14 18:58:49 +03:00
|
|
|
return Promise.resolve(user.save(options)).then(function then() {
|
2013-11-29 04:28:01 +04:00
|
|
|
return 5 - level;
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2013-08-06 23:27:56 +04:00
|
|
|
// Finds the user by email, and checks the password
|
2015-06-14 18:58:49 +03:00
|
|
|
check: function check(object) {
|
2013-11-29 04:28:01 +04:00
|
|
|
var self = this,
|
|
|
|
s;
|
2015-06-14 18:58:49 +03:00
|
|
|
return this.getByEmail(object.email).then(function then(user) {
|
2014-07-24 19:34:52 +04:00
|
|
|
if (!user) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NotFoundError(i18n.t('errors.models.user.noUserWithEnteredEmailAddr')));
|
2014-07-24 19:34:52 +04:00
|
|
|
}
|
2014-07-24 13:46:05 +04:00
|
|
|
if (user.get('status') === 'invited' || user.get('status') === 'invited-pending' ||
|
|
|
|
user.get('status') === 'inactive'
|
|
|
|
) {
|
2016-02-18 15:52:53 +03:00
|
|
|
return Promise.reject(new errors.NoPermissionError(i18n.t('errors.models.user.userIsInactive')));
|
2014-07-02 18:22:18 +04:00
|
|
|
}
|
2013-11-29 04:28:01 +04:00
|
|
|
if (user.get('status') !== 'locked') {
|
2015-06-14 18:58:49 +03:00
|
|
|
return bcryptCompare(object.password, user.get('password')).then(function then(matched) {
|
2013-11-29 04:28:01 +04:00
|
|
|
if (!matched) {
|
2015-06-14 18:58:49 +03:00
|
|
|
return Promise.resolve(self.setWarning(user, {validate: false})).then(function then(remaining) {
|
2013-11-29 04:28:01 +04:00
|
|
|
s = (remaining > 1) ? 's' : '';
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.UnauthorizedError(i18n.t('errors.models.user.incorrectPasswordAttempts', {remaining: remaining, s: s})));
|
2014-08-07 21:50:23 +04:00
|
|
|
|
|
|
|
// Use comma structure, not .catch, because we don't want to catch incorrect passwords
|
2015-06-14 18:58:49 +03:00
|
|
|
}, function handleError(error) {
|
2014-08-07 21:50:23 +04:00
|
|
|
// If we get a validation or other error during this save, catch it and log it, but don't
|
|
|
|
// cause a login error because of it. The user validation is not important here.
|
|
|
|
errors.logError(
|
|
|
|
error,
|
2015-11-12 15:29:45 +03:00
|
|
|
i18n.t('errors.models.user.userUpdateError.context'),
|
|
|
|
i18n.t('errors.models.user.userUpdateError.help')
|
2014-08-07 21:50:23 +04:00
|
|
|
);
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.UnauthorizedError(i18n.t('errors.models.user.incorrectPassword')));
|
2013-11-29 04:28:01 +04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
return Promise.resolve(user.set({status: 'active', last_login: new Date()}).save({validate: false}))
|
2015-06-14 18:58:49 +03:00
|
|
|
.catch(function handleError(error) {
|
2014-08-07 21:50:23 +04:00
|
|
|
// If we get a validation or other error during this save, catch it and log it, but don't
|
|
|
|
// cause a login error because of it. The user validation is not important here.
|
|
|
|
errors.logError(
|
|
|
|
error,
|
2015-11-12 15:29:45 +03:00
|
|
|
i18n.t('errors.models.user.userUpdateError.context'),
|
|
|
|
i18n.t('errors.models.user.userUpdateError.help')
|
2014-08-07 21:50:23 +04:00
|
|
|
);
|
|
|
|
return user;
|
|
|
|
});
|
2013-11-29 04:28:01 +04:00
|
|
|
}, errors.logAndThrowError);
|
|
|
|
}
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NoPermissionError(
|
|
|
|
i18n.t('errors.models.user.accountLocked')));
|
2015-06-14 18:58:49 +03:00
|
|
|
}, function handleError(error) {
|
2014-01-15 02:47:17 +04:00
|
|
|
if (error.message === 'NotFound' || error.message === 'EmptyResponse') {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NotFoundError(i18n.t('errors.models.user.noUserWithEnteredEmailAddr')));
|
2014-01-15 02:47:17 +04:00
|
|
|
}
|
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(error);
|
2013-08-09 05:22:49 +04:00
|
|
|
});
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
2013-08-06 03:49:06 +04:00
|
|
|
/**
|
|
|
|
* Naive change password method
|
2015-07-07 16:32:50 +03:00
|
|
|
* @param {Object} object
|
2014-09-10 08:06:24 +04:00
|
|
|
* @param {Object} options
|
2013-08-06 03:49:06 +04:00
|
|
|
*/
|
2015-07-07 16:32:50 +03:00
|
|
|
changePassword: function changePassword(object, options) {
|
2013-08-20 22:52:44 +04:00
|
|
|
var self = this,
|
2015-07-07 16:32:50 +03:00
|
|
|
newPassword = object.newPassword,
|
|
|
|
ne2Password = object.ne2Password,
|
2016-03-26 03:17:06 +03:00
|
|
|
userId = parseInt(object.user_id),
|
2015-07-07 16:32:50 +03:00
|
|
|
oldPassword = object.oldPassword,
|
2014-12-17 18:36:08 +03:00
|
|
|
user;
|
2013-09-01 02:20:12 +04:00
|
|
|
|
2016-03-26 03:17:06 +03:00
|
|
|
// If the two passwords do not match
|
2013-08-06 03:49:06 +04:00
|
|
|
if (newPassword !== ne2Password) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.newPasswordsDoNotMatch')));
|
2014-12-11 23:23:07 +03:00
|
|
|
}
|
|
|
|
|
2016-03-26 03:17:06 +03:00
|
|
|
// If the old password is empty when changing current user's password
|
2014-12-11 23:23:07 +03:00
|
|
|
if (userId === options.context.user && _.isEmpty(oldPassword)) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.passwordRequiredForOperation')));
|
2013-08-06 03:49:06 +04:00
|
|
|
}
|
|
|
|
|
2016-03-26 03:17:06 +03:00
|
|
|
// If password is not complex enough
|
2014-12-17 18:36:08 +03:00
|
|
|
if (!validatePasswordLength(newPassword)) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.passwordDoesNotComplyLength')));
|
2014-12-17 18:36:08 +03:00
|
|
|
}
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return self.forge({id: userId}).fetch({require: true}).then(function then(_user) {
|
2013-09-01 02:20:12 +04:00
|
|
|
user = _user;
|
2016-03-26 03:17:06 +03:00
|
|
|
// If the user is the current user, check old password
|
2014-12-11 23:23:07 +03:00
|
|
|
if (userId === options.context.user) {
|
|
|
|
return bcryptCompare(oldPassword, user.get('password'));
|
|
|
|
}
|
2016-03-26 03:17:06 +03:00
|
|
|
// If user is admin and changing another user's password, old password isn't compared to the old one
|
2014-12-11 23:23:07 +03:00
|
|
|
return true;
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(matched) {
|
2013-09-01 02:20:12 +04:00
|
|
|
if (!matched) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.incorrectPassword')));
|
2013-09-01 02:20:12 +04:00
|
|
|
}
|
2014-12-17 18:36:08 +03:00
|
|
|
|
|
|
|
return generatePasswordHash(newPassword);
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(hash) {
|
2014-12-17 18:36:08 +03:00
|
|
|
return user.save({password: hash});
|
2013-08-06 03:49:06 +04:00
|
|
|
});
|
2013-09-01 02:20:12 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
generateResetToken: function generateResetToken(email, expires, dbHash) {
|
|
|
|
return this.getByEmail(email).then(function then(foundUser) {
|
2014-07-02 18:22:18 +04:00
|
|
|
if (!foundUser) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NotFoundError(i18n.t('errors.models.user.noUserWithEnteredEmailAddr')));
|
2014-07-02 18:22:18 +04:00
|
|
|
}
|
|
|
|
|
2013-11-22 07:17:38 +04:00
|
|
|
var hash = crypto.createHash('sha256'),
|
2014-07-15 15:03:12 +04:00
|
|
|
text = '';
|
2013-08-20 22:52:44 +04:00
|
|
|
|
2013-11-22 07:17:38 +04:00
|
|
|
// Token:
|
2014-12-01 18:59:49 +03:00
|
|
|
// BASE64(TIMESTAMP + email + HASH(TIMESTAMP + email + oldPasswordHash + dbHash ))
|
2013-11-22 07:17:38 +04:00
|
|
|
hash.update(String(expires));
|
|
|
|
hash.update(email.toLocaleLowerCase());
|
|
|
|
hash.update(foundUser.get('password'));
|
|
|
|
hash.update(String(dbHash));
|
|
|
|
|
|
|
|
text += [expires, email, hash.digest('base64')].join('|');
|
2014-12-01 18:59:49 +03:00
|
|
|
return new Buffer(text).toString('base64');
|
2013-11-22 07:17:38 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
validateToken: function validateToken(token, dbHash) {
|
2014-01-30 16:27:29 +04:00
|
|
|
/*jslint bitwise:true*/
|
2013-11-22 07:17:38 +04:00
|
|
|
// TODO: Is there a chance the use of ascii here will cause problems if oldPassword has weird characters?
|
|
|
|
var tokenText = new Buffer(token, 'base64').toString('ascii'),
|
|
|
|
parts,
|
|
|
|
expires,
|
|
|
|
email;
|
|
|
|
|
|
|
|
parts = tokenText.split('|');
|
|
|
|
|
|
|
|
// Check if invalid structure
|
|
|
|
if (!parts || parts.length !== 3) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.BadRequestError(i18n.t('errors.models.user.invalidTokenStructure')));
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
expires = parseInt(parts[0], 10);
|
|
|
|
email = parts[1];
|
|
|
|
|
|
|
|
if (isNaN(expires)) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.BadRequestError(i18n.t('errors.models.user.invalidTokenExpiration')));
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
2014-01-30 16:27:29 +04:00
|
|
|
// Check if token is expired to prevent replay attacks
|
2013-11-22 07:17:38 +04:00
|
|
|
if (expires < Date.now()) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.expiredToken')));
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
2014-07-24 13:46:05 +04:00
|
|
|
// to prevent brute force attempts to reset the password the combination of email+expires is only allowed for
|
|
|
|
// 10 attempts
|
2014-01-30 16:27:29 +04:00
|
|
|
if (tokenSecurity[email + '+' + expires] && tokenSecurity[email + '+' + expires].count >= 10) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NoPermissionError(i18n.t('errors.models.user.tokenLocked')));
|
2014-01-30 16:27:29 +04:00
|
|
|
}
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return this.generateResetToken(email, expires, dbHash).then(function then(generatedToken) {
|
2014-01-30 16:27:29 +04:00
|
|
|
// Check for matching tokens with timing independent comparison
|
|
|
|
var diff = 0,
|
|
|
|
i;
|
|
|
|
|
2014-05-06 05:45:08 +04:00
|
|
|
// check if the token length is correct
|
2014-01-30 16:27:29 +04:00
|
|
|
if (token.length !== generatedToken.length) {
|
|
|
|
diff = 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (i = token.length - 1; i >= 0; i = i - 1) {
|
|
|
|
diff |= token.charCodeAt(i) ^ generatedToken.charCodeAt(i);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (diff === 0) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return email;
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
2014-01-30 16:27:29 +04:00
|
|
|
// increase the count for email+expires for each failed attempt
|
2014-07-24 13:46:05 +04:00
|
|
|
tokenSecurity[email + '+' + expires] = {
|
|
|
|
count: tokenSecurity[email + '+' + expires] ? tokenSecurity[email + '+' + expires].count + 1 : 1
|
|
|
|
};
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.BadRequestError(i18n.t('errors.models.user.invalidToken')));
|
2013-11-22 07:17:38 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2015-07-07 16:32:50 +03:00
|
|
|
resetPassword: function resetPassword(options) {
|
|
|
|
var self = this,
|
|
|
|
token = options.token,
|
|
|
|
newPassword = options.newPassword,
|
|
|
|
ne2Password = options.ne2Password,
|
|
|
|
dbHash = options.dbHash;
|
2013-11-22 07:17:38 +04:00
|
|
|
|
|
|
|
if (newPassword !== ne2Password) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.newPasswordsDoNotMatch')));
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
2014-12-17 18:36:08 +03:00
|
|
|
if (!validatePasswordLength(newPassword)) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError(i18n.t('errors.models.user.passwordDoesNotComplyLength')));
|
2014-12-17 18:36:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Validate the token; returns the email address from token
|
2015-06-14 18:58:49 +03:00
|
|
|
return self.validateToken(utils.decodeBase64URLsafe(token), dbHash).then(function then(email) {
|
2013-11-22 07:17:38 +04:00
|
|
|
// Fetch the user by email, and hash the password at the same time.
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.join(
|
2014-10-22 01:18:45 +04:00
|
|
|
self.getByEmail(email),
|
2013-11-22 07:17:38 +04:00
|
|
|
generatePasswordHash(newPassword)
|
|
|
|
);
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(results) {
|
2014-10-22 01:18:45 +04:00
|
|
|
if (!results[0]) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NotFoundError(i18n.t('errors.models.user.userNotFound')));
|
2014-10-22 01:18:45 +04:00
|
|
|
}
|
|
|
|
|
2013-11-22 07:17:38 +04:00
|
|
|
// Update the user with the new password hash
|
|
|
|
var foundUser = results[0],
|
|
|
|
passwordHash = results[1];
|
|
|
|
|
2014-07-03 19:06:07 +04:00
|
|
|
return foundUser.save({password: passwordHash, status: 'active'});
|
2013-09-01 02:20:12 +04:00
|
|
|
});
|
2013-08-06 03:49:06 +04:00
|
|
|
},
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
transferOwnership: function transferOwnership(object, options) {
|
2014-12-17 18:36:08 +03:00
|
|
|
var ownerRole,
|
|
|
|
contextUser;
|
|
|
|
|
|
|
|
return Promise.join(ghostBookshelf.model('Role').findOne({name: 'Owner'}),
|
|
|
|
User.findOne({id: options.context.user}, {include: ['roles']}))
|
2015-06-14 18:58:49 +03:00
|
|
|
.then(function then(results) {
|
2014-12-17 18:36:08 +03:00
|
|
|
ownerRole = results[0];
|
|
|
|
contextUser = results[1];
|
|
|
|
|
2014-07-24 13:46:05 +04:00
|
|
|
// check if user has the owner role
|
2015-04-18 00:27:04 +03:00
|
|
|
var currentRoles = contextUser.toJSON(options).roles;
|
2014-11-27 03:28:29 +03:00
|
|
|
if (!_.any(currentRoles, {id: ownerRole.id})) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.NoPermissionError(i18n.t('errors.models.user.onlyOwnerCanTransferOwnerRole')));
|
2014-07-24 13:46:05 +04:00
|
|
|
}
|
2014-12-17 18:36:08 +03:00
|
|
|
|
|
|
|
return Promise.join(ghostBookshelf.model('Role').findOne({name: 'Administrator'}),
|
|
|
|
User.findOne({id: object.id}, {include: ['roles']}));
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(results) {
|
2014-12-17 18:36:08 +03:00
|
|
|
var adminRole = results[0],
|
|
|
|
user = results[1],
|
2015-04-18 00:27:04 +03:00
|
|
|
currentRoles = user.toJSON(options).roles;
|
2014-12-17 18:36:08 +03:00
|
|
|
|
2014-11-27 03:28:29 +03:00
|
|
|
if (!_.any(currentRoles, {id: adminRole.id})) {
|
2015-11-12 15:29:45 +03:00
|
|
|
return Promise.reject(new errors.ValidationError('errors.models.user.onlyAdmCanBeAssignedOwnerRole'));
|
2014-07-30 19:40:30 +04:00
|
|
|
}
|
|
|
|
|
2014-07-24 13:46:05 +04:00
|
|
|
// convert owner to admin
|
2014-12-17 18:36:08 +03:00
|
|
|
return Promise.join(contextUser.roles().updatePivot({role_id: adminRole.id}),
|
|
|
|
user.roles().updatePivot({role_id: ownerRole.id}),
|
|
|
|
user.id);
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(results) {
|
2014-07-31 17:41:10 +04:00
|
|
|
return Users.forge()
|
2014-12-17 18:36:08 +03:00
|
|
|
.query('whereIn', 'id', [contextUser.id, results[2]])
|
2014-09-10 08:06:24 +04:00
|
|
|
.fetch({withRelated: ['roles']});
|
2015-06-14 18:58:49 +03:00
|
|
|
}).then(function then(users) {
|
2015-04-18 00:27:04 +03:00
|
|
|
options.include = ['roles'];
|
|
|
|
return users.toJSON(options);
|
2014-07-24 13:46:05 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2014-01-15 02:47:17 +04:00
|
|
|
// Get the user by email address, enforces case insensitivity rejects if the user is not found
|
|
|
|
// When multi-user support is added, email addresses must be deduplicated with case insensitivity, so that
|
|
|
|
// joe@bloggs.com and JOE@BLOGGS.COM cannot be created as two separate users.
|
2015-06-14 18:58:49 +03:00
|
|
|
getByEmail: function getByEmail(email, options) {
|
2014-07-31 04:15:34 +04:00
|
|
|
options = options || {};
|
2014-01-15 02:47:17 +04:00
|
|
|
// We fetch all users and process them in JS as there is no easy way to make this query across all DBs
|
|
|
|
// Although they all support `lower()`, sqlite can't case transform unicode characters
|
|
|
|
// This is somewhat mute, as validator.isEmail() also doesn't support unicode, but this is much easier / more
|
|
|
|
// likely to be fixed in the near future.
|
2014-07-31 04:15:34 +04:00
|
|
|
options.require = true;
|
|
|
|
|
2015-06-14 18:58:49 +03:00
|
|
|
return Users.forge(options).fetch(options).then(function then(users) {
|
|
|
|
var userWithEmail = users.find(function findUser(user) {
|
2014-01-15 02:47:17 +04:00
|
|
|
return user.get('email').toLowerCase() === email.toLowerCase();
|
|
|
|
});
|
|
|
|
if (userWithEmail) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return userWithEmail;
|
2014-01-15 02:47:17 +04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2013-06-25 15:43:15 +04:00
|
|
|
});
|
2013-06-01 18:47:41 +04:00
|
|
|
|
2013-09-23 02:20:08 +04:00
|
|
|
Users = ghostBookshelf.Collection.extend({
|
2013-06-25 15:43:15 +04:00
|
|
|
model: User
|
|
|
|
});
|
2013-06-01 18:47:41 +04:00
|
|
|
|
2013-06-25 15:43:15 +04:00
|
|
|
module.exports = {
|
2014-07-13 15:17:18 +04:00
|
|
|
User: ghostBookshelf.model('User', User),
|
|
|
|
Users: ghostBookshelf.collection('Users', Users)
|
2013-08-06 03:49:06 +04:00
|
|
|
};
|