/user/update-email endpoint

This commit is contained in:
Victor Piousbox
2016-03-04 21:27:16 +00:00
parent 2b8846b803
commit 7dfdbb8b05
6 changed files with 138 additions and 3 deletions

View File

@@ -4,8 +4,10 @@
"missingEmail": "Missing email.", "missingEmail": "Missing email.",
"missingUsername": "Missing username.", "missingUsername": "Missing username.",
"missingPassword": "Missing password.", "missingPassword": "Missing password.",
"wrongPassword": "Wrong password.",
"notAnEmail": "Invalid email address.", "notAnEmail": "Invalid email address.",
"emailTaken": "Email already taken.", "emailTaken": "Email already taken.",
"newEmailRequired": "The newEmail body parameter is required.",
"usernameTaken": "Username already taken.", "usernameTaken": "Username already taken.",
"passwordConfirmationMatch": "Password confirmation doesn't match password.", "passwordConfirmationMatch": "Password confirmation doesn't match password.",
"invalidLoginCredentials": "Incorrect username / email and / or password.", "invalidLoginCredentials": "Incorrect username / email and / or password.",
@@ -64,6 +66,7 @@
"userAlreadyPendingInvitation": "User already pending invitation.", "userAlreadyPendingInvitation": "User already pending invitation.",
"userAlreadyInAParty": "User already in a party.", "userAlreadyInAParty": "User already in a party.",
"userWithIDNotFound": "User with id \"<%= userId %>\" not found.", "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.", "uuidsMustBeAnArray": "UUIDs invites must be a an Array.",
"emailsMustBeAnArray": "Email invites must be a an Array.", "emailsMustBeAnArray": "Email invites must be a an Array.",
"canOnlyInviteMaxInvites": "You can only invite \"<%= maxInvites %>\" at a time", "canOnlyInviteMaxInvites": "You can only invite \"<%= maxInvites %>\" at a time",

View File

@@ -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'),
});
});
});
});

View File

@@ -7,7 +7,7 @@ import { isEmpty, cloneDeep } from 'lodash';
const API_TEST_SERVER_PORT = nconf.get('PORT'); const API_TEST_SERVER_PORT = nconf.get('PORT');
let apiVersion; 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 // If a user is passed in, the uuid and api token of
// the user are used to make the requests // the user are used to make the requests
export function requester (user = {}, additionalSets = {}) { export function requester (user = {}, additionalSets = {}) {

View File

@@ -8,10 +8,11 @@ import {
let api = {}; 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 * @apiVersion 3.0.0
* @apiName UnsubscribeEmail * @apiName UnsubscribeEmail
* @apiGroup Unsubscribe * @apiGroup Unsubscribe
* @apiDescription This is a GET method so that you can put the unsubscribe link in emails.
* *
* @apiParam {String} code An unsubscription code * @apiParam {String} code An unsubscription code
* *

View File

@@ -1,6 +1,12 @@
import { authWithHeaders } from '../../middlewares/api-v3/auth'; import { authWithHeaders } from '../../middlewares/api-v3/auth';
import cron from '../../middlewares/api-v3/cron'; import cron from '../../middlewares/api-v3/cron';
import common from '../../../../common'; import common from '../../../../common';
import {
PreconditionFailed,
BadRequest,
NotAuthorized,
} from '../../libs/api-v3/errors';
import * as passwordUtils from '../../libs/api-v3/password';
let api = {}; let api = {};
@@ -19,7 +25,7 @@ api.getUser = {
async handler (req, res) { async handler (req, res) {
let user = res.locals.user.toJSON(); 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; delete user.apiToken;
// TODO move to model (maybe virtuals, maybe in toJSON) // 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; export default api;

View File

@@ -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 * @apiDefine NotFound
* @apiError NotFound The requested resource was not found. * @apiError NotFound The requested resource was not found.