diff --git a/prisma/migrations/20250418153435_username_updated_at/migration.sql b/prisma/migrations/20250418153435_username_updated_at/migration.sql new file mode 100644 index 0000000..4f84f6c --- /dev/null +++ b/prisma/migrations/20250418153435_username_updated_at/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "users" ADD COLUMN "usernameUpdatedAt" TIMESTAMP(3); diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml index 648c57f..044d57c 100644 --- a/prisma/migrations/migration_lock.toml +++ b/prisma/migrations/migration_lock.toml @@ -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" \ No newline at end of file +provider = "postgresql" diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 0b10cfe..330641a 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -18,6 +18,8 @@ model User { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt + usernameUpdatedAt DateTime? + accounts Account[] sessions Session[] miis Mii[] diff --git a/src/app/api/auth/username/route.ts b/src/app/api/auth/username/route.ts index ff106f6..afccb68 100644 --- a/src/app/api/auth/username/route.ts +++ b/src/app/api/auth/username/route.ts @@ -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);