From 7dfdbb8b0523d0f78154ba9246a4daafa4e32be2 Mon Sep 17 00:00:00 2001 From: Victor Piousbox Date: Fri, 4 Mar 2016 21:27:16 +0000 Subject: [PATCH] /user/update-email endpoint --- common/locales/en/api-v3.json | 3 + .../user/POST-user-update-email.test.js | 77 +++++++++++++++++++ test/helpers/api-integration/requester.js | 2 +- website/src/controllers/api-v3/email.js | 3 +- website/src/controllers/api-v3/user.js | 42 +++++++++- website/src/libs/api-v3/errors.js | 14 ++++ 6 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 test/api/v3/integration/user/POST-user-update-email.test.js diff --git a/common/locales/en/api-v3.json b/common/locales/en/api-v3.json index 06ba7afd75..0ff43db786 100644 --- a/common/locales/en/api-v3.json +++ b/common/locales/en/api-v3.json @@ -4,8 +4,10 @@ "missingEmail": "Missing email.", "missingUsername": "Missing username.", "missingPassword": "Missing password.", + "wrongPassword": "Wrong password.", "notAnEmail": "Invalid email address.", "emailTaken": "Email already taken.", + "newEmailRequired": "The newEmail body parameter is required.", "usernameTaken": "Username already taken.", "passwordConfirmationMatch": "Password confirmation doesn't match password.", "invalidLoginCredentials": "Incorrect username / email and / or password.", @@ -64,6 +66,7 @@ "userAlreadyPendingInvitation": "User already pending invitation.", "userAlreadyInAParty": "User already in a party.", "userWithIDNotFound": "User with id \"<%= userId %>\" not found.", + "userHasNoLocalRegistration": "User does not have a local registration (username, email, password).", "uuidsMustBeAnArray": "UUIDs invites must be a an Array.", "emailsMustBeAnArray": "Email invites must be a an Array.", "canOnlyInviteMaxInvites": "You can only invite \"<%= maxInvites %>\" at a time", diff --git a/test/api/v3/integration/user/POST-user-update-email.test.js b/test/api/v3/integration/user/POST-user-update-email.test.js new file mode 100644 index 0000000000..6a95b57ce8 --- /dev/null +++ b/test/api/v3/integration/user/POST-user-update-email.test.js @@ -0,0 +1,77 @@ +import { + generateUser, + translate as t, +} from '../../../../helpers/api-v3-integration.helper'; +import { model as User } from '../../../../../website/src/models/user'; + +describe('POST /email/update', () => { + let user; + let fbUser; + let endpoint = '/user/update-email'; + let newEmail = 'some-new-email_2@example.net'; + let thePassword = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js + + describe('local user', async () => { + beforeEach(async () => { + user = await generateUser(); + }); + + it('does not change email if one is not provided', async () => { + await expect(user.post(endpoint)).to.eventually.be.rejected.and.eql({ + code: 400, + error: 'BadRequest', + message: 'Invalid request parameters.', + }); + }); + + it('does not change email if password is not provided', async () => { + await expect(user.post(endpoint, { + newEmail, + })).to.eventually.be.rejected.and.eql({ + code: 400, + error: 'BadRequest', + message: 'Invalid request parameters.', + }); + }); + + it('does not change email if wrong password is provided', async () => { + await expect(user.post(endpoint, { + newEmail, + password: 'wrong password', + })).to.eventually.be.rejected.and.eql({ + code: 401, + error: 'NotAuthorized', + message: t('wrongPassword'), + }); + }); + + it('changes email if new email and existing password are provided', async () => { + let response = await user.post(endpoint, { + newEmail, + password: thePassword, + }); + expect(response).to.eql({ email: 'some-new-email_2@example.net' }); + let id = user._id; + user = await User.findOne({ _id: id }); + expect(user.auth.local.email).to.eql(newEmail); + }); + }); + + describe('facebook user', async () => { + beforeEach(async () => { + fbUser = await generateUser(); + await fbUser.update({ 'auth.local': { ok: true } }); + }); + + it('does not change email if user.auth.local.email does not exist for this user', async () => { + await expect(fbUser.post(endpoint, { + newEmail, + password: thePassword, + })).to.eventually.be.rejected.and.eql({ + code: 412, + error: 'PreconditionFailed', + message: t('userHasNoLocalRegistration'), + }); + }); + }); +}); diff --git a/test/helpers/api-integration/requester.js b/test/helpers/api-integration/requester.js index 3eab7c7ede..903c198686 100644 --- a/test/helpers/api-integration/requester.js +++ b/test/helpers/api-integration/requester.js @@ -7,7 +7,7 @@ import { isEmpty, cloneDeep } from 'lodash'; const API_TEST_SERVER_PORT = nconf.get('PORT'); let apiVersion; -// Sets up an abject that can make all REST requests +// Sets up an object that can make all REST requests // If a user is passed in, the uuid and api token of // the user are used to make the requests export function requester (user = {}, additionalSets = {}) { diff --git a/website/src/controllers/api-v3/email.js b/website/src/controllers/api-v3/email.js index b3af91b340..a5fa7054bb 100644 --- a/website/src/controllers/api-v3/email.js +++ b/website/src/controllers/api-v3/email.js @@ -8,10 +8,11 @@ import { let api = {}; /** - * @api {post} /unsubscribe Unsubscribe an email or user from email notifications + * @api {get} /unsubscribe Unsubscribe an email or user from email notifications * @apiVersion 3.0.0 * @apiName UnsubscribeEmail * @apiGroup Unsubscribe + * @apiDescription This is a GET method so that you can put the unsubscribe link in emails. * * @apiParam {String} code An unsubscription code * diff --git a/website/src/controllers/api-v3/user.js b/website/src/controllers/api-v3/user.js index 39efc002f9..95e8029081 100644 --- a/website/src/controllers/api-v3/user.js +++ b/website/src/controllers/api-v3/user.js @@ -1,6 +1,12 @@ import { authWithHeaders } from '../../middlewares/api-v3/auth'; import cron from '../../middlewares/api-v3/cron'; import common from '../../../../common'; +import { + PreconditionFailed, + BadRequest, + NotAuthorized, +} from '../../libs/api-v3/errors'; +import * as passwordUtils from '../../libs/api-v3/password'; let api = {}; @@ -19,7 +25,7 @@ api.getUser = { async handler (req, res) { let user = res.locals.user.toJSON(); - // Remove apiToken from resonse TODO make it priavte at the user level? returned in signup/login + // Remove apiToken from response TODO make it priavte at the user level? returned in signup/login delete user.apiToken; // TODO move to model (maybe virtuals, maybe in toJSON) @@ -31,4 +37,38 @@ api.getUser = { }, }; +/** + * @api {post} /user/update-email + * @apiVersion 3.0.0 + * @apiName EmailUpdate + * @apiGroup User + * + * @apiSuccess {Object} { status: 'ok' } + **/ +api.updateEmail = { + method: 'POST', + middlewares: [authWithHeaders(), cron], + url: '/user/update-email', + async handler (req, res) { + let user = res.locals.user; + + if (!user.auth.local.email) throw new PreconditionFailed(res.t('userHasNoLocalRegistration')); + + req.checkBody('newEmail', res.t('newEmailRequired')).notEmpty().isEmail(); + req.checkBody('password', res.t('missingPassword')).notEmpty(); + let validationErrors = req.validationErrors(); + if (validationErrors) throw validationErrors; + + // check password + let candidatePassword = passwordUtils.encrypt(req.body.password, user.auth.local.salt); + if (candidatePassword !== user.auth.local.hashed_password) throw new NotAuthorized(res.t('wrongPassword')); + + // save new email + user.auth.local.email = req.body.newEmail; + await user.save(); + + return res.respond(200, { email: user.auth.local.email }); + }, +}; + export default api; diff --git a/website/src/libs/api-v3/errors.js b/website/src/libs/api-v3/errors.js index cb93e7b4a2..4d4d2376a3 100644 --- a/website/src/libs/api-v3/errors.js +++ b/website/src/libs/api-v3/errors.js @@ -47,6 +47,20 @@ export class BadRequest extends CustomError { } } +/** + * @apiDefine PreconditionFailed + * @apiError PreconditionFailed error 412 + * + **/ +export class PreconditionFailed extends CustomError { + constructor (customMessage) { + super(); + this.name = this.constructor.name; + this.httpCode = 412; + this.message = customMessage || 'Precondition failed.'; + } +} + /** * @apiDefine NotFound * @apiError NotFound The requested resource was not found.