fix(update$): Remove User.update$, refactor to use native loopback interfaces
This commit is contained in:
committed by
mrugesh mohapatra
parent
97f7d53bee
commit
0f73fdbd9c
@ -45,10 +45,22 @@ module.exports = function(UserCredential) {
|
|||||||
return findCred(query)
|
return findCred(query)
|
||||||
.flatMap(_credentials => {
|
.flatMap(_credentials => {
|
||||||
const modified = new Date();
|
const modified = new Date();
|
||||||
const updateUser = User.update$(
|
const updateUser = new Promise((resolve, reject) => {
|
||||||
{ id: userId },
|
User.find({ id: userId }, (err, user) => {
|
||||||
createUserUpdatesFromProfile(provider, profile)
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return user.updateAttributes(
|
||||||
|
createUserUpdatesFromProfile(provider, profile),
|
||||||
|
updateErr => {
|
||||||
|
if (updateErr) {
|
||||||
|
return reject(updateErr);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
let updateCredentials;
|
let updateCredentials;
|
||||||
if (!_credentials) {
|
if (!_credentials) {
|
||||||
updateCredentials = createCred({
|
updateCredentials = createCred({
|
||||||
@ -65,25 +77,18 @@ module.exports = function(UserCredential) {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
_credentials.credentials = credentials;
|
_credentials.credentials = credentials;
|
||||||
updateCredentials = observeQuery(
|
updateCredentials = observeQuery(_credentials, 'updateAttributes', {
|
||||||
_credentials,
|
|
||||||
'updateAttributes',
|
|
||||||
{
|
|
||||||
profile: null,
|
profile: null,
|
||||||
credentials,
|
credentials,
|
||||||
modified
|
modified
|
||||||
}
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return Observable.combineLatest(
|
return Observable.combineLatest(
|
||||||
updateUser,
|
Observable.fromPromise(updateUser),
|
||||||
updateCredentials,
|
updateCredentials,
|
||||||
(_, credentials) => credentials
|
(_, credentials) => credentials
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
.subscribe(
|
.subscribe(credentials => cb(null, credentials), cb);
|
||||||
credentials => cb(null, credentials),
|
|
||||||
cb
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -126,16 +126,26 @@ export default function(UserIdent) {
|
|||||||
created: new Date(),
|
created: new Date(),
|
||||||
ttl: user.constructor.settings.ttl
|
ttl: user.constructor.settings.ttl
|
||||||
});
|
});
|
||||||
const updateUser = user.update$({
|
const updateUser = new Promise((resolve, reject) =>
|
||||||
|
user.updateAttributes(
|
||||||
|
{
|
||||||
email: email,
|
email: email,
|
||||||
emailVerified: true,
|
emailVerified: true,
|
||||||
emailAuthLinkTTL: null,
|
emailAuthLinkTTL: null,
|
||||||
emailVerifyTTL: null
|
emailVerifyTTL: null
|
||||||
});
|
},
|
||||||
|
err => {
|
||||||
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
return Observable.combineLatest(
|
return Observable.combineLatest(
|
||||||
Observable.of(user),
|
Observable.of(user),
|
||||||
createToken,
|
createToken,
|
||||||
updateUser,
|
Observable.fromPromise(updateUser),
|
||||||
(user, token) => ({ user, token })
|
(user, token) => ({ user, token })
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
|
@ -20,13 +20,10 @@ import generate from 'nanoid/generate';
|
|||||||
import { homeLocation, apiLocation } from '../../../config/env';
|
import { homeLocation, apiLocation } from '../../../config/env';
|
||||||
|
|
||||||
import { fixCompletedChallengeItem } from '../utils';
|
import { fixCompletedChallengeItem } from '../utils';
|
||||||
import { themes } from '../utils/themes';
|
|
||||||
import { saveUser, observeMethod } from '../../server/utils/rx.js';
|
import { saveUser, observeMethod } from '../../server/utils/rx.js';
|
||||||
import { blacklistedUsernames } from '../../server/utils/constants.js';
|
import { blacklistedUsernames } from '../../server/utils/constants.js';
|
||||||
import { wrapHandledError } from '../../server/utils/create-handled-error.js';
|
import { wrapHandledError } from '../../server/utils/create-handled-error.js';
|
||||||
import {
|
import { getEmailSender } from '../../server/utils/url-utils.js';
|
||||||
getEmailSender
|
|
||||||
} from '../../server/utils/url-utils.js';
|
|
||||||
import {
|
import {
|
||||||
normaliseUserFields,
|
normaliseUserFields,
|
||||||
getProgress,
|
getProgress,
|
||||||
@ -38,20 +35,15 @@ const BROWNIEPOINTS_TIMEOUT = [1, 'hour'];
|
|||||||
const nanoidCharSet =
|
const nanoidCharSet =
|
||||||
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||||
|
|
||||||
const createEmailError = redirectTo => wrapHandledError(
|
const createEmailError = redirectTo =>
|
||||||
new Error('email format is invalid'),
|
wrapHandledError(new Error('email format is invalid'), {
|
||||||
{
|
|
||||||
type: 'info',
|
type: 'info',
|
||||||
message: 'Please check to make sure the email is a valid email address.',
|
message: 'Please check to make sure the email is a valid email address.',
|
||||||
redirectTo
|
redirectTo
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
function destroyAll(id, Model) {
|
function destroyAll(id, Model) {
|
||||||
return Observable.fromNodeCallback(
|
return Observable.fromNodeCallback(Model.destroyAll, Model)({ userId: id });
|
||||||
Model.destroyAll,
|
|
||||||
Model
|
|
||||||
)({ userId: id });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildCompletedChallengesUpdate(completedChallenges, project) {
|
function buildCompletedChallengesUpdate(completedChallenges, project) {
|
||||||
@ -61,18 +53,16 @@ function buildCompletedChallengesUpdate(completedChallenges, project) {
|
|||||||
const currentCompletedChallenges = [
|
const currentCompletedChallenges = [
|
||||||
...completedChallenges.map(fixCompletedChallengeItem)
|
...completedChallenges.map(fixCompletedChallengeItem)
|
||||||
];
|
];
|
||||||
const currentCompletedProjects = currentCompletedChallenges
|
const currentCompletedProjects = currentCompletedChallenges.filter(({ id }) =>
|
||||||
.filter(({id}) => solutionKeys.includes(id));
|
solutionKeys.includes(id)
|
||||||
|
);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const update = solutionKeys.reduce((update, currentId) => {
|
const update = solutionKeys.reduce((update, currentId) => {
|
||||||
const indexOfCurrentId = _.findIndex(
|
const indexOfCurrentId = _.findIndex(update, ({ id }) => id === currentId);
|
||||||
update,
|
|
||||||
({id}) => id === currentId
|
|
||||||
);
|
|
||||||
const isCurrentlyCompleted = indexOfCurrentId !== -1;
|
const isCurrentlyCompleted = indexOfCurrentId !== -1;
|
||||||
if (isCurrentlyCompleted) {
|
if (isCurrentlyCompleted) {
|
||||||
update[indexOfCurrentId] = {
|
update[indexOfCurrentId] = {
|
||||||
..._.find(update, ({id}) => id === currentId),
|
..._.find(update, ({ id }) => id === currentId),
|
||||||
solution: solutions[currentId]
|
solution: solutions[currentId]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -90,16 +80,12 @@ function buildCompletedChallengesUpdate(completedChallenges, project) {
|
|||||||
return update;
|
return update;
|
||||||
}, currentCompletedProjects);
|
}, currentCompletedProjects);
|
||||||
const updatedExisting = _.uniqBy(
|
const updatedExisting = _.uniqBy(
|
||||||
[
|
[...update, ...currentCompletedChallenges],
|
||||||
...update,
|
|
||||||
...currentCompletedChallenges
|
|
||||||
],
|
|
||||||
'id'
|
'id'
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
updated: updatedExisting,
|
updated: updatedExisting,
|
||||||
isNewCompletionCount:
|
isNewCompletionCount: updatedExisting.length - completedChallenges.length
|
||||||
updatedExisting.length - completedChallenges.length
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -107,7 +93,8 @@ function isTheSame(val1, val2) {
|
|||||||
return val1 === val2;
|
return val1 === val2;
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderSignUpEmail = loopback.template(path.join(
|
const renderSignUpEmail = loopback.template(
|
||||||
|
path.join(
|
||||||
__dirname,
|
__dirname,
|
||||||
'..',
|
'..',
|
||||||
'..',
|
'..',
|
||||||
@ -115,9 +102,11 @@ const renderSignUpEmail = loopback.template(path.join(
|
|||||||
'views',
|
'views',
|
||||||
'emails',
|
'emails',
|
||||||
'user-request-sign-up.ejs'
|
'user-request-sign-up.ejs'
|
||||||
));
|
)
|
||||||
|
);
|
||||||
|
|
||||||
const renderSignInEmail = loopback.template(path.join(
|
const renderSignInEmail = loopback.template(
|
||||||
|
path.join(
|
||||||
__dirname,
|
__dirname,
|
||||||
'..',
|
'..',
|
||||||
'..',
|
'..',
|
||||||
@ -125,9 +114,11 @@ const renderSignInEmail = loopback.template(path.join(
|
|||||||
'views',
|
'views',
|
||||||
'emails',
|
'emails',
|
||||||
'user-request-sign-in.ejs'
|
'user-request-sign-in.ejs'
|
||||||
));
|
)
|
||||||
|
);
|
||||||
|
|
||||||
const renderEmailChangeEmail = loopback.template(path.join(
|
const renderEmailChangeEmail = loopback.template(
|
||||||
|
path.join(
|
||||||
__dirname,
|
__dirname,
|
||||||
'..',
|
'..',
|
||||||
'..',
|
'..',
|
||||||
@ -135,7 +126,8 @@ const renderEmailChangeEmail = loopback.template(path.join(
|
|||||||
'views',
|
'views',
|
||||||
'emails',
|
'emails',
|
||||||
'user-request-update-email.ejs'
|
'user-request-update-email.ejs'
|
||||||
));
|
)
|
||||||
|
);
|
||||||
|
|
||||||
function getAboutProfile({
|
function getAboutProfile({
|
||||||
username,
|
username,
|
||||||
@ -158,12 +150,12 @@ function nextTick(fn) {
|
|||||||
function getWaitPeriod(ttl) {
|
function getWaitPeriod(ttl) {
|
||||||
const fiveMinutesAgo = moment().subtract(5, 'minutes');
|
const fiveMinutesAgo = moment().subtract(5, 'minutes');
|
||||||
const lastEmailSentAt = moment(new Date(ttl || null));
|
const lastEmailSentAt = moment(new Date(ttl || null));
|
||||||
const isWaitPeriodOver = ttl ?
|
const isWaitPeriodOver = ttl
|
||||||
lastEmailSentAt.isBefore(fiveMinutesAgo) : true;
|
? lastEmailSentAt.isBefore(fiveMinutesAgo)
|
||||||
|
: true;
|
||||||
|
|
||||||
if (!isWaitPeriodOver) {
|
if (!isWaitPeriodOver) {
|
||||||
const minutesLeft = 5 -
|
const minutesLeft = 5 - (moment().minutes() - lastEmailSentAt.minutes());
|
||||||
(moment().minutes() - lastEmailSentAt.minutes());
|
|
||||||
return minutesLeft;
|
return minutesLeft;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -175,23 +167,22 @@ function getWaitMessage(ttl) {
|
|||||||
if (minutesLeft <= 0) {
|
if (minutesLeft <= 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const timeToWait = minutesLeft ?
|
const timeToWait = minutesLeft
|
||||||
`${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}` :
|
? `${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}`
|
||||||
'a few seconds';
|
: 'a few seconds';
|
||||||
|
|
||||||
return dedent`
|
return dedent`
|
||||||
Please wait ${timeToWait} to resend an authentication link.
|
Please wait ${timeToWait} to resend an authentication link.
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
const getRandomNumber = () => Math.random();
|
||||||
|
|
||||||
module.exports = function(User) {
|
module.exports = function(User) {
|
||||||
// set salt factor for passwords
|
// set salt factor for passwords
|
||||||
User.settings.saltWorkFactor = 5;
|
User.settings.saltWorkFactor = 5;
|
||||||
// set user.rand to random number
|
// set user.rand to random number
|
||||||
User.definition.rawProperties.rand.default =
|
User.definition.rawProperties.rand.default = getRandomNumber;
|
||||||
User.definition.properties.rand.default = function() {
|
User.definition.properties.rand.default = getRandomNumber;
|
||||||
return Math.random();
|
|
||||||
};
|
|
||||||
// increase user accessToken ttl to 900 days
|
// increase user accessToken ttl to 900 days
|
||||||
User.settings.ttl = 900 * 24 * 60 * 60 * 1000;
|
User.settings.ttl = 900 * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
@ -207,11 +198,8 @@ module.exports = function(User) {
|
|||||||
|
|
||||||
User.on('dataSourceAttached', () => {
|
User.on('dataSourceAttached', () => {
|
||||||
User.findOne$ = Observable.fromNodeCallback(User.findOne, User);
|
User.findOne$ = Observable.fromNodeCallback(User.findOne, User);
|
||||||
User.update$ = Observable.fromNodeCallback(User.updateAll, User);
|
|
||||||
User.count$ = Observable.fromNodeCallback(User.count, User);
|
User.count$ = Observable.fromNodeCallback(User.count, User);
|
||||||
User.create$ = Observable.fromNodeCallback(
|
User.create$ = Observable.fromNodeCallback(User.create.bind(User));
|
||||||
User.create.bind(User)
|
|
||||||
);
|
|
||||||
User.prototype.createAccessToken$ = Observable.fromNodeCallback(
|
User.prototype.createAccessToken$ = Observable.fromNodeCallback(
|
||||||
User.prototype.createAccessToken
|
User.prototype.createAccessToken
|
||||||
);
|
);
|
||||||
@ -225,10 +213,7 @@ module.exports = function(User) {
|
|||||||
.flatMap(user => {
|
.flatMap(user => {
|
||||||
// note(berks): we now require all new users to supply an email
|
// note(berks): we now require all new users to supply an email
|
||||||
// this was not always the case
|
// this was not always the case
|
||||||
if (
|
if (typeof user.email !== 'string' || !isEmail(user.email)) {
|
||||||
typeof user.email !== 'string' ||
|
|
||||||
!isEmail(user.email)
|
|
||||||
) {
|
|
||||||
throw createEmailError();
|
throw createEmailError();
|
||||||
}
|
}
|
||||||
// assign random username to new users
|
// assign random username to new users
|
||||||
@ -250,21 +235,19 @@ module.exports = function(User) {
|
|||||||
if (user.progressTimestamps.length === 0) {
|
if (user.progressTimestamps.length === 0) {
|
||||||
user.progressTimestamps.push(Date.now());
|
user.progressTimestamps.push(Date.now());
|
||||||
}
|
}
|
||||||
return Observable.fromPromise(User.doesExist(null, user.email))
|
return Observable.fromPromise(User.doesExist(null, user.email)).do(
|
||||||
.do(exists => {
|
exists => {
|
||||||
if (exists) {
|
if (exists) {
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error('user already exists'), {
|
||||||
new Error('user already exists'),
|
|
||||||
{
|
|
||||||
redirectTo: `${homeLocation}/signin`,
|
redirectTo: `${homeLocation}/signin`,
|
||||||
message: dedent`
|
message: dedent`
|
||||||
The ${user.email} email address is already associated with an account.
|
The ${user.email} email address is already associated with an account.
|
||||||
Try signing in with it here instead.
|
Try signing in with it here instead.
|
||||||
`
|
`
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
|
||||||
});
|
|
||||||
})
|
})
|
||||||
.ignoreElements();
|
.ignoreElements();
|
||||||
|
|
||||||
@ -282,9 +265,10 @@ module.exports = function(User) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
user.username = user.username.trim().toLowerCase();
|
user.username = user.username.trim().toLowerCase();
|
||||||
user.email = typeof user.email === 'string' ?
|
user.email =
|
||||||
user.email.trim().toLowerCase() :
|
typeof user.email === 'string'
|
||||||
user.email;
|
? user.email.trim().toLowerCase()
|
||||||
|
: user.email;
|
||||||
|
|
||||||
if (!user.progressTimestamps) {
|
if (!user.progressTimestamps) {
|
||||||
user.progressTimestamps = [];
|
user.progressTimestamps = [];
|
||||||
@ -303,8 +287,7 @@ module.exports = function(User) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.ignoreElements();
|
.ignoreElements();
|
||||||
return Observable.merge(beforeCreate, updateOrSave)
|
return Observable.merge(beforeCreate, updateOrSave).toPromise();
|
||||||
.toPromise();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// remove lingering user identities before deleting user
|
// remove lingering user identities before deleting user
|
||||||
@ -325,8 +308,7 @@ module.exports = function(User) {
|
|||||||
credData: credData
|
credData: credData
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
)
|
).subscribe(
|
||||||
.subscribe(
|
|
||||||
function(data) {
|
function(data) {
|
||||||
log('deleted', data);
|
log('deleted', data);
|
||||||
},
|
},
|
||||||
@ -344,38 +326,41 @@ module.exports = function(User) {
|
|||||||
log('setting up user hooks');
|
log('setting up user hooks');
|
||||||
// overwrite lb confirm
|
// overwrite lb confirm
|
||||||
User.confirm = function(uid, token, redirectTo) {
|
User.confirm = function(uid, token, redirectTo) {
|
||||||
return this.findById(uid)
|
return this.findById(uid).then(user => {
|
||||||
.then(user => {
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error(`User not found: ${uid}`), {
|
||||||
new Error(`User not found: ${uid}`),
|
|
||||||
{
|
|
||||||
// standard oops
|
// standard oops
|
||||||
type: 'info',
|
type: 'info',
|
||||||
redirectTo
|
redirectTo
|
||||||
}
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (user.verificationToken !== token) {
|
if (user.verificationToken !== token) {
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error(`Invalid token: ${token}`), {
|
||||||
new Error(`Invalid token: ${token}`),
|
|
||||||
{
|
|
||||||
type: 'info',
|
type: 'info',
|
||||||
message: dedent`
|
message: dedent`
|
||||||
Looks like you have clicked an invalid link.
|
Looks like you have clicked an invalid link.
|
||||||
Please sign in and request a fresh one.
|
Please sign in and request a fresh one.
|
||||||
`,
|
`,
|
||||||
redirectTo
|
redirectTo
|
||||||
|
});
|
||||||
}
|
}
|
||||||
);
|
return new Promise((resolve, reject) =>
|
||||||
}
|
user.updateAttributes(
|
||||||
return user.update$({
|
{
|
||||||
email: user.newEmail,
|
email: user.newEmail,
|
||||||
emailVerified: true,
|
emailVerified: true,
|
||||||
emailVerifyTTL: null,
|
emailVerifyTTL: null,
|
||||||
newEmail: null,
|
newEmail: null,
|
||||||
verificationToken: null
|
verificationToken: null
|
||||||
}).toPromise();
|
},
|
||||||
|
err => {
|
||||||
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -392,19 +377,16 @@ module.exports = function(User) {
|
|||||||
|
|
||||||
User.prototype.loginByRequest = function loginByRequest(req, res) {
|
User.prototype.loginByRequest = function loginByRequest(req, res) {
|
||||||
const {
|
const {
|
||||||
query: {
|
query: { emailChange }
|
||||||
emailChange
|
|
||||||
}
|
|
||||||
} = req;
|
} = req;
|
||||||
const createToken = this.createAccessToken$()
|
const createToken = this.createAccessToken$().do(accessToken => {
|
||||||
.do(accessToken => {
|
|
||||||
const config = {
|
const config = {
|
||||||
signed: !!req.signedCookies,
|
signed: !!req.signedCookies,
|
||||||
maxAge: accessToken.ttl,
|
maxAge: accessToken.ttl,
|
||||||
domain: process.env.COOKIE_DOMAIN || 'localhost'
|
domain: process.env.COOKIE_DOMAIN || 'localhost'
|
||||||
};
|
};
|
||||||
if (accessToken && accessToken.id) {
|
if (accessToken && accessToken.id) {
|
||||||
const jwtAccess = jwt.sign({accessToken}, process.env.JWT_SECRET);
|
const jwtAccess = jwt.sign({ accessToken }, process.env.JWT_SECRET);
|
||||||
res.cookie('jwt_access_token', jwtAccess, config);
|
res.cookie('jwt_access_token', jwtAccess, config);
|
||||||
res.cookie('access_token', accessToken.id, config);
|
res.cookie('access_token', accessToken.id, config);
|
||||||
res.cookie('userId', accessToken.userId, config);
|
res.cookie('userId', accessToken.userId, config);
|
||||||
@ -422,16 +404,23 @@ module.exports = function(User) {
|
|||||||
newEmail: null
|
newEmail: null
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const updateUser = this.update$(data);
|
const updateUser = new Promise((resolve, reject) =>
|
||||||
|
this.updateAttributes(data, err => {
|
||||||
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
return Observable.combineLatest(
|
return Observable.combineLatest(
|
||||||
createToken,
|
createToken,
|
||||||
updateUser,
|
Observable.fromPromise(updateUser),
|
||||||
req.logIn(this),
|
req.logIn(this),
|
||||||
(accessToken) => accessToken,
|
accessToken => accessToken
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
User.afterRemote('logout', function({req, res}, result, next) {
|
User.afterRemote('logout', function({ req, res }, result, next) {
|
||||||
const config = {
|
const config = {
|
||||||
signed: !!req.signedCookies,
|
signed: !!req.signedCookies,
|
||||||
domain: process.env.COOKIE_DOMAIN || 'localhost'
|
domain: process.env.COOKIE_DOMAIN || 'localhost'
|
||||||
@ -461,13 +450,10 @@ module.exports = function(User) {
|
|||||||
where.email = email ? email.toLowerCase() : email;
|
where.email = email ? email.toLowerCase() : email;
|
||||||
}
|
}
|
||||||
log('where', where);
|
log('where', where);
|
||||||
return User.count(where)
|
return User.count(where).then(count => count > 0);
|
||||||
.then(count => count > 0);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
User.remoteMethod(
|
User.remoteMethod('doesExist', {
|
||||||
'doesExist',
|
|
||||||
{
|
|
||||||
description: 'checks whether a user exists using email or username',
|
description: 'checks whether a user exists using email or username',
|
||||||
accepts: [
|
accepts: [
|
||||||
{
|
{
|
||||||
@ -489,8 +475,7 @@ module.exports = function(User) {
|
|||||||
path: '/exists',
|
path: '/exists',
|
||||||
verb: 'get'
|
verb: 'get'
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
User.about = function about(username, cb) {
|
User.about = function about(username, cb) {
|
||||||
if (!username) {
|
if (!username) {
|
||||||
@ -511,9 +496,7 @@ module.exports = function(User) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
User.remoteMethod(
|
User.remoteMethod('about', {
|
||||||
'about',
|
|
||||||
{
|
|
||||||
description: 'get public info about user',
|
description: 'get public info about user',
|
||||||
accepts: [
|
accepts: [
|
||||||
{
|
{
|
||||||
@ -531,8 +514,7 @@ module.exports = function(User) {
|
|||||||
path: '/about',
|
path: '/about',
|
||||||
verb: 'get'
|
verb: 'get'
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
User.prototype.createAuthToken = function createAuthToken({ ttl } = {}) {
|
User.prototype.createAuthToken = function createAuthToken({ ttl } = {}) {
|
||||||
return Observable.fromNodeCallback(
|
return Observable.fromNodeCallback(
|
||||||
@ -543,17 +525,12 @@ module.exports = function(User) {
|
|||||||
User.prototype.createDonation = function createDonation(donation = {}) {
|
User.prototype.createDonation = function createDonation(donation = {}) {
|
||||||
return Observable.fromNodeCallback(
|
return Observable.fromNodeCallback(
|
||||||
this.donations.create.bind(this.donations)
|
this.donations.create.bind(this.donations)
|
||||||
)(donation)
|
)(donation).do(() =>
|
||||||
.do(() => this.update$({
|
this.updateAttributes({
|
||||||
$set: {
|
isDonating: true,
|
||||||
isDonating: true
|
donationEmails: [...(this.donationEmails || []), donation.email]
|
||||||
},
|
|
||||||
$push: {
|
|
||||||
donationEmails: donation.email
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
.do(() => this.manualReload());
|
|
||||||
};
|
};
|
||||||
|
|
||||||
User.prototype.getEncodedEmail = function getEncodedEmail(email) {
|
User.prototype.getEncodedEmail = function getEncodedEmail(email) {
|
||||||
@ -569,13 +546,10 @@ module.exports = function(User) {
|
|||||||
return Observable.defer(() => {
|
return Observable.defer(() => {
|
||||||
const messageOrNull = getWaitMessage(this.emailAuthLinkTTL);
|
const messageOrNull = getWaitMessage(this.emailAuthLinkTTL);
|
||||||
if (messageOrNull) {
|
if (messageOrNull) {
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error('request is throttled'), {
|
||||||
new Error('request is throttled'),
|
|
||||||
{
|
|
||||||
type: 'info',
|
type: 'info',
|
||||||
message: messageOrNull
|
message: messageOrNull
|
||||||
}
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// create a temporary access token with ttl for 15 minutes
|
// create a temporary access token with ttl for 15 minutes
|
||||||
@ -609,12 +583,22 @@ module.exports = function(User) {
|
|||||||
emailChange: !!newEmail
|
emailChange: !!newEmail
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
const userUpdate = new Promise((resolve, reject) =>
|
||||||
|
this.updateAttributes({ emailAuthLinkTTL }, err => {
|
||||||
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
return Observable.forkJoin(
|
return Observable.forkJoin(
|
||||||
User.email.send$(mailOptions),
|
User.email.send$(mailOptions),
|
||||||
this.update$({ emailAuthLinkTTL })
|
Observable.fromPromise(userUpdate)
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
.map(() => 'Check your email and click the link we sent you to confirm' +
|
.map(
|
||||||
|
() =>
|
||||||
|
'Check your email and click the link we sent you to confirm' +
|
||||||
' your new email address.'
|
' your new email address.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -622,7 +606,6 @@ module.exports = function(User) {
|
|||||||
User.prototype.requestAuthEmail = requestAuthEmail;
|
User.prototype.requestAuthEmail = requestAuthEmail;
|
||||||
|
|
||||||
User.prototype.requestUpdateEmail = function requestUpdateEmail(newEmail) {
|
User.prototype.requestUpdateEmail = function requestUpdateEmail(newEmail) {
|
||||||
|
|
||||||
const currentEmail = this.email;
|
const currentEmail = this.email;
|
||||||
const isOwnEmail = isTheSame(newEmail, currentEmail);
|
const isOwnEmail = isTheSame(newEmail, currentEmail);
|
||||||
const isResendUpdateToSameEmail = isTheSame(newEmail, this.newEmail);
|
const isResendUpdateToSameEmail = isTheSame(newEmail, this.newEmail);
|
||||||
@ -631,28 +614,22 @@ module.exports = function(User) {
|
|||||||
|
|
||||||
if (isOwnEmail && isVerifiedEmail) {
|
if (isOwnEmail && isVerifiedEmail) {
|
||||||
// email is already associated and verified with this account
|
// email is already associated and verified with this account
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error('email is already verified'), {
|
||||||
new Error('email is already verified'),
|
|
||||||
{
|
|
||||||
type: 'info',
|
type: 'info',
|
||||||
message: `
|
message: `
|
||||||
${newEmail} is already associated with this account.
|
${newEmail} is already associated with this account.
|
||||||
You can update a new email address instead.`
|
You can update a new email address instead.`
|
||||||
}
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (isResendUpdateToSameEmail && isLinkSentWithinLimit) {
|
if (isResendUpdateToSameEmail && isLinkSentWithinLimit) {
|
||||||
// trying to update with the same newEmail and
|
// trying to update with the same newEmail and
|
||||||
// confirmation email is still valid
|
// confirmation email is still valid
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error(), {
|
||||||
new Error(),
|
|
||||||
{
|
|
||||||
type: 'info',
|
type: 'info',
|
||||||
message: dedent`
|
message: dedent`
|
||||||
We have already sent an email confirmation request to ${newEmail}.
|
We have already sent an email confirmation request to ${newEmail}.
|
||||||
${isLinkSentWithinLimit}`
|
${isLinkSentWithinLimit}`
|
||||||
}
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (!isEmail('' + newEmail)) {
|
if (!isEmail('' + newEmail)) {
|
||||||
throw createEmailError();
|
throw createEmailError();
|
||||||
@ -678,31 +655,27 @@ module.exports = function(User) {
|
|||||||
if (exists && !isOwnEmail) {
|
if (exists && !isOwnEmail) {
|
||||||
// newEmail is not associated with this account,
|
// newEmail is not associated with this account,
|
||||||
// but is associated with different account
|
// but is associated with different account
|
||||||
throw wrapHandledError(
|
throw wrapHandledError(new Error('email already in use'), {
|
||||||
new Error('email already in use'),
|
|
||||||
{
|
|
||||||
type: 'info',
|
type: 'info',
|
||||||
message:
|
message: `${newEmail} is already associated with another account.`
|
||||||
`${newEmail} is already associated with another account.`
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatMap(()=>{
|
.flatMap(() => {
|
||||||
const updatePromise = new Promise((resolve, reject) =>
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
this.updateAttributes(updateConfig, err => {
|
this.updateAttributes(updateConfig, err => {
|
||||||
if (err) {
|
if (err) {
|
||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
return resolve();
|
return resolve();
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
return Observable.forkJoin(
|
return Observable.forkJoin(
|
||||||
Observable.fromPromise(updatePromise),
|
Observable.fromPromise(updatePromise),
|
||||||
this.requestAuthEmail(false, newEmail),
|
this.requestAuthEmail(false, newEmail),
|
||||||
(_, message) => message
|
(_, message) => message
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return 'Something unexpected happened whilst updating your email.';
|
return 'Something unexpected happened whilst updating your email.';
|
||||||
}
|
}
|
||||||
@ -714,40 +687,47 @@ module.exports = function(User) {
|
|||||||
|
|
||||||
User.prototype.requestCompletedChallenges = requestCompletedChallenges;
|
User.prototype.requestCompletedChallenges = requestCompletedChallenges;
|
||||||
|
|
||||||
User.prototype.requestUpdateFlags = function requestUpdateFlags(values) {
|
User.prototype.requestUpdateFlags = async function requestUpdateFlags(
|
||||||
|
values
|
||||||
|
) {
|
||||||
const flagsToCheck = Object.keys(values);
|
const flagsToCheck = Object.keys(values);
|
||||||
const valuesToCheck = _.pick({ ...this }, flagsToCheck);
|
const valuesToCheck = _.pick({ ...this }, flagsToCheck);
|
||||||
const valuesToUpdate = flagsToCheck
|
const flagsToUpdate = flagsToCheck.filter(
|
||||||
.filter(flag => !isTheSame(values[flag], valuesToCheck[flag]));
|
flag => !isTheSame(values[flag], valuesToCheck[flag])
|
||||||
if (!valuesToUpdate.length) {
|
);
|
||||||
return Observable.of(dedent`
|
if (!flagsToUpdate.length) {
|
||||||
|
return Observable.of(
|
||||||
|
dedent`
|
||||||
No property in
|
No property in
|
||||||
${JSON.stringify(flagsToCheck, null, 2)}
|
${JSON.stringify(flagsToCheck, null, 2)}
|
||||||
will introduce a change in this user.
|
will introduce a change in this user.
|
||||||
`
|
`
|
||||||
)
|
).map(() => dedent`Your settings have not been updated.`);
|
||||||
.map(() => dedent`Your settings have not been updated.`);
|
|
||||||
}
|
}
|
||||||
return Observable.from(valuesToUpdate)
|
const userUpdateData = flagsToUpdate.reduce((data, currentFlag) => {
|
||||||
.flatMap(flag => Observable.of({ flag, newValue: values[flag] }))
|
data[currentFlag] = values[currentFlag];
|
||||||
.toArray()
|
return data;
|
||||||
.flatMap(updates => {
|
}, {});
|
||||||
return Observable.forkJoin(
|
log(userUpdateData);
|
||||||
Observable.from(updates)
|
const userUpdate = new Promise((resolve, reject) =>
|
||||||
.flatMap(({ flag, newValue }) => {
|
this.updateAttributes(userUpdateData, err => {
|
||||||
return Observable.fromPromise(User.doesExist(null, this.email))
|
if (err) {
|
||||||
.flatMap(() => this.update$({ [flag]: newValue }));
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
})
|
return Observable.fromPromise(userUpdate).map(
|
||||||
.doOnNext(() => this.manualReload())
|
() => dedent`
|
||||||
.map(() => dedent`
|
|
||||||
We have successfully updated your account.
|
We have successfully updated your account.
|
||||||
`);
|
`
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
User.prototype.updateMyPortfolio =
|
User.prototype.updateMyPortfolio = function updateMyPortfolio(
|
||||||
function updateMyPortfolio(portfolioItem, deleteRequest) {
|
portfolioItem,
|
||||||
|
deleteRequest
|
||||||
|
) {
|
||||||
const currentPortfolio = this.portfolio.slice(0);
|
const currentPortfolio = this.portfolio.slice(0);
|
||||||
const pIndex = _.findIndex(
|
const pIndex = _.findIndex(
|
||||||
currentPortfolio,
|
currentPortfolio,
|
||||||
@ -759,16 +739,24 @@ module.exports = function(User) {
|
|||||||
p => p.id !== portfolioItem.id
|
p => p.id !== portfolioItem.id
|
||||||
);
|
);
|
||||||
} else if (pIndex === -1) {
|
} else if (pIndex === -1) {
|
||||||
updatedPortfolio = currentPortfolio.concat([ portfolioItem ]);
|
updatedPortfolio = currentPortfolio.concat([portfolioItem]);
|
||||||
} else {
|
} else {
|
||||||
updatedPortfolio = [ ...currentPortfolio ];
|
updatedPortfolio = [...currentPortfolio];
|
||||||
updatedPortfolio[pIndex] = { ...portfolioItem };
|
updatedPortfolio[pIndex] = { ...portfolioItem };
|
||||||
}
|
}
|
||||||
return this.update$({ portfolio: updatedPortfolio })
|
const userUpdate = new Promise((resolve, reject) =>
|
||||||
.do(() => this.manualReload())
|
this.updateAttribute('portfolio', updatedPortfolio, err => {
|
||||||
.map(() => dedent`
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return Observable.fromPromise(userUpdate).map(
|
||||||
|
() => dedent`
|
||||||
Your portfolio has been updated.
|
Your portfolio has been updated.
|
||||||
`);
|
`
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
User.prototype.updateMyProjects = function updateMyProjects(project) {
|
User.prototype.updateMyProjects = function updateMyProjects(project) {
|
||||||
@ -778,10 +766,7 @@ module.exports = function(User) {
|
|||||||
const {
|
const {
|
||||||
updated,
|
updated,
|
||||||
isNewCompletionCount
|
isNewCompletionCount
|
||||||
} = buildCompletedChallengesUpdate(
|
} = buildCompletedChallengesUpdate(this.completedChallenges, project);
|
||||||
this.completedChallenges,
|
|
||||||
project
|
|
||||||
);
|
|
||||||
updateData.$set.completedChallenges = updated;
|
updateData.$set.completedChallenges = updated;
|
||||||
if (isNewCompletionCount) {
|
if (isNewCompletionCount) {
|
||||||
let points = [];
|
let points = [];
|
||||||
@ -792,33 +777,45 @@ module.exports = function(User) {
|
|||||||
$each: points.map(() => Date.now())
|
$each: points.map(() => Date.now())
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return this.update$(updateData);
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
|
this.updateAttributes(updateData, err => {
|
||||||
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
})
|
})
|
||||||
.doOnNext(() => this.manualReload() )
|
);
|
||||||
.map(() => dedent`
|
return Observable.fromPromise(updatePromise);
|
||||||
|
})
|
||||||
|
.map(
|
||||||
|
() => dedent`
|
||||||
Your projects have been updated.
|
Your projects have been updated.
|
||||||
`);
|
`
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
User.prototype.updateMyProfileUI = function updateMyProfileUI(profileUI) {
|
User.prototype.updateMyProfileUI = function updateMyProfileUI(profileUI) {
|
||||||
const oldUI = { ...this.profileUI };
|
const newProfileUI = {
|
||||||
const update = {
|
...this.profileUI,
|
||||||
profileUI: {
|
|
||||||
...oldUI,
|
|
||||||
...profileUI
|
...profileUI
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
const profileUIUpdate = new Promise((resolve, reject) =>
|
||||||
return this.update$(update)
|
this.updateAttribute('profileUI', newProfileUI, err => {
|
||||||
.doOnNext(() => this.manualReload())
|
if (err) {
|
||||||
.map(() => dedent`
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return Observable.fromPromise(profileUIUpdate).map(
|
||||||
|
() => dedent`
|
||||||
Your privacy settings have been updated.
|
Your privacy settings have been updated.
|
||||||
`);
|
`
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
User.prototype.updateMyUsername = function updateMyUsername(newUsername) {
|
User.prototype.updateMyUsername = function updateMyUsername(newUsername) {
|
||||||
return Observable.defer(
|
return Observable.defer(() => {
|
||||||
() => {
|
|
||||||
const isOwnUsername = isTheSame(newUsername, this.username);
|
const isOwnUsername = isTheSame(newUsername, this.username);
|
||||||
if (isOwnUsername) {
|
if (isOwnUsername) {
|
||||||
return Observable.of(dedent`
|
return Observable.of(dedent`
|
||||||
@ -826,9 +823,7 @@ module.exports = function(User) {
|
|||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
return Observable.fromPromise(User.doesExist(newUsername));
|
return Observable.fromPromise(User.doesExist(newUsername));
|
||||||
}
|
}).flatMap(boolOrMessage => {
|
||||||
)
|
|
||||||
.flatMap(boolOrMessage => {
|
|
||||||
if (typeof boolOrMessage === 'string') {
|
if (typeof boolOrMessage === 'string') {
|
||||||
return Observable.of(boolOrMessage);
|
return Observable.of(boolOrMessage);
|
||||||
}
|
}
|
||||||
@ -838,11 +833,20 @@ module.exports = function(User) {
|
|||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.update$({ username: newUsername })
|
const usernameUpdate = new Promise((resolve, reject) =>
|
||||||
.do(() => this.manualReload())
|
this.updateAttribute('username', newUsername, err => {
|
||||||
.map(() => dedent`
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return Observable.fromPromise(usernameUpdate).map(
|
||||||
|
() => dedent`
|
||||||
Your username has been updated successfully.
|
Your username has been updated successfully.
|
||||||
`);
|
`
|
||||||
|
);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -896,7 +900,7 @@ module.exports = function(User) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
User.getPublicProfile = function getPublicProfile(username, cb) {
|
User.getPublicProfile = function getPublicProfile(username, cb) {
|
||||||
return User.findOne$({ where: { username }})
|
return User.findOne$({ where: { username } })
|
||||||
.flatMap(user => {
|
.flatMap(user => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return Observable.of({});
|
return Observable.of({});
|
||||||
@ -932,10 +936,7 @@ module.exports = function(User) {
|
|||||||
result: user.username
|
result: user.username
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.subscribe(
|
.subscribe(user => cb(null, user), cb);
|
||||||
user => cb(null, user),
|
|
||||||
cb
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
User.remoteMethod('getPublicProfile', {
|
User.remoteMethod('getPublicProfile', {
|
||||||
@ -957,53 +958,56 @@ module.exports = function(User) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
User.giveBrowniePoints =
|
User.giveBrowniePoints = function giveBrowniePoints(
|
||||||
function giveBrowniePoints(receiver, giver, data = {}, dev = false, cb) {
|
receiver,
|
||||||
|
giver,
|
||||||
|
data = {},
|
||||||
|
dev = false,
|
||||||
|
cb
|
||||||
|
) {
|
||||||
const findUser = observeMethod(User, 'findOne');
|
const findUser = observeMethod(User, 'findOne');
|
||||||
if (!receiver) {
|
if (!receiver) {
|
||||||
return nextTick(() => {
|
return nextTick(() => {
|
||||||
cb(
|
cb(new TypeError(`receiver should be a string but got ${receiver}`));
|
||||||
new TypeError(`receiver should be a string but got ${ receiver }`)
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!giver) {
|
if (!giver) {
|
||||||
return nextTick(() => {
|
return nextTick(() => {
|
||||||
cb(new TypeError(`giver should be a string but got ${ giver }`));
|
cb(new TypeError(`giver should be a string but got ${giver}`));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let temp = moment();
|
let temp = moment();
|
||||||
const browniePoints = temp
|
const browniePoints = temp.subtract
|
||||||
.subtract.apply(temp, BROWNIEPOINTS_TIMEOUT)
|
.apply(temp, BROWNIEPOINTS_TIMEOUT)
|
||||||
.valueOf();
|
.valueOf();
|
||||||
const user$ = findUser({ where: { username: receiver }});
|
const user$ = findUser({ where: { username: receiver } });
|
||||||
|
|
||||||
return user$
|
return (
|
||||||
.tapOnNext((user) => {
|
user$
|
||||||
|
.tapOnNext(user => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new Error(`could not find receiver for ${ receiver }`);
|
throw new Error(`could not find receiver for ${receiver}`);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.flatMap(({ progressTimestamps = [] }) => {
|
.flatMap(({ progressTimestamps = [] }) => {
|
||||||
return Observable.from(progressTimestamps);
|
return Observable.from(progressTimestamps);
|
||||||
})
|
})
|
||||||
// filter out non objects
|
// filter out non objects
|
||||||
.filter((timestamp) => !!timestamp || typeof timestamp === 'object')
|
.filter(timestamp => !!timestamp || typeof timestamp === 'object')
|
||||||
// filterout timestamps older then an hour
|
// filterout timestamps older then an hour
|
||||||
.filter(({ timestamp = 0 }) => {
|
.filter(({ timestamp = 0 }) => {
|
||||||
return timestamp >= browniePoints;
|
return timestamp >= browniePoints;
|
||||||
})
|
})
|
||||||
// filter out brownie points given by giver
|
// filter out brownie points given by giver
|
||||||
.filter((browniePoint) => {
|
.filter(browniePoint => {
|
||||||
return browniePoint.giver === giver;
|
return browniePoint.giver === giver;
|
||||||
})
|
})
|
||||||
// no results means this is the first brownie point given by giver
|
// no results means this is the first brownie point given by giver
|
||||||
// so return -1 to indicate receiver should receive point
|
// so return -1 to indicate receiver should receive point
|
||||||
.first({ defaultValue: -1 })
|
.first({ defaultValue: -1 })
|
||||||
.flatMap((browniePointsFromGiver) => {
|
.flatMap(browniePointsFromGiver => {
|
||||||
if (browniePointsFromGiver === -1) {
|
if (browniePointsFromGiver === -1) {
|
||||||
|
return user$.flatMap(user => {
|
||||||
return user$.flatMap((user) => {
|
|
||||||
user.progressTimestamps.push({
|
user.progressTimestamps.push({
|
||||||
giver,
|
giver,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
@ -1013,29 +1017,26 @@ module.exports = function(User) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
return Observable.throw(
|
return Observable.throw(
|
||||||
new Error(`${ giver } already gave ${ receiver } points`)
|
new Error(`${giver} already gave ${receiver} points`)
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
.subscribe(
|
.subscribe(
|
||||||
(user) => {
|
user => {
|
||||||
return cb(
|
return cb(
|
||||||
null,
|
null,
|
||||||
getAboutProfile(user),
|
getAboutProfile(user),
|
||||||
dev ?
|
dev ? { giver, receiver, data } : null
|
||||||
{ giver, receiver, data } :
|
|
||||||
null
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
(e) => cb(e, null, dev ? { giver, receiver, data } : null),
|
e => cb(e, null, dev ? { giver, receiver, data } : null),
|
||||||
() => {
|
() => {
|
||||||
log('brownie points assigned completed');
|
log('brownie points assigned completed');
|
||||||
}
|
}
|
||||||
|
)
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
User.remoteMethod(
|
User.remoteMethod('giveBrowniePoints', {
|
||||||
'giveBrowniePoints',
|
|
||||||
{
|
|
||||||
description: 'Give this user brownie points',
|
description: 'Give this user brownie points',
|
||||||
accepts: [
|
accepts: [
|
||||||
{
|
{
|
||||||
@ -1071,78 +1072,15 @@ module.exports = function(User) {
|
|||||||
path: '/give-brownie-points',
|
path: '/give-brownie-points',
|
||||||
verb: 'POST'
|
verb: 'POST'
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
User.themes = themes;
|
|
||||||
|
|
||||||
User.prototype.updateTheme = function updateTheme(theme) {
|
|
||||||
if (!this.constructor.themes[theme]) {
|
|
||||||
const err = wrapHandledError(
|
|
||||||
new Error('Theme is not valid.'),
|
|
||||||
{
|
|
||||||
Type: 'info',
|
|
||||||
message: err.message
|
|
||||||
}
|
|
||||||
);
|
|
||||||
return Promise.reject(err);
|
|
||||||
}
|
|
||||||
return this.update$({ theme })
|
|
||||||
.doOnNext(() => this.manualReload())
|
|
||||||
.toPromise();
|
|
||||||
};
|
|
||||||
|
|
||||||
// deprecated. remove once live
|
|
||||||
User.remoteMethod(
|
|
||||||
'updateTheme',
|
|
||||||
{
|
|
||||||
description: 'updates the users chosen theme',
|
|
||||||
accepts: [
|
|
||||||
{
|
|
||||||
arg: 'theme',
|
|
||||||
type: 'string',
|
|
||||||
required: true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
returns: [
|
|
||||||
{
|
|
||||||
arg: 'status',
|
|
||||||
type: 'object'
|
|
||||||
}
|
|
||||||
],
|
|
||||||
http: {
|
|
||||||
path: '/update-theme',
|
|
||||||
verb: 'POST'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// user.updateTo$(updateData: Object) => Observable[Number]
|
|
||||||
User.prototype.update$ = function update$(updateData) {
|
|
||||||
const id = this.getId();
|
|
||||||
const updateOptions = { allowExtendedOperators: true };
|
|
||||||
if (
|
|
||||||
!updateData ||
|
|
||||||
typeof updateData !== 'object' ||
|
|
||||||
!Object.keys(updateData).length
|
|
||||||
) {
|
|
||||||
return Observable.throw(new Error(
|
|
||||||
dedent`
|
|
||||||
updateData must be an object with at least one key,
|
|
||||||
but got ${updateData} with ${Object.keys(updateData).length}
|
|
||||||
`.split('\n').join(' ')
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return this.constructor.update$({ id }, updateData, updateOptions);
|
|
||||||
};
|
|
||||||
User.prototype.getPoints$ = function getPoints$() {
|
User.prototype.getPoints$ = function getPoints$() {
|
||||||
const id = this.getId();
|
const id = this.getId();
|
||||||
const filter = {
|
const filter = {
|
||||||
where: { id },
|
where: { id },
|
||||||
fields: { progressTimestamps: true }
|
fields: { progressTimestamps: true }
|
||||||
};
|
};
|
||||||
return this.constructor.findOne$(filter)
|
return this.constructor.findOne$(filter).map(user => {
|
||||||
.map(user => {
|
|
||||||
this.progressTimestamps = user.progressTimestamps;
|
this.progressTimestamps = user.progressTimestamps;
|
||||||
return user.progressTimestamps;
|
return user.progressTimestamps;
|
||||||
});
|
});
|
||||||
@ -1153,8 +1091,7 @@ module.exports = function(User) {
|
|||||||
where: { id },
|
where: { id },
|
||||||
fields: { completedChallenges: true }
|
fields: { completedChallenges: true }
|
||||||
};
|
};
|
||||||
return this.constructor.findOne$(filter)
|
return this.constructor.findOne$(filter).map(user => {
|
||||||
.map(user => {
|
|
||||||
this.completedChallenges = user.completedChallenges;
|
this.completedChallenges = user.completedChallenges;
|
||||||
return user.completedChallenges;
|
return user.completedChallenges;
|
||||||
});
|
});
|
||||||
|
@ -272,9 +272,17 @@ function createVerifyCert(certTypeIds, app) {
|
|||||||
// set here so sendCertifiedEmail works properly
|
// set here so sendCertifiedEmail works properly
|
||||||
// not used otherwise
|
// not used otherwise
|
||||||
user[certType] = true;
|
user[certType] = true;
|
||||||
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
|
user.updateAttributes(updateData, err => {
|
||||||
|
if (err) {
|
||||||
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
return Observable.combineLatest(
|
return Observable.combineLatest(
|
||||||
// update user data
|
// update user data
|
||||||
user.update$(updateData),
|
Observable.fromPromise(updatePromise),
|
||||||
// If user has committed to nonprofit,
|
// If user has committed to nonprofit,
|
||||||
// this will complete their pledge
|
// this will complete their pledge
|
||||||
completeCommitment$(user),
|
completeCommitment$(user),
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
* a db migration to fix all completedChallenges
|
* a db migration to fix all completedChallenges
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
import { Observable } from 'rx';
|
||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
import debug from 'debug';
|
import debug from 'debug';
|
||||||
import accepts from 'accepts';
|
import accepts from 'accepts';
|
||||||
@ -87,9 +87,6 @@ function buildUserUpdate(user, challengeId, _completedChallenge, timezone) {
|
|||||||
timezone: userTimezone
|
timezone: userTimezone
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
log('user update data', updateData);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
alreadyCompleted,
|
alreadyCompleted,
|
||||||
updateData,
|
updateData,
|
||||||
@ -215,12 +212,15 @@ export default async function bootChallenge(app, done) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const points = alreadyCompleted ? user.points : user.points + 1;
|
const points = alreadyCompleted ? user.points : user.points + 1;
|
||||||
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
return user
|
user.updateAttributes(updateData, err => {
|
||||||
.update$(updateData)
|
if (err) {
|
||||||
.doOnNext(() => user.manualReload())
|
return reject(err);
|
||||||
.doOnNext(({ count }) => log('%s documents updated', count))
|
}
|
||||||
.map(() => {
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return Observable.fromPromise(updatePromise).map(() => {
|
||||||
if (type === 'json') {
|
if (type === 'json') {
|
||||||
return res.json({
|
return res.json({
|
||||||
points,
|
points,
|
||||||
@ -239,6 +239,8 @@ export default async function bootChallenge(app, done) {
|
|||||||
const type = accepts(req).type('html', 'json', 'text');
|
const type = accepts(req).type('html', 'json', 'text');
|
||||||
const errors = req.validationErrors(true);
|
const errors = req.validationErrors(true);
|
||||||
|
|
||||||
|
const { user } = req;
|
||||||
|
|
||||||
if (errors) {
|
if (errors) {
|
||||||
if (type === 'json') {
|
if (type === 'json') {
|
||||||
return res.status(403).send({ errors });
|
return res.status(403).send({ errors });
|
||||||
@ -248,26 +250,30 @@ export default async function bootChallenge(app, done) {
|
|||||||
return res.sendStatus(403);
|
return res.sendStatus(403);
|
||||||
}
|
}
|
||||||
|
|
||||||
return req.user
|
return user
|
||||||
.getCompletedChallenges$()
|
.getCompletedChallenges$()
|
||||||
.flatMap(() => {
|
.flatMap(() => {
|
||||||
const completedDate = Date.now();
|
const completedDate = Date.now();
|
||||||
const { id, solution, timezone, files } = req.body;
|
const { id, solution, timezone, files } = req.body;
|
||||||
|
|
||||||
const { alreadyCompleted, updateData } = buildUserUpdate(
|
const { alreadyCompleted, updateData } = buildUserUpdate(
|
||||||
req.user,
|
user,
|
||||||
id,
|
id,
|
||||||
{ id, solution, completedDate, files },
|
{ id, solution, completedDate, files },
|
||||||
timezone
|
timezone
|
||||||
);
|
);
|
||||||
|
|
||||||
const user = req.user;
|
|
||||||
const points = alreadyCompleted ? user.points : user.points + 1;
|
const points = alreadyCompleted ? user.points : user.points + 1;
|
||||||
|
|
||||||
return user
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
.update$(updateData)
|
user.updateAttributes(updateData, err => {
|
||||||
.doOnNext(({ count }) => log('%s documents updated', count))
|
if (err) {
|
||||||
.map(() => {
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return Observable.fromPromise(updatePromise).map(() => {
|
||||||
if (type === 'json') {
|
if (type === 'json') {
|
||||||
return res.json({
|
return res.json({
|
||||||
points,
|
points,
|
||||||
@ -329,11 +335,15 @@ export default async function bootChallenge(app, done) {
|
|||||||
completedChallenge
|
completedChallenge
|
||||||
);
|
);
|
||||||
|
|
||||||
return user
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
.update$(updateData)
|
user.updateAttributes(updateData, err => {
|
||||||
.doOnNext(() => user.manualReload())
|
if (err) {
|
||||||
.doOnNext(({ count }) => log('%s documents updated', count))
|
return reject(err);
|
||||||
.doOnNext(() => {
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return Observable.fromPromise(updatePromise).doOnNext(() => {
|
||||||
if (type === 'json') {
|
if (type === 'json') {
|
||||||
return res.send({
|
return res.send({
|
||||||
alreadyCompleted,
|
alreadyCompleted,
|
||||||
@ -376,10 +386,15 @@ export default async function bootChallenge(app, done) {
|
|||||||
completedChallenge
|
completedChallenge
|
||||||
);
|
);
|
||||||
|
|
||||||
return user
|
const updatePromise = new Promise((resolve, reject) =>
|
||||||
.update$(updateData)
|
user.updateAttributes(updateData, err => {
|
||||||
.doOnNext(({ count }) => log('%s documents updated', count))
|
if (err) {
|
||||||
.doOnNext(() => {
|
return reject(err);
|
||||||
|
}
|
||||||
|
return resolve();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return Observable.fromPromise(updatePromise).doOnNext(() => {
|
||||||
if (type === 'json') {
|
if (type === 'json') {
|
||||||
return res.send({
|
return res.send({
|
||||||
alreadyCompleted,
|
alreadyCompleted,
|
||||||
|
@ -120,12 +120,15 @@ function getUnlinkSocial(req, res, next) {
|
|||||||
|
|
||||||
const updateData = { [social]: null };
|
const updateData = { [social]: null };
|
||||||
|
|
||||||
return user.update$(updateData).subscribe(() => {
|
return user.updateAttributes(updateData, err => {
|
||||||
|
if (err) {
|
||||||
|
return next(err);
|
||||||
|
}
|
||||||
log(`${social} has been unlinked successfully`);
|
log(`${social} has been unlinked successfully`);
|
||||||
|
|
||||||
req.flash('info', `You've successfully unlinked your ${social}.`);
|
req.flash('info', `You've successfully unlinked your ${social}.`);
|
||||||
return res.redirect('/' + username);
|
return res.redirectWithFlash(`${homeLocation}/${username}`);
|
||||||
}, next);
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"db": {
|
"db": {
|
||||||
"name": "db",
|
"name": "db",
|
||||||
"connector": "mongodb"
|
"connector": "mongodb",
|
||||||
|
"allowExtendedOperators": true
|
||||||
},
|
},
|
||||||
"mail": {
|
"mail": {
|
||||||
"name": "mail",
|
"name": "mail",
|
||||||
|
Reference in New Issue
Block a user