Prevent username reusing

This commit is contained in:
syuilo
2019-07-22 10:15:00 +09:00
parent 3432d6e615
commit 85008303f5
7 changed files with 59 additions and 3 deletions

View File

@ -1,6 +1,6 @@
import $ from 'cafy';
import define from '../../define';
import { Users } from '../../../../models';
import { Users, UsedUsernames } from '../../../../models';
export const meta = {
tags: ['users'],
@ -21,7 +21,9 @@ export default define(meta, async (ps) => {
usernameLower: ps.username.toLowerCase()
});
const exist2 = await UsedUsernames.count({ username: ps.username.toLowerCase() });
return {
available: exist === 0
available: exist === 0 && exist2 === 0
};
});

View File

@ -5,7 +5,7 @@ import generateUserToken from '../common/generate-native-user-token';
import config from '../../../config';
import { fetchMeta } from '../../../misc/fetch-meta';
import * as recaptcha from 'recaptcha-promise';
import { Users, Signins, RegistrationTickets } from '../../../models';
import { Users, Signins, RegistrationTickets, UsedUsernames } from '../../../models';
import { genId } from '../../../misc/gen-id';
import { usersChart } from '../../../services/chart';
import { User } from '../../../models/entities/user';
@ -13,6 +13,7 @@ import { UserKeypair } from '../../../models/entities/user-keypair';
import { toPunyNullable } from '../../../misc/convert-host';
import { UserProfile } from '../../../models/entities/user-profile';
import { getConnection } from 'typeorm';
import { UsedUsername } from '../../../models/entities/used-username';
export default async (ctx: Koa.BaseContext) => {
const body = ctx.request.body as any;
@ -78,11 +79,18 @@ export default async (ctx: Koa.BaseContext) => {
// Generate secret
const secret = generateUserToken();
// Check username duplication
if (await Users.findOne({ usernameLower: username.toLowerCase(), host: null })) {
ctx.status = 400;
return;
}
// Check deleted username duplication
if (await UsedUsernames.findOne({ username: username.toLowerCase() })) {
ctx.status = 400;
return;
}
const keyPair = await new Promise<string[]>((s, j) =>
generateKeyPair('rsa', {
modulusLength: 4096,
@ -133,6 +141,10 @@ export default async (ctx: Koa.BaseContext) => {
autoWatch: false,
password: hash,
}));
await transactionalEntityManager.save(new UsedUsername({
username: username.toLowerCase(),
}));
});
usersChart.update(account, true);