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'),
|
2013-10-23 17:00:28 +04:00
|
|
|
bcrypt = require('bcryptjs'),
|
2013-09-23 02:20:08 +04:00
|
|
|
ghostBookshelf = require('./base'),
|
2013-11-11 23:55:22 +04:00
|
|
|
http = require('http'),
|
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'),
|
2014-09-03 08:27:37 +04:00
|
|
|
config = require('../config'),
|
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) {
|
|
|
|
try {
|
2014-02-28 10:51:52 +04:00
|
|
|
if (!validator.isLength(password, 8)) {
|
|
|
|
throw new Error('Your password must be at least 8 characters long.');
|
|
|
|
}
|
2013-08-20 22:52:44 +04:00
|
|
|
} catch (error) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(error);
|
2013-08-20 22:52:44 +04:00
|
|
|
}
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.resolve();
|
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',
|
|
|
|
|
2014-03-25 14:59:15 +04:00
|
|
|
saving: function (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'),
|
|
|
|
{transacting: options.transacting})
|
2013-09-14 23:01:46 +04:00
|
|
|
.then(function (slug) {
|
|
|
|
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
|
|
|
|
validate: function () {
|
|
|
|
var opts = arguments[1];
|
|
|
|
if (opts && _.has(opts, 'validate') && opts.validate === false) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
return validation.validateSchema(this.tableName, this.toJSON());
|
|
|
|
},
|
|
|
|
|
2014-07-15 15:03:12 +04:00
|
|
|
// Get the user from the options object
|
|
|
|
contextUser: function (options) {
|
|
|
|
// 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 {
|
|
|
|
errors.logAndThrowError(new Error('missing context'));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2014-05-06 14:14:58 +04:00
|
|
|
toJSON: function (options) {
|
|
|
|
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
|
|
|
|
2014-05-06 14:14:58 +04:00
|
|
|
return attrs;
|
|
|
|
},
|
|
|
|
|
2013-06-25 15:43:15 +04:00
|
|
|
posts: function () {
|
2014-07-13 15:17:18 +04:00
|
|
|
return this.hasMany('Posts', 'created_by');
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
roles: function () {
|
2014-07-13 15:17:18 +04:00
|
|
|
return this.belongsToMany('Role');
|
2013-06-25 15:43:15 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
permissions: function () {
|
2014-07-13 15:17:18 +04:00
|
|
|
return this.belongsToMany('Permission');
|
2014-07-24 13:46:05 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
hasRole: function (roleName) {
|
|
|
|
var roles = this.related('roles');
|
|
|
|
|
|
|
|
return roles.some(function (role) {
|
|
|
|
return role.get('name') === roleName;
|
|
|
|
});
|
2013-06-25 15:43:15 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
}, {
|
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.
|
|
|
|
*/
|
|
|
|
permittedOptions: function (methodName) {
|
|
|
|
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-08 20:00:59 +04:00
|
|
|
findAll: ['withRelated'],
|
2014-07-15 15:03:12 +04:00
|
|
|
setup: ['id'],
|
2014-07-20 20:42:03 +04:00
|
|
|
edit: ['withRelated', 'id'],
|
|
|
|
findPage: ['page', 'limit', 'status']
|
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 All
|
|
|
|
*
|
2014-09-10 08:06:24 +04:00
|
|
|
* @param {Object} options
|
2014-07-08 20:00:59 +04:00
|
|
|
* @returns {*}
|
|
|
|
*/
|
|
|
|
findAll: function (options) {
|
|
|
|
options = options || {};
|
2014-09-10 08:06:24 +04:00
|
|
|
options.withRelated = _.union(['roles'], options.include);
|
2014-07-08 20:00:59 +04:00
|
|
|
return ghostBookshelf.Model.findAll.call(this, options);
|
|
|
|
},
|
|
|
|
|
2014-07-20 20:42:03 +04:00
|
|
|
/**
|
|
|
|
* #### findPage
|
|
|
|
* Find results by page - returns an object containing the
|
|
|
|
* information about the request (page, limit), along with the
|
|
|
|
* info needed for pagination (pages, total).
|
|
|
|
*
|
|
|
|
* **response:**
|
|
|
|
*
|
|
|
|
* {
|
|
|
|
* users: [
|
|
|
|
* {...}, {...}, {...}
|
|
|
|
* ],
|
|
|
|
* meta: {
|
|
|
|
* page: __,
|
|
|
|
* limit: __,
|
|
|
|
* pages: __,
|
|
|
|
* total: __
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
*
|
2014-09-10 08:06:24 +04:00
|
|
|
* @param {Object} options
|
2014-07-20 20:42:03 +04:00
|
|
|
*/
|
|
|
|
findPage: function (options) {
|
|
|
|
options = options || {};
|
|
|
|
|
|
|
|
var userCollection = Users.forge(),
|
2014-08-14 01:58:12 +04:00
|
|
|
roleInstance = options.role !== undefined ? ghostBookshelf.model('Role').forge({name: options.role}) : false;
|
2014-07-20 20:42:03 +04:00
|
|
|
|
|
|
|
if (options.limit && options.limit !== 'all') {
|
2014-08-01 09:53:09 +04:00
|
|
|
options.limit = parseInt(options.limit, 10) || 15;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.page) {
|
|
|
|
options.page = parseInt(options.page, 10) || 1;
|
2014-07-20 20:42:03 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
options = this.filterOptions(options, 'findPage');
|
|
|
|
|
|
|
|
// Set default settings for options
|
|
|
|
options = _.extend({
|
|
|
|
page: 1, // pagination page
|
|
|
|
limit: 15,
|
|
|
|
status: 'active',
|
2014-07-29 15:30:18 +04:00
|
|
|
where: {},
|
|
|
|
whereIn: {}
|
2014-07-20 20:42:03 +04:00
|
|
|
}, options);
|
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
// TODO: there are multiple statuses that make a user "active" or "invited" - we a way to translate/map them:
|
|
|
|
// TODO (cont'd from above): * valid "active" statuses: active, warn-1, warn-2, warn-3, warn-4, locked
|
|
|
|
// TODO (cont'd from above): * valid "invited" statuses" invited, invited-pending
|
2014-07-20 20:42:03 +04:00
|
|
|
|
2014-07-23 10:13:20 +04:00
|
|
|
// Filter on the status. A status of 'all' translates to no filter since we want all statuses
|
|
|
|
if (options.status && options.status !== 'all') {
|
2014-07-20 20:42:03 +04:00
|
|
|
// make sure that status is valid
|
2014-09-10 08:06:24 +04:00
|
|
|
// TODO: need a better way of getting a list of statuses other than hard-coding them...
|
2014-07-24 13:46:05 +04:00
|
|
|
options.status = _.indexOf(
|
2014-07-29 15:30:18 +04:00
|
|
|
['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked', 'invited', 'inactive'],
|
2014-07-24 13:46:05 +04:00
|
|
|
options.status) !== -1 ? options.status : 'active';
|
2014-07-29 15:30:18 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (options.status === 'active') {
|
2014-08-05 22:11:17 +04:00
|
|
|
userCollection.query().whereIn('status', activeStates);
|
2014-07-29 15:30:18 +04:00
|
|
|
} else if (options.status === 'invited') {
|
2014-08-05 22:11:17 +04:00
|
|
|
userCollection.query().whereIn('status', invitedStates);
|
2014-07-29 15:30:18 +04:00
|
|
|
} else if (options.status !== 'all') {
|
2014-07-20 20:42:03 +04:00
|
|
|
options.where.status = options.status;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there are where conditionals specified, add those
|
|
|
|
// to the query.
|
|
|
|
if (options.where) {
|
|
|
|
userCollection.query('where', options.where);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add related objects
|
2014-09-10 08:06:24 +04:00
|
|
|
options.withRelated = _.union(['roles'], options.include);
|
2014-07-20 20:42:03 +04:00
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
// only include a limit-query if a numeric limit is provided
|
2014-07-20 20:42:03 +04:00
|
|
|
if (_.isNumber(options.limit)) {
|
|
|
|
userCollection
|
|
|
|
.query('limit', options.limit)
|
|
|
|
.query('offset', options.limit * (options.page - 1));
|
|
|
|
}
|
|
|
|
|
2014-07-30 18:02:25 +04:00
|
|
|
function fetchRoleQuery() {
|
|
|
|
if (roleInstance) {
|
|
|
|
return roleInstance.fetch();
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.resolve(fetchRoleQuery())
|
2014-07-30 18:02:25 +04:00
|
|
|
.then(function () {
|
|
|
|
if (roleInstance) {
|
|
|
|
userCollection
|
|
|
|
.query('join', 'roles_users', 'roles_users.user_id', '=', 'users.id')
|
|
|
|
.query('where', 'roles_users.role_id', '=', roleInstance.id);
|
|
|
|
}
|
2014-07-20 20:42:03 +04:00
|
|
|
|
2014-07-30 18:02:25 +04:00
|
|
|
return userCollection
|
|
|
|
.query('orderBy', 'last_login', 'DESC')
|
|
|
|
.query('orderBy', 'name', 'ASC')
|
|
|
|
.query('orderBy', 'created_at', 'DESC')
|
|
|
|
.fetch(_.omit(options, 'page', 'limit'));
|
|
|
|
})
|
2014-07-20 20:42:03 +04:00
|
|
|
|
|
|
|
// Fetch pagination information
|
|
|
|
.then(function () {
|
|
|
|
var qb,
|
|
|
|
tableName = _.result(userCollection, 'tableName'),
|
|
|
|
idAttribute = _.result(userCollection, 'idAttribute');
|
|
|
|
|
|
|
|
// After we're done, we need to figure out what
|
|
|
|
// the limits are for the pagination values.
|
|
|
|
qb = ghostBookshelf.knex(tableName);
|
|
|
|
|
|
|
|
if (options.where) {
|
|
|
|
qb.where(options.where);
|
|
|
|
}
|
|
|
|
|
2014-07-30 18:02:25 +04:00
|
|
|
if (roleInstance) {
|
|
|
|
qb.join('roles_users', 'roles_users.user_id', '=', 'users.id');
|
|
|
|
qb.where('roles_users.role_id', '=', roleInstance.id);
|
|
|
|
}
|
|
|
|
|
2014-07-20 20:42:03 +04:00
|
|
|
return qb.count(tableName + '.' + idAttribute + ' as aggregate');
|
|
|
|
})
|
|
|
|
|
|
|
|
// Format response of data
|
|
|
|
.then(function (resp) {
|
|
|
|
var totalUsers = parseInt(resp[0].aggregate, 10),
|
|
|
|
calcPages = Math.ceil(totalUsers / options.limit),
|
|
|
|
pagination = {},
|
|
|
|
meta = {},
|
|
|
|
data = {};
|
|
|
|
|
2014-08-01 09:53:09 +04:00
|
|
|
pagination.page = options.page;
|
2014-07-20 20:42:03 +04:00
|
|
|
pagination.limit = options.limit;
|
|
|
|
pagination.pages = calcPages === 0 ? 1 : calcPages;
|
|
|
|
pagination.total = totalUsers;
|
|
|
|
pagination.next = null;
|
|
|
|
pagination.prev = null;
|
|
|
|
|
|
|
|
// Pass include to each model so that toJSON works correctly
|
|
|
|
if (options.include) {
|
|
|
|
_.each(userCollection.models, function (item) {
|
|
|
|
item.include = options.include;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
data.users = userCollection.toJSON();
|
|
|
|
data.meta = meta;
|
|
|
|
meta.pagination = pagination;
|
|
|
|
|
|
|
|
if (pagination.pages > 1) {
|
|
|
|
if (pagination.page === 1) {
|
|
|
|
pagination.next = pagination.page + 1;
|
|
|
|
} else if (pagination.page === pagination.pages) {
|
|
|
|
pagination.prev = pagination.page - 1;
|
|
|
|
} else {
|
|
|
|
pagination.next = pagination.page + 1;
|
|
|
|
pagination.prev = pagination.page - 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-30 18:02:25 +04:00
|
|
|
if (roleInstance) {
|
|
|
|
meta.filters = {};
|
|
|
|
if (!roleInstance.isNew()) {
|
|
|
|
meta.filters.roles = [roleInstance.toJSON()];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-20 20:42:03 +04:00
|
|
|
return data;
|
|
|
|
})
|
|
|
|
.catch(errors.logAndThrowError);
|
|
|
|
},
|
|
|
|
|
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)
|
|
|
|
*/
|
|
|
|
findOne: function (data, options) {
|
2014-08-05 22:11:17 +04:00
|
|
|
var query,
|
|
|
|
status;
|
|
|
|
|
|
|
|
data = _.extend({
|
|
|
|
status: 'active'
|
|
|
|
}, data || {});
|
|
|
|
|
|
|
|
status = data.status;
|
|
|
|
delete data.status;
|
|
|
|
|
2014-07-08 20:00:59 +04:00
|
|
|
options = options || {};
|
2014-09-10 08:06:24 +04:00
|
|
|
options.withRelated = _.union(['roles'], options.include);
|
2014-07-08 20:00:59 +04:00
|
|
|
|
2014-07-15 15:03:12 +04:00
|
|
|
// Support finding by role
|
|
|
|
if (data.role) {
|
|
|
|
options.withRelated = [{
|
2014-09-10 08:06:24 +04:00
|
|
|
roles: function (qb) {
|
2014-07-15 15:03:12 +04:00
|
|
|
qb.where('name', data.role);
|
|
|
|
}
|
|
|
|
}];
|
|
|
|
delete data.role;
|
|
|
|
}
|
|
|
|
|
2014-08-05 22:11:17 +04:00
|
|
|
// We pass include to forge so that toJSON has access
|
|
|
|
query = this.forge(data, {include: options.include});
|
|
|
|
|
|
|
|
data = this.filterData(data);
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
|
|
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)
|
|
|
|
*/
|
|
|
|
edit: function (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-07-08 20:00:59 +04:00
|
|
|
options = options || {};
|
2014-09-10 08:06:24 +04:00
|
|
|
options.withRelated = _.union(['roles'], options.include);
|
2014-07-08 20:00:59 +04:00
|
|
|
|
2014-07-22 00:50:43 +04:00
|
|
|
return ghostBookshelf.Model.edit.call(this, data, options).then(function (user) {
|
|
|
|
if (data.roles) {
|
2014-07-24 12:17:10 +04:00
|
|
|
roleId = parseInt(data.roles[0].id || data.roles[0], 10);
|
2014-07-22 00:50:43 +04:00
|
|
|
|
|
|
|
if (data.roles.length > 1) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(
|
2014-07-24 13:46:05 +04:00
|
|
|
new errors.ValidationError('Only one role per user is supported at the moment.')
|
|
|
|
);
|
2014-07-22 00:50:43 +04:00
|
|
|
}
|
2014-07-24 12:17:10 +04:00
|
|
|
|
|
|
|
return user.roles().fetch().then(function (roles) {
|
|
|
|
// return if the role is already assigned
|
|
|
|
if (roles.models[0].id === roleId) {
|
2014-08-11 13:51:14 +04:00
|
|
|
return;
|
2014-07-24 12:17:10 +04:00
|
|
|
}
|
2014-08-14 01:58:12 +04:00
|
|
|
return ghostBookshelf.model('Role').findOne({id: roleId});
|
2014-07-24 13:46:05 +04:00
|
|
|
}).then(function (roleToAssign) {
|
|
|
|
if (roleToAssign && roleToAssign.get('name') === 'Owner') {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(
|
2014-07-30 19:40:30 +04:00
|
|
|
new errors.ValidationError('This method does not support assigning the owner role')
|
|
|
|
);
|
2014-07-22 00:50:43 +04:00
|
|
|
} else {
|
|
|
|
// assign all other roles
|
2014-07-24 12:17:10 +04:00
|
|
|
return user.roles().updatePivot({role_id: roleId});
|
2014-07-22 00:50:43 +04:00
|
|
|
}
|
|
|
|
}).then(function () {
|
2014-08-05 22:11:17 +04:00
|
|
|
options.status = 'all';
|
|
|
|
return self.findOne({id: user.id}, options);
|
2014-07-22 00:50:43 +04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
return user;
|
|
|
|
});
|
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
|
|
|
*/
|
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: function (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
|
|
|
|
|
|
|
options = this.filterOptions(options, 'add');
|
2014-09-10 08:06:24 +04:00
|
|
|
options.withRelated = _.union(['roles'], options.include);
|
2014-07-31 23:53:55 +04:00
|
|
|
|
2014-08-14 01:58:12 +04:00
|
|
|
return ghostBookshelf.model('Role').findOne({name: 'Author'}, _.pick(options, 'transacting')).then(function (authorRole) {
|
2014-07-30 19:40:30 +04:00
|
|
|
// Get the role we're going to assign to this user, or the author role if there isn't one
|
2014-07-31 04:15:34 +04:00
|
|
|
roles = data.roles || [authorRole.get('id')];
|
|
|
|
|
2014-07-30 19:40:30 +04:00
|
|
|
// check for too many roles
|
|
|
|
if (roles.length > 1) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.ValidationError('Only one role per user is supported at the moment.'));
|
2014-07-30 19:40:30 +04:00
|
|
|
}
|
|
|
|
// remove roles from the object
|
|
|
|
delete data.roles;
|
2014-05-06 05:45:08 +04:00
|
|
|
|
2014-07-30 19:40:30 +04:00
|
|
|
return validatePasswordLength(userData.password);
|
|
|
|
}).then(function () {
|
2014-07-31 23:53:55 +04:00
|
|
|
return self.forge().fetch(options);
|
2013-08-20 22:52:44 +04:00
|
|
|
}).then(function () {
|
2013-11-22 07:17:38 +04:00
|
|
|
// Generate a new password hash
|
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
|
|
|
return generatePasswordHash(data.password);
|
2013-08-16 03:22:08 +04:00
|
|
|
}).then(function (hash) {
|
|
|
|
// Assign the hashed password
|
|
|
|
userData.password = hash;
|
2013-11-11 23:55:22 +04:00
|
|
|
// LookupGravatar
|
|
|
|
return self.gravatarLookup(userData);
|
|
|
|
}).then(function (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);
|
2013-08-16 03:22:08 +04:00
|
|
|
}).then(function (addedUser) {
|
|
|
|
// 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
|
2014-07-29 07:00:45 +04:00
|
|
|
roles = _.map(roles, function (role) {
|
2014-07-31 04:15:34 +04:00
|
|
|
if (_.isString(role)) {
|
|
|
|
return parseInt(role, 10);
|
|
|
|
} else if (_.isNumber(role)) {
|
2014-07-29 07:00:45 +04:00
|
|
|
return role;
|
|
|
|
} else {
|
|
|
|
return parseInt(role.id, 10);
|
|
|
|
}
|
|
|
|
});
|
2014-07-24 13:46:05 +04:00
|
|
|
|
2014-07-31 23:53:55 +04:00
|
|
|
return userData.roles().attach(roles, options);
|
2014-07-24 13:46:05 +04:00
|
|
|
}).then(function () {
|
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
|
|
|
},
|
|
|
|
|
2014-07-10 21:29:51 +04:00
|
|
|
setup: function (data, options) {
|
|
|
|
var self = this,
|
|
|
|
userData = this.filterData(data);
|
2014-07-11 16:17:09 +04:00
|
|
|
|
2014-07-10 21:29:51 +04:00
|
|
|
options = this.filterOptions(options, 'setup');
|
2014-09-10 08:06:24 +04:00
|
|
|
options.withRelated = _.union(['roles'], options.include);
|
2014-07-11 16:17:09 +04:00
|
|
|
|
2014-07-10 21:29:51 +04:00
|
|
|
return validatePasswordLength(userData.password).then(function () {
|
|
|
|
// Generate a new password hash
|
|
|
|
return generatePasswordHash(data.password);
|
|
|
|
}).then(function (hash) {
|
|
|
|
// Assign the hashed password
|
|
|
|
userData.password = hash;
|
|
|
|
// LookupGravatar
|
|
|
|
return self.gravatarLookup(userData);
|
|
|
|
}).then(function (userWithGravatar) {
|
|
|
|
userData = userWithGravatar;
|
|
|
|
// Generate a new slug
|
|
|
|
return ghostBookshelf.Model.generateSlug.call(this, User, userData.name, options);
|
|
|
|
}).then(function (slug) {
|
|
|
|
// Assign slug and save the updated user
|
|
|
|
userData.slug = slug;
|
|
|
|
return self.edit.call(self, userData, options);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2014-07-23 22:17:29 +04:00
|
|
|
permissible: function (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-07-24 13:46:05 +04:00
|
|
|
// If we passed in an id instead of a model, get the model then check the permissions
|
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);
|
|
|
|
// Get the actual post model
|
2014-08-06 20:48:18 +04:00
|
|
|
return this.findOne({id: userModelOrId, status: 'all'}).then(function (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') {
|
|
|
|
// 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
|
2014-09-10 08:06:24 +04:00
|
|
|
if (_.any(loadedPermissions.user.roles, {name: 'Author'})) {
|
2014-07-24 13:46:05 +04:00
|
|
|
// If this is the same user that requests the operation allow it.
|
|
|
|
hasUserPermission = hasUserPermission || context.user === userModel.get('id');
|
|
|
|
}
|
|
|
|
|
2014-09-10 08:06:24 +04:00
|
|
|
if (_.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
|
|
|
|
if (userModel.hasRole('Owner')) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject();
|
2014-07-24 13:46:05 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Users with the role 'Editor' have complex permissions when the action === 'destroy'
|
2014-09-10 08:06:24 +04:00
|
|
|
if (_.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');
|
|
|
|
}
|
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
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject();
|
2014-04-08 17:40:33 +04:00
|
|
|
},
|
|
|
|
|
2014-08-07 21:50:23 +04:00
|
|
|
setWarning: function (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;
|
|
|
|
if (level > 3) {
|
|
|
|
user.set('status', 'locked');
|
|
|
|
} else {
|
|
|
|
user.set('status', 'warn-' + level);
|
|
|
|
}
|
|
|
|
}
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.resolve(user.save(options)).then(function () {
|
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
|
2014-06-30 16:58:10 +04:00
|
|
|
check: function (object) {
|
2013-11-29 04:28:01 +04:00
|
|
|
var self = this,
|
|
|
|
s;
|
2014-06-30 16:58:10 +04:00
|
|
|
return this.getByEmail(object.email).then(function (user) {
|
2014-07-24 19:34:52 +04:00
|
|
|
if (!user) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.NotFoundError('There is no user with that email address.'));
|
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'
|
|
|
|
) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('The user with that email address is inactive.'));
|
2014-07-02 18:22:18 +04:00
|
|
|
}
|
2013-11-29 04:28:01 +04:00
|
|
|
if (user.get('status') !== 'locked') {
|
2014-08-17 10:17:23 +04:00
|
|
|
return bcryptCompare(object.password, user.get('password')).then(function (matched) {
|
2013-11-29 04:28:01 +04:00
|
|
|
if (!matched) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.resolve(self.setWarning(user, {validate: false})).then(function (remaining) {
|
2013-11-29 04:28:01 +04:00
|
|
|
s = (remaining > 1) ? 's' : '';
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.UnauthorizedError('Your password is incorrect.<br>' +
|
2013-11-29 04:28:01 +04:00
|
|
|
remaining + ' attempt' + s + ' remaining!'));
|
2014-08-07 21:50:23 +04:00
|
|
|
|
|
|
|
// Use comma structure, not .catch, because we don't want to catch incorrect passwords
|
|
|
|
}, function (error) {
|
|
|
|
// 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,
|
|
|
|
'Error thrown from user update during login',
|
|
|
|
'Visit and save your profile after logging in to check for problems.'
|
|
|
|
);
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.UnauthorizedError('Your password is incorrect.'));
|
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}))
|
2014-08-07 21:50:23 +04:00
|
|
|
.catch(function (error) {
|
|
|
|
// 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,
|
|
|
|
'Error thrown from user update during login',
|
|
|
|
'Visit and save your profile after logging in to check for problems.'
|
|
|
|
);
|
|
|
|
return user;
|
|
|
|
});
|
2013-11-29 04:28:01 +04:00
|
|
|
}, errors.logAndThrowError);
|
|
|
|
}
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.NoPermissionError('Your account is locked due to too many ' +
|
2013-11-29 04:28:01 +04:00
|
|
|
'login attempts. Please reset your password to log in again by clicking ' +
|
|
|
|
'the "Forgotten password?" link!'));
|
2013-08-09 05:22:49 +04:00
|
|
|
}, function (error) {
|
2014-01-15 02:47:17 +04:00
|
|
|
if (error.message === 'NotFound' || error.message === 'EmptyResponse') {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.NotFoundError('There is no user with that email address.'));
|
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
|
2014-09-10 08:06:24 +04:00
|
|
|
* @param {String} oldPassword
|
|
|
|
* @param {String} newPassword
|
|
|
|
* @param {String} ne2Password
|
|
|
|
* @param {Object} options
|
2013-08-06 03:49:06 +04:00
|
|
|
*/
|
2014-06-20 13:15:01 +04:00
|
|
|
changePassword: function (oldPassword, newPassword, ne2Password, options) {
|
2013-08-20 22:52:44 +04:00
|
|
|
var self = this,
|
2014-06-20 13:15:01 +04:00
|
|
|
userid = options.context.user,
|
2013-09-01 02:20:12 +04:00
|
|
|
user = null;
|
|
|
|
|
2013-08-06 03:49:06 +04:00
|
|
|
if (newPassword !== ne2Password) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Your new passwords do not match'));
|
2013-08-06 03:49:06 +04:00
|
|
|
}
|
|
|
|
|
2013-08-20 22:52:44 +04:00
|
|
|
return validatePasswordLength(newPassword).then(function () {
|
|
|
|
return self.forge({id: userid}).fetch({require: true});
|
2013-09-01 02:20:12 +04:00
|
|
|
}).then(function (_user) {
|
|
|
|
user = _user;
|
2014-08-17 10:17:23 +04:00
|
|
|
return bcryptCompare(oldPassword, user.get('password'));
|
2013-09-01 02:20:12 +04:00
|
|
|
}).then(function (matched) {
|
|
|
|
if (!matched) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Your password is incorrect'));
|
2013-09-01 02:20:12 +04:00
|
|
|
}
|
2014-08-17 10:17:23 +04:00
|
|
|
return bcryptGenSalt();
|
2013-10-23 17:00:28 +04:00
|
|
|
}).then(function (salt) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return bcryptHash(newPassword, salt);
|
2013-09-01 02:20:12 +04:00
|
|
|
}).then(function (hash) {
|
|
|
|
user.save({password: hash});
|
|
|
|
return user;
|
2013-08-06 03:49:06 +04:00
|
|
|
});
|
2013-09-01 02:20:12 +04:00
|
|
|
},
|
|
|
|
|
2013-11-22 07:17:38 +04:00
|
|
|
generateResetToken: function (email, expires, dbHash) {
|
2014-01-15 02:47:17 +04:00
|
|
|
return this.getByEmail(email).then(function (foundUser) {
|
2014-07-02 18:22:18 +04:00
|
|
|
if (!foundUser) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.NotFoundError('There is no user with that email address.'));
|
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:
|
|
|
|
// BASE64(TIMESTAMP + email + HASH(TIMESTAMP + email + oldPasswordHash + dbHash ))
|
|
|
|
|
|
|
|
hash.update(String(expires));
|
|
|
|
hash.update(email.toLocaleLowerCase());
|
|
|
|
hash.update(foundUser.get('password'));
|
|
|
|
hash.update(String(dbHash));
|
|
|
|
|
|
|
|
text += [expires, email, hash.digest('base64')].join('|');
|
|
|
|
|
|
|
|
return new Buffer(text).toString('base64');
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
validateToken: function (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) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Invalid token structure'));
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
expires = parseInt(parts[0], 10);
|
|
|
|
email = parts[1];
|
|
|
|
|
|
|
|
if (isNaN(expires)) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Invalid token expiration'));
|
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()) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Expired token'));
|
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) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Token locked'));
|
2014-01-30 16:27:29 +04:00
|
|
|
}
|
|
|
|
|
2013-11-22 07:17:38 +04:00
|
|
|
return this.generateResetToken(email, expires, dbHash).then(function (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
|
|
|
|
};
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Invalid token'));
|
2013-11-22 07:17:38 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
resetPassword: function (token, newPassword, ne2Password, dbHash) {
|
|
|
|
var self = this;
|
|
|
|
|
|
|
|
if (newPassword !== ne2Password) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new Error('Your new passwords do not match'));
|
2013-11-22 07:17:38 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
return validatePasswordLength(newPassword).then(function () {
|
|
|
|
// Validate the token; returns the email address from token
|
|
|
|
return self.validateToken(token, dbHash);
|
|
|
|
}).then(function (email) {
|
|
|
|
// Fetch the user by email, and hash the password at the same time.
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.join(
|
2013-11-22 07:17:38 +04:00
|
|
|
self.forge({email: email.toLocaleLowerCase()}).fetch({require: true}),
|
|
|
|
generatePasswordHash(newPassword)
|
|
|
|
);
|
|
|
|
}).then(function (results) {
|
|
|
|
// 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
|
|
|
},
|
|
|
|
|
2014-07-30 19:40:30 +04:00
|
|
|
transferOwnership: function (object, options) {
|
|
|
|
var adminRole,
|
|
|
|
ownerRole,
|
|
|
|
contextUser,
|
|
|
|
assignUser;
|
|
|
|
|
2014-07-24 13:46:05 +04:00
|
|
|
// Get admin role
|
2014-08-14 01:58:12 +04:00
|
|
|
return ghostBookshelf.model('Role').findOne({name: 'Administrator'}).then(function (result) {
|
2014-07-24 13:46:05 +04:00
|
|
|
adminRole = result;
|
2014-08-14 01:58:12 +04:00
|
|
|
return ghostBookshelf.model('Role').findOne({name: 'Owner'});
|
2014-07-30 19:40:30 +04:00
|
|
|
}).then(function (result) {
|
|
|
|
ownerRole = result;
|
|
|
|
return User.findOne({id: options.context.user});
|
|
|
|
}).then(function (ctxUser) {
|
2014-07-24 13:46:05 +04:00
|
|
|
// check if user has the owner role
|
2014-07-30 19:40:30 +04:00
|
|
|
var currentRoles = ctxUser.toJSON().roles;
|
2014-07-24 13:46:05 +04:00
|
|
|
if (!_.contains(currentRoles, ownerRole.id)) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.NoPermissionError('Only owners are able to transfer the owner role.'));
|
2014-07-24 13:46:05 +04:00
|
|
|
}
|
2014-07-30 19:40:30 +04:00
|
|
|
contextUser = ctxUser;
|
|
|
|
return User.findOne({id: object.id});
|
|
|
|
}).then(function (user) {
|
|
|
|
var currentRoles = user.toJSON().roles;
|
|
|
|
if (!_.contains(currentRoles, adminRole.id)) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.ValidationError('Only administrators can be assigned the owner role.'));
|
2014-07-30 19:40:30 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
assignUser = user;
|
2014-07-24 13:46:05 +04:00
|
|
|
// convert owner to admin
|
|
|
|
return contextUser.roles().updatePivot({role_id: adminRole.id});
|
|
|
|
}).then(function () {
|
|
|
|
// assign owner role to a new user
|
2014-07-30 19:40:30 +04:00
|
|
|
return assignUser.roles().updatePivot({role_id: ownerRole.id});
|
2014-07-31 17:41:10 +04:00
|
|
|
}).then(function () {
|
|
|
|
return Users.forge()
|
|
|
|
.query('whereIn', 'id', [contextUser.id, assignUser.id])
|
2014-09-10 08:06:24 +04:00
|
|
|
.fetch({withRelated: ['roles']});
|
2014-07-31 17:41:10 +04:00
|
|
|
}).then(function (users) {
|
2014-09-10 08:06:24 +04:00
|
|
|
return users.toJSON({include: ['roles']});
|
2014-07-24 13:46:05 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2013-11-11 23:55:22 +04:00
|
|
|
gravatarLookup: function (userData) {
|
2013-12-17 20:21:00 +04:00
|
|
|
var gravatarUrl = '//www.gravatar.com/avatar/' +
|
2014-07-02 18:22:18 +04:00
|
|
|
crypto.createHash('md5').update(userData.email.toLowerCase().trim()).digest('hex') +
|
2014-08-17 10:17:23 +04:00
|
|
|
'?d=404&s=250';
|
2013-11-11 23:55:22 +04:00
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
return new Promise(function (resolve) {
|
2014-09-03 08:27:37 +04:00
|
|
|
if (config.isPrivacyDisabled('useGravatar')) {
|
|
|
|
resolve(userData);
|
|
|
|
}
|
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
http.get('http:' + gravatarUrl, function (res) {
|
|
|
|
if (res.statusCode !== 404) {
|
|
|
|
userData.image = gravatarUrl;
|
|
|
|
}
|
2013-11-11 23:55:22 +04:00
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
resolve(userData);
|
|
|
|
}).on('error', function () {
|
2014-09-10 08:06:24 +04:00
|
|
|
// Error making request just continue.
|
2014-08-17 10:17:23 +04:00
|
|
|
resolve(userData);
|
|
|
|
});
|
|
|
|
});
|
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.
|
2014-07-31 04:15:34 +04:00
|
|
|
getByEmail: function (email, options) {
|
|
|
|
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;
|
|
|
|
|
|
|
|
return Users.forge(options).fetch(options).then(function (users) {
|
2014-01-15 02:47:17 +04:00
|
|
|
var userWithEmail = users.find(function (user) {
|
|
|
|
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
|
|
|
};
|