freeCodeCamp/common/models/user.js

345 lines
8.3 KiB
JavaScript
Raw Normal View History

2015-07-29 22:00:24 +00:00
import { Observable } from 'rx';
import uuid from 'node-uuid';
2015-07-29 22:00:24 +00:00
import moment from 'moment';
import debugFactory from 'debug';
import { saveUser, observeMethod } from '../../server/utils/rx';
import { blacklistedUsernames } from '../../server/utils/constants';
const debug = debugFactory('freecc:user:remote');
const BROWNIEPOINTS_TIMEOUT = [30, 'seconds'];
2015-07-29 22:00:24 +00:00
function getAboutProfile({
username,
githubProfile: github,
2015-07-31 19:15:23 +00:00
progressTimestamps = [],
bio
2015-07-29 22:00:24 +00:00
}) {
return {
username,
github,
2015-07-31 19:15:23 +00:00
browniePoints: progressTimestamps.length,
bio
2015-07-29 22:00:24 +00:00
};
}
function nextTick(fn) {
return process.nextTick(fn);
}
2015-06-11 23:11:07 +00:00
module.exports = function(User) {
// NOTE(berks): user email validation currently not needed but build in. This
// work around should let us sneak by
// see:
// https://github.com/strongloop/loopback/issues/1137#issuecomment-109200135
delete User.validations.email;
2015-06-12 18:38:00 +00:00
// set salt factor for passwords
User.settings.saltWorkFactor = 5;
// username should not be in blacklist
User.validatesExclusionOf('username', {
'in': blacklistedUsernames,
message: 'is taken'
});
// username should be unique
User.validatesUniquenessOf('username');
User.observe('before save', function({ instance: user }, next) {
if (user) {
user.username = user.username.trim().toLowerCase();
2015-08-06 05:56:23 +00:00
user.email = typeof user.email === 'string' ?
user.email.trim().toLowerCase() :
user.email;
if (!user.progressTimestamps) {
user.progressTimestamps = [];
}
if (user.progressTimestamps.length === 0) {
user.progressTimestamps.push({ timestamp: Date.now() });
}
}
next();
});
2015-06-11 23:11:07 +00:00
debug('setting up user hooks');
User.afterRemote('confirm', function(ctx) {
2015-06-12 01:03:01 +00:00
ctx.req.flash('success', {
msg: [
'You\'re email has been confirmed!'
]
});
ctx.res.redirect('/email-signin');
});
User.beforeRemote('create', function({ req }, notUsed, next) {
req.body.username = 'fcc' + uuid.v4().slice(0, 8);
next();
});
User.afterRemote('login', function(ctx, user, next) {
2015-06-11 23:11:07 +00:00
var res = ctx.res;
var req = ctx.req;
// var args = ctx.args;
2015-06-11 23:11:07 +00:00
var accessToken = {};
var config = {
signed: !!req.signedCookies,
maxAge: accessToken.ttl
};
if (accessToken && accessToken.id) {
res.cookie('access_token', accessToken.id, config);
res.cookie('userId', accessToken.userId, config);
}
2015-06-16 04:27:32 +00:00
debug('before pass login');
return req.logIn(user, function(err) {
if (err) {
return next(err);
}
req.flash('success', { msg: 'Success! You are logged in.' });
return res.redirect('/');
});
2015-06-11 23:11:07 +00:00
});
2015-06-16 04:29:32 +00:00
User.afterRemoteError('login', function(ctx) {
2015-06-16 04:27:32 +00:00
var res = ctx.res;
var req = ctx.req;
req.flash('errors', {
msg: 'Invalid username or password.'
});
return res.redirect('/');
});
2015-06-11 23:11:07 +00:00
User.afterRemote('logout', function(ctx, result, next) {
var res = ctx.result;
res.clearCookie('access_token');
res.clearCookie('userId');
next();
});
User.doesExist = function doesExist(username, email, cb) {
if (!username && !email) {
2015-07-29 22:00:24 +00:00
return nextTick(function() {
2015-06-11 23:11:07 +00:00
cb(null, false);
});
}
debug('checking existence');
2015-06-11 23:46:31 +00:00
// check to see if username is on blacklist
if (username && blacklistedUsernames.indexOf(username) !== -1) {
return cb(null, true);
}
2015-06-11 23:11:07 +00:00
var where = {};
if (username) {
where.username = username.toLowerCase();
} else {
where.email = email ? email.toLowerCase() : email;
}
debug('where', where);
User.count(
where,
2015-07-29 18:32:16 +00:00
function(err, count) {
2015-06-11 23:11:07 +00:00
if (err) {
debug('err checking existance: ', err);
return cb(err);
}
if (count > 0) {
return cb(null, true);
}
return cb(null, false);
}
);
};
User.remoteMethod(
'doesExist',
{
description: 'checks whether a user exists using email or username',
accepts: [
{
arg: 'username',
type: 'string'
},
{
arg: 'email',
type: 'string'
}
],
returns: [
{
arg: 'exists',
type: 'boolean'
}
],
http: {
path: '/exists',
verb: 'get'
}
}
);
2015-07-29 18:32:16 +00:00
User.about = function about(username, cb) {
if (!username) {
// Zalgo!!
2015-07-29 22:00:24 +00:00
return nextTick(() => {
2015-08-04 17:52:41 +00:00
cb(new TypeError(
`username should be a string but got ${ username }`
));
2015-07-29 18:32:16 +00:00
});
}
User.findOne({ where: { username } }, (err, user) => {
if (err) {
2015-07-29 18:41:41 +00:00
return cb(err);
2015-07-29 18:32:16 +00:00
}
if (!user || user.username !== username) {
2015-08-04 17:52:41 +00:00
return cb(new Error(`no user found for ${ username }`));
2015-07-29 18:32:16 +00:00
}
2015-07-29 22:00:24 +00:00
const aboutUser = getAboutProfile(user);
2015-07-29 18:41:41 +00:00
return cb(null, aboutUser);
2015-07-29 18:32:16 +00:00
});
};
User.remoteMethod(
'about',
{
description: 'get public info about user',
accepts: [
{
arg: 'username',
type: 'string'
}
],
returns: [
{
arg: 'about',
type: 'object'
}
],
http: {
path: '/about',
verb: 'get'
}
}
);
2015-07-29 22:00:24 +00:00
User.giveBrowniePoints =
function giveBrowniePoints(receiver, giver, data = {}, dev = false, cb) {
2015-07-29 22:00:24 +00:00
const findUser = observeMethod(User, 'findOne');
if (!receiver) {
return nextTick(() => {
2015-07-31 20:45:21 +00:00
cb(
new TypeError(`receiver should be a string but got ${ receiver }`)
);
2015-07-29 22:00:24 +00:00
});
}
if (!giver) {
return nextTick(() => {
2015-07-31 20:45:21 +00:00
cb(new TypeError(`giver should be a string but got ${ giver }`));
2015-07-29 22:00:24 +00:00
});
}
let temp = moment();
const browniePoints = temp
.subtract.apply(temp, BROWNIEPOINTS_TIMEOUT)
.valueOf();
2015-07-29 22:00:24 +00:00
const user$ = findUser({ where: { username: receiver }});
user$
.tapOnNext((user) => {
if (!user) {
2015-07-31 20:45:21 +00:00
throw new Error(`could not find receiver for ${ receiver }`);
2015-07-29 22:00:24 +00:00
}
})
.flatMap(({ progressTimestamps = [] }) => {
return Observable.from(progressTimestamps);
})
// filter out non objects
.filter((timestamp) => !!timestamp || typeof timestamp === 'object')
// filterout timestamps older then an hour
.filter(({ timestamp = 0 }) => {
return timestamp >= browniePoints;
2015-07-29 22:00:24 +00:00
})
// filter out brownie points given by giver
.filter((browniePoint) => {
return browniePoint.giver === giver;
})
// no results means this is the first brownie point given by giver
// so return -1 to indicate receiver should receive point
.firstOrDefault(null, -1)
.flatMap((browniePointsFromGiver) => {
if (browniePointsFromGiver === -1) {
return user$.flatMap((user) => {
user.progressTimestamps.push({
giver,
timestamp: Date.now(),
...data
});
return saveUser(user);
});
}
return Observable.throw(
2015-07-31 20:45:21 +00:00
new Error(`${ giver } already gave ${ receiver } points`)
2015-07-29 22:00:24 +00:00
);
})
.subscribe(
(user) => {
return cb(
null,
getAboutProfile(user),
dev ?
{ giver, receiver, data } :
null
);
2015-07-29 22:00:24 +00:00
},
(e) => cb(e, null, dev ? { giver, receiver, data } : null),
2015-07-29 22:00:24 +00:00
() => {
debug('brownie points assigned completed');
}
);
};
User.remoteMethod(
'giveBrowniePoints',
{
description: 'Give this user brownie points',
accepts: [
{
arg: 'receiver',
type: 'string',
required: true
},
{
arg: 'giver',
type: 'string',
required: true
},
{
arg: 'data',
type: 'object'
},
{
arg: 'debug',
type: 'boolean'
2015-07-29 22:00:24 +00:00
}
],
returns: [
{
arg: 'about',
type: 'object'
},
{
arg: 'debug',
type: 'object'
2015-07-29 22:00:24 +00:00
}
],
http: {
path: '/give-brownie-points',
verb: 'POST'
2015-07-29 22:00:24 +00:00
}
}
2015-07-31 19:15:23 +00:00
);
2015-06-11 23:11:07 +00:00
};