move the update username route to v3 (#10836)

This commit is contained in:
Matteo Pagliazzi
2018-11-14 10:40:27 +01:00
committed by Phillip Thelen
parent cc13c4f28e
commit 7d29ae44ba
5 changed files with 157 additions and 332 deletions

View File

@@ -12,14 +12,14 @@ const ENDPOINT = '/user/auth/update-username';
describe('PUT /user/auth/update-username', async () => {
let user;
let newUsername = 'new-username';
let password = 'password'; // from habitrpg/test/helpers/api-integration/v3/object-generators.js
let password = 'password'; // from habitrpg/test/helpers/api-integration/v4/object-generators.js
beforeEach(async () => {
user = await generateUser();
});
it('successfully changes username', async () => {
it('successfully changes username with password', async () => {
let newUsername = 'new-username';
let response = await user.put(ENDPOINT, {
username: newUsername,
password,
@@ -29,6 +29,38 @@ describe('PUT /user/auth/update-username', async () => {
expect(user.auth.local.username).to.eql(newUsername);
});
it('successfully changes username without password', async () => {
let newUsername = 'new-username-nopw';
let response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.auth.local.username).to.eql(newUsername);
});
it('successfully changes username containing number and underscore', async () => {
let newUsername = 'new_username9';
let response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.auth.local.username).to.eql(newUsername);
});
it('sets verifiedUsername when changing username', async () => {
user.flags.verifiedUsername = false;
await user.sync();
let newUsername = 'new-username-verify';
let response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.flags.verifiedUsername).to.eql(true);
});
it('converts user with SHA1 encrypted password to bcrypt encryption', async () => {
let myNewUsername = 'my-new-username';
let textPassword = 'mySecretPassword';
@@ -80,6 +112,7 @@ describe('PUT /user/auth/update-username', async () => {
});
it('errors if password is wrong', async () => {
let newUsername = 'new-username';
await expect(user.put(ENDPOINT, {
username: newUsername,
password: 'wrong-password',
@@ -90,19 +123,6 @@ describe('PUT /user/auth/update-username', async () => {
});
});
it('prevents social-only user from changing username', async () => {
let socialUser = await generateUser({ 'auth.local': { ok: true } });
await expect(socialUser.put(ENDPOINT, {
username: newUsername,
password,
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('userHasNoLocalRegistration'),
});
});
it('errors if new username is not provided', async () => {
await expect(user.put(ENDPOINT, {
password,
@@ -112,5 +132,93 @@ describe('PUT /user/auth/update-username', async () => {
message: t('invalidReqParams'),
});
});
it('errors if new username is a slur', async () => {
await expect(user.put(ENDPOINT, {
username: 'TESTPLACEHOLDERSLURWORDHERE',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
});
it('errors if new username contains a slur', async () => {
await expect(user.put(ENDPOINT, {
username: 'TESTPLACEHOLDERSLURWORDHERE_otherword',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
await expect(user.put(ENDPOINT, {
username: 'something_TESTPLACEHOLDERSLURWORDHERE',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
await expect(user.put(ENDPOINT, {
username: 'somethingTESTPLACEHOLDERSLURWORDHEREotherword',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
});
it('errors if new username is not allowed', async () => {
await expect(user.put(ENDPOINT, {
username: 'support',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueForbidden'),
});
});
it('errors if new username is not allowed regardless of casing', async () => {
await expect(user.put(ENDPOINT, {
username: 'SUppORT',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueForbidden'),
});
});
it('errors if username has incorrect length', async () => {
await expect(user.put(ENDPOINT, {
username: 'thisisaverylongusernameover20characters',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueLength'),
});
});
it('errors if new username contains invalid characters', async () => {
await expect(user.put(ENDPOINT, {
username: 'Eichhörnchen',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueInvalidCharacters'),
});
await expect(user.put(ENDPOINT, {
username: 'test.name',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueInvalidCharacters'),
});
await expect(user.put(ENDPOINT, {
username: '🤬',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueInvalidCharacters'),
});
});
});
});

View File

@@ -1,224 +0,0 @@
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v4';
import {
bcryptCompare,
sha1MakeSalt,
sha1Encrypt as sha1EncryptPassword,
} from '../../../../../website/server/libs/password';
const ENDPOINT = '/user/auth/update-username';
describe('PUT /user/auth/update-username', async () => {
let user;
let password = 'password'; // from habitrpg/test/helpers/api-integration/v4/object-generators.js
beforeEach(async () => {
user = await generateUser();
});
it('successfully changes username with password', async () => {
let newUsername = 'new-username';
let response = await user.put(ENDPOINT, {
username: newUsername,
password,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.auth.local.username).to.eql(newUsername);
});
it('successfully changes username without password', async () => {
let newUsername = 'new-username-nopw';
let response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.auth.local.username).to.eql(newUsername);
});
it('successfully changes username containing number and underscore', async () => {
let newUsername = 'new_username9';
let response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.auth.local.username).to.eql(newUsername);
});
it('sets verifiedUsername when changing username', async () => {
user.flags.verifiedUsername = false;
await user.sync();
let newUsername = 'new-username-verify';
let response = await user.put(ENDPOINT, {
username: newUsername,
});
expect(response).to.eql({ username: newUsername });
await user.sync();
expect(user.flags.verifiedUsername).to.eql(true);
});
it('converts user with SHA1 encrypted password to bcrypt encryption', async () => {
let myNewUsername = 'my-new-username';
let textPassword = 'mySecretPassword';
let salt = sha1MakeSalt();
let sha1HashedPassword = sha1EncryptPassword(textPassword, salt);
await user.update({
'auth.local.hashed_password': sha1HashedPassword,
'auth.local.passwordHashMethod': 'sha1',
'auth.local.salt': salt,
});
await user.sync();
expect(user.auth.local.passwordHashMethod).to.equal('sha1');
expect(user.auth.local.salt).to.equal(salt);
expect(user.auth.local.hashed_password).to.equal(sha1HashedPassword);
// update email
let response = await user.put(ENDPOINT, {
username: myNewUsername,
password: textPassword,
});
expect(response).to.eql({ username: myNewUsername });
await user.sync();
expect(user.auth.local.username).to.eql(myNewUsername);
expect(user.auth.local.passwordHashMethod).to.equal('bcrypt');
expect(user.auth.local.salt).to.be.undefined;
expect(user.auth.local.hashed_password).not.to.equal(sha1HashedPassword);
let isValidPassword = await bcryptCompare(textPassword, user.auth.local.hashed_password);
expect(isValidPassword).to.equal(true);
});
context('errors', async () => {
it('prevents username update if new username is already taken', async () => {
let existingUsername = 'existing-username';
await generateUser({'auth.local.username': existingUsername, 'auth.local.lowerCaseUsername': existingUsername });
await expect(user.put(ENDPOINT, {
username: existingUsername,
password,
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameTaken'),
});
});
it('errors if password is wrong', async () => {
let newUsername = 'new-username';
await expect(user.put(ENDPOINT, {
username: newUsername,
password: 'wrong-password',
})).to.eventually.be.rejected.and.eql({
code: 401,
error: 'NotAuthorized',
message: t('wrongPassword'),
});
});
it('errors if new username is not provided', async () => {
await expect(user.put(ENDPOINT, {
password,
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('invalidReqParams'),
});
});
it('errors if new username is a slur', async () => {
await expect(user.put(ENDPOINT, {
username: 'TESTPLACEHOLDERSLURWORDHERE',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
});
it('errors if new username contains a slur', async () => {
await expect(user.put(ENDPOINT, {
username: 'TESTPLACEHOLDERSLURWORDHERE_otherword',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
await expect(user.put(ENDPOINT, {
username: 'something_TESTPLACEHOLDERSLURWORDHERE',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
await expect(user.put(ENDPOINT, {
username: 'somethingTESTPLACEHOLDERSLURWORDHEREotherword',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: [t('usernameIssueLength'), t('usernameIssueSlur')].join(' '),
});
});
it('errors if new username is not allowed', async () => {
await expect(user.put(ENDPOINT, {
username: 'support',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueForbidden'),
});
});
it('errors if new username is not allowed regardless of casing', async () => {
await expect(user.put(ENDPOINT, {
username: 'SUppORT',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueForbidden'),
});
});
it('errors if username has incorrect length', async () => {
await expect(user.put(ENDPOINT, {
username: 'thisisaverylongusernameover20characters',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueLength'),
});
});
it('errors if new username contains invalid characters', async () => {
await expect(user.put(ENDPOINT, {
username: 'Eichhörnchen',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueInvalidCharacters'),
});
await expect(user.put(ENDPOINT, {
username: 'test.name',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueInvalidCharacters'),
});
await expect(user.put(ENDPOINT, {
username: '🤬',
})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('usernameIssueInvalidCharacters'),
});
});
});
});

View File

@@ -17,10 +17,10 @@ import { encrypt } from '../../libs/encryption';
import {
loginRes,
hasBackupAuth,
hasLocalAuth,
loginSocial,
registerLocal,
} from '../../libs/auth';
import {verifyUsername} from '../../libs/user/validation';
const BASE_URL = nconf.get('BASE_URL');
const TECH_ASSISTANCE_EMAIL = nconf.get('EMAILS:TECH_ASSISTANCE_EMAIL');
@@ -144,7 +144,6 @@ api.loginSocial = {
* @apiName UpdateUsername
* @apiGroup User
*
* @apiParam (Body) {String} password The current user password
* @apiParam (Body) {String} username The new username
* @apiSuccess {String} data.username The new username
@@ -154,37 +153,55 @@ api.updateUsername = {
middlewares: [authWithHeaders()],
url: '/user/auth/update-username',
async handler (req, res) {
let user = res.locals.user;
const user = res.locals.user;
req.checkBody({
password: {
notEmpty: {errorMessage: res.t('missingPassword')},
},
username: {
notEmpty: {errorMessage: res.t('missingUsername')},
},
});
let validationErrors = req.validationErrors();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
if (!hasLocalAuth(user)) throw new BadRequest(res.t('userHasNoLocalRegistration'));
const newUsername = req.body.username;
let password = req.body.password;
const issues = verifyUsername(newUsername, res);
if (issues.length > 0) throw new BadRequest(issues.join(' '));
const password = req.body.password;
if (password !== undefined) {
let isValidPassword = await passwordUtils.compare(user, password);
if (!isValidPassword) throw new NotAuthorized(res.t('wrongPassword'));
}
let count = await User.count({ 'auth.local.lowerCaseUsername': req.body.username.toLowerCase() });
if (count > 0) throw new BadRequest(res.t('usernameTaken'));
const existingUser = await User.findOne({ 'auth.local.lowerCaseUsername': newUsername.toLowerCase() }, {auth: 1}).exec();
if (existingUser !== undefined && existingUser !== null && existingUser._id !== user._id) {
throw new BadRequest(res.t('usernameTaken'));
}
// if password is using old sha1 encryption, change it
if (user.auth.local.passwordHashMethod === 'sha1') {
if (user.auth.local.passwordHashMethod === 'sha1' && password !== undefined) {
await passwordUtils.convertToBcrypt(user, password); // user is saved a few lines below
}
// save username
user.auth.local.lowerCaseUsername = req.body.username.toLowerCase();
user.auth.local.username = req.body.username;
user.auth.local.lowerCaseUsername = newUsername.toLowerCase();
user.auth.local.username = newUsername;
if (!user.flags.verifiedUsername) {
user.flags.verifiedUsername = true;
if (user.items.pets['Bear-Veteran']) {
user.items.pets['Fox-Veteran'] = 5;
} else if (user.items.pets['Lion-Veteran']) {
user.items.pets['Bear-Veteran'] = 5;
} else if (user.items.pets['Tiger-Veteran']) {
user.items.pets['Lion-Veteran'] = 5;
} else if (user.items.pets['Wolf-Veteran']) {
user.items.pets['Tiger-Veteran'] = 5;
} else {
user.items.pets['Wolf-Veteran'] = 5;
}
}
await user.save();
res.respond(200, { username: req.body.username });

View File

@@ -2,86 +2,11 @@ import {
authWithHeaders,
} from '../../middlewares/auth';
import * as authLib from '../../libs/auth';
import {
NotAuthorized,
BadRequest,
} from '../../libs/errors';
import * as passwordUtils from '../../libs/password';
import { model as User } from '../../models/user';
import {verifyUsername} from '../../libs/user/validation';
const api = {};
/**
* @api {put} /api/v4/user/auth/update-username Update username
* @apiDescription Update the username of a local user
* @apiName UpdateUsername
* @apiGroup User
*
* @apiParam (Body) {String} username The new username
* @apiSuccess {String} data.username The new username
**/
api.updateUsername = {
method: 'PUT',
middlewares: [authWithHeaders()],
url: '/user/auth/update-username',
async handler (req, res) {
const user = res.locals.user;
req.checkBody({
username: {
notEmpty: {errorMessage: res.t('missingUsername')},
},
});
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const newUsername = req.body.username;
const issues = verifyUsername(newUsername, res);
if (issues.length > 0) throw new BadRequest(issues.join(' '));
const password = req.body.password;
if (password !== undefined) {
let isValidPassword = await passwordUtils.compare(user, password);
if (!isValidPassword) throw new NotAuthorized(res.t('wrongPassword'));
}
const existingUser = await User.findOne({ 'auth.local.lowerCaseUsername': newUsername.toLowerCase() }, {auth: 1}).exec();
if (existingUser !== undefined && existingUser !== null && existingUser._id !== user._id) {
throw new BadRequest(res.t('usernameTaken'));
}
// if password is using old sha1 encryption, change it
if (user.auth.local.passwordHashMethod === 'sha1' && password !== undefined) {
await passwordUtils.convertToBcrypt(user, password); // user is saved a few lines below
}
// save username
user.auth.local.lowerCaseUsername = newUsername.toLowerCase();
user.auth.local.username = newUsername;
if (!user.flags.verifiedUsername) {
user.flags.verifiedUsername = true;
if (user.items.pets['Bear-Veteran']) {
user.items.pets['Fox-Veteran'] = 5;
} else if (user.items.pets['Lion-Veteran']) {
user.items.pets['Bear-Veteran'] = 5;
} else if (user.items.pets['Tiger-Veteran']) {
user.items.pets['Lion-Veteran'] = 5;
} else if (user.items.pets['Wolf-Veteran']) {
user.items.pets['Tiger-Veteran'] = 5;
} else {
user.items.pets['Wolf-Veteran'] = 5;
}
}
await user.save();
res.respond(200, { username: req.body.username });
},
};
api.verifyUsername = {
method: 'POST',
url: '/user/auth/verify-username',

View File

@@ -34,7 +34,6 @@ app.use('/api/v3', v3Router);
// A list of v3 routes in the format METHOD-URL to skip
const v4RouterOverrides = [
// 'GET-/status', Example to override the GET /status api call
'PUT-/user/auth/update-username',
'POST-/user/auth/local/register',
'GET-/user',
'PUT-/user',