update user modify for unique usernames

This commit is contained in:
Puyodead1
2023-06-14 11:37:17 -04:00
committed by Rory&
parent 9a415989b1
commit 08fcec36ba
6 changed files with 80 additions and 31 deletions

View File

@@ -61,6 +61,8 @@ router.patch(
}),
async (req: Request, res: Response) => {
const body = req.body as UserModifySchema;
const { uniqueUsernames } = Config.get().general;
const { minUsername, maxUsername } = Config.get().limits.user;
const user = await User.findOneOrFail({
where: { id: req.user_id },
@@ -120,9 +122,53 @@ router.patch(
newToken = (await generateToken(user.id)) as string;
}
// TODO: uniqueUsernames: disallow if uniqueUsernames is enabled
if (body.username) {
const check_username = body?.username?.replace(/\s/g, "").trim();
// password is required to update username
if (!body.password)
throw FieldErrors({
password: {
message: req.t("common:field.PASSWORD_DOES_NOT_MATCH"),
code: "PASSWORD_DOES_NOT_MATCH",
},
});
// handle username changes (pomelo)
if (uniqueUsernames) {
body.username = body.username.toLowerCase();
// validate username length
if (
body.username.length < minUsername ||
body.username.length > maxUsername
) {
throw FieldErrors({
username: {
code: "BASE_TYPE_BAD_LENGTH",
message: req.t(
"common:field.BASE_TYPE_BAD_LENGTH",
{ length: `${minUsername} and ${maxUsername}` },
),
},
});
}
// check if username is already taken (pomelo only)
const userCount = await User.count({
where: { username: body.username },
});
if (userCount > 0) {
throw FieldErrors({
username: {
code: "USERNAME_ALREADY_TAKEN",
message: req.t(
"common:field.USERNAME_ALREADY_TAKEN",
),
},
});
}
}
// handle username changes (old username system)
const check_username = body?.username?.replace(/\s/g, "");
if (!check_username) {
throw FieldErrors({
username: {
@@ -132,8 +178,7 @@ router.patch(
});
}
const { maxUsername } = Config.get().limits.user;
if (check_username.length > maxUsername || check_username.length < 2) {
if (check_username.length > maxUsername) {
throw FieldErrors({
username: {
code: "BASE_TYPE_BAD_LENGTH",
@@ -152,8 +197,18 @@ router.patch(
}
}
// TODO: uniqueUsernames: disallow if uniqueUsernames is enabled
if (body.discriminator) {
if (uniqueUsernames) {
throw FieldErrors({
username: {
code: "DISCRIMINATOR_UPDATE_BLOCKED",
message: req.t(
"common:field.DISCRIMINATOR_UPDATE_BLOCKED",
),
},
});
}
if (
await User.findOne({
where: {
@@ -165,7 +220,7 @@ router.patch(
throw FieldErrors({
discriminator: {
code: "INVALID_DISCRIMINATOR",
message: "This discriminator is already in use.",
message: req.t("common.field.INVALID_DISCRIMINATOR"),
},
});
}