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

@@ -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',