feat: username 90-day change restriction

This commit is contained in:
trafficlunar 2025-04-18 16:47:31 +01:00
parent d95d8c2dd6
commit 10f1fc2fb3
4 changed files with 16 additions and 2 deletions

View file

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "users" ADD COLUMN "usernameUpdatedAt" TIMESTAMP(3);

View file

@ -1,3 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
provider = "postgresql"

View file

@ -18,6 +18,8 @@ model User {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
usernameUpdatedAt DateTime?
accounts Account[]
sessions Session[]
miis Mii[]

View file

@ -3,6 +3,7 @@ import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { usernameSchema } from "@/lib/schemas";
import dayjs from "dayjs";
export async function PATCH(request: NextRequest) {
const session = await auth();
@ -11,6 +12,15 @@ export async function PATCH(request: NextRequest) {
const { username } = await request.json();
if (!username) return NextResponse.json({ error: "New username is required" }, { status: 400 });
// Check if username was updated in the last 90 days
const user = await prisma.user.findUnique({ where: { email: session.user?.email ?? undefined } });
if (user && user.usernameUpdatedAt) {
const timePeriod = dayjs().subtract(90, "days");
const lastUpdate = dayjs(user.usernameUpdatedAt);
if (lastUpdate.isAfter(timePeriod)) return NextResponse.json({ error: "Username was changed in the last 90 days" }, { status: 400 });
}
const validation = usernameSchema.safeParse(username);
if (!validation.success) return NextResponse.json({ error: validation.error.errors[0].message }, { status: 400 });
@ -20,7 +30,7 @@ export async function PATCH(request: NextRequest) {
try {
await prisma.user.update({
where: { email: session.user?.email ?? undefined },
data: { username },
data: { username, usernameUpdatedAt: new Date() },
});
} catch (error) {
console.error("Failed to update username:", error);