feat: remove usernames

This commit is contained in:
trafficlunar 2026-03-24 22:09:00 +00:00
parent 6453788ec3
commit 8fffa1c9cc
42 changed files with 153 additions and 389 deletions

View file

@ -0,0 +1,16 @@
/*
Warnings:
- You are about to drop the column `username` on the `users` table. All the data in the column will be lost.
- You are about to drop the column `usernameUpdatedAt` on the `users` table. All the data in the column will be lost.
*/
-- DropIndex
DROP INDEX "users_username_key";
-- AlterTable
ALTER TABLE "miis" ALTER COLUMN "allowedCopying" DROP NOT NULL;
-- AlterTable
ALTER TABLE "users" DROP COLUMN "username",
DROP COLUMN "usernameUpdatedAt";

View file

@ -9,7 +9,6 @@ datasource db {
model User { model User {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
username String? @unique
name String name String
email String @unique email String @unique
emailVerified DateTime? emailVerified DateTime?
@ -19,7 +18,6 @@ model User {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
usernameUpdatedAt DateTime?
imageUpdatedAt DateTime? imageUpdatedAt DateTime?
accounts Account[] accounts Account[]

View file

@ -21,7 +21,7 @@ export const metadata: Metadata = {
export default async function AdminPage() { export default async function AdminPage() {
const session = await auth(); const session = await auth();
if (!session || Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) redirect("/404"); if (!session || Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) redirect("/404");
return ( return (
<div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex flex-col gap-4"> <div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex flex-col gap-4">

View file

@ -11,7 +11,7 @@ export async function POST(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await request.text(); const body = await request.text();
bannerText = body; bannerText = body;
@ -23,7 +23,7 @@ export async function DELETE() {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
bannerText = null; bannerText = null;
return NextResponse.json({ success: true }); return NextResponse.json({ success: true });

View file

@ -12,7 +12,7 @@ export async function PATCH(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await request.json(); const body = await request.json();
const validatedCanSubmit = z.boolean().safeParse(body); const validatedCanSubmit = z.boolean().safeParse(body);

View file

@ -8,7 +8,7 @@ export async function GET(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
const parsed = idSchema.safeParse(searchParams.get("id")); const parsed = idSchema.safeParse(searchParams.get("id"));
@ -51,7 +51,6 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ return NextResponse.json({
success: true, success: true,
name: user.name, name: user.name,
username: user.username,
image: user.image, image: user.image,
createdAt: user.createdAt, createdAt: user.createdAt,
punishments: user.punishments, punishments: user.punishments,

View file

@ -30,7 +30,7 @@ export async function POST(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
const parsedUserId = idSchema.safeParse(searchParams.get("id")); const parsedUserId = idSchema.safeParse(searchParams.get("id"));
@ -69,7 +69,7 @@ export async function DELETE(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
const parsedPunishmentId = idSchema.safeParse(searchParams.get("id")); const parsedPunishmentId = idSchema.safeParse(searchParams.get("id"));

View file

@ -7,7 +7,7 @@ export async function PATCH() {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (Number(session.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); if (Number(session.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
// Start processing in background // Start processing in background
regenerateImages().catch(console.error); regenerateImages().catch(console.error);

View file

@ -10,7 +10,7 @@ import { RateLimit } from "@/lib/rate-limit";
export async function PATCH(request: NextRequest) { export async function PATCH(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 3); const rateLimit = new RateLimit(request, 3);
const check = await rateLimit.handle(); const check = await rateLimit.handle();
@ -24,7 +24,7 @@ export async function PATCH(request: NextRequest) {
try { try {
await prisma.user.update({ await prisma.user.update({
where: { id: Number(session.user.id) }, where: { id: Number(session.user?.id) },
data: { description: profanity.censor(description) }, data: { description: profanity.censor(description) },
}); });
} catch (error) { } catch (error) {

View file

@ -8,7 +8,7 @@ import { RateLimit } from "@/lib/rate-limit";
export async function DELETE(request: NextRequest) { export async function DELETE(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session || !session.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session || !session.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user.id, name: session.user.name });
const rateLimit = new RateLimit(request, 1); const rateLimit = new RateLimit(request, 1);
const check = await rateLimit.handle(); const check = await rateLimit.handle();

View file

@ -1,40 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import * as Sentry from "@sentry/nextjs";
import { profanity } from "@2toad/profanity";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { displayNameSchema } from "@/lib/schemas";
import { RateLimit } from "@/lib/rate-limit";
export async function PATCH(request: NextRequest) {
const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username });
const rateLimit = new RateLimit(request, 3);
const check = await rateLimit.handle();
if (check) return check;
const { displayName } = await request.json();
if (!displayName) return rateLimit.sendResponse({ error: "New display name is required" }, 400);
const validation = displayNameSchema.safeParse(displayName);
if (!validation.success) return rateLimit.sendResponse({ error: validation.error.issues[0].message }, 400);
// Check for inappropriate words
if (profanity.exists(displayName)) return rateLimit.sendResponse({ error: "Display name contains inappropriate words" }, 400);
try {
await prisma.user.update({
where: { id: Number(session.user.id) },
data: { name: displayName },
});
} catch (error) {
console.error("Failed to update display name:", error);
Sentry.captureException(error, { extra: { stage: "update-display-name" } });
return rateLimit.sendResponse({ error: "Failed to update display name" }, 500);
}
return rateLimit.sendResponse({ success: true });
}

View file

@ -0,0 +1,40 @@
import { NextRequest, NextResponse } from "next/server";
import * as Sentry from "@sentry/nextjs";
import { profanity } from "@2toad/profanity";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { userNameSchema } from "@/lib/schemas";
import { RateLimit } from "@/lib/rate-limit";
export async function PATCH(request: NextRequest) {
const session = await auth();
if (!session || !session.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, name: session.user.name });
const rateLimit = new RateLimit(request, 3);
const check = await rateLimit.handle();
if (check) return check;
const { name } = await request.json();
if (!name) return rateLimit.sendResponse({ error: "New name is required" }, 400);
const validation = userNameSchema.safeParse(name);
if (!validation.success) return rateLimit.sendResponse({ error: validation.error.issues[0].message }, 400);
// Check for inappropriate words
if (profanity.exists(name)) return rateLimit.sendResponse({ error: "Name contains inappropriate words" }, 400);
try {
await prisma.user.update({
where: { id: Number(session.user.id) },
data: { name },
});
} catch (error) {
console.error("Failed to update name:", error);
Sentry.captureException(error, { extra: { stage: "update-name" } });
return rateLimit.sendResponse({ error: "Failed to update name" }, 500);
}
return rateLimit.sendResponse({ success: true });
}

View file

@ -21,14 +21,14 @@ const formDataSchema = z.object({
export async function PATCH(request: NextRequest) { export async function PATCH(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 3); const rateLimit = new RateLimit(request, 3);
const check = await rateLimit.handle(); const check = await rateLimit.handle();
if (check) return check; if (check) return check;
// Check if profile picture was updated in the last 7 days // Check if profile picture was updated in the last 7 days
const user = await prisma.user.findUnique({ where: { id: Number(session.user.id) } }); const user = await prisma.user.findUnique({ where: { id: Number(session.user?.id) } });
if (user && user.imageUpdatedAt) { if (user && user.imageUpdatedAt) {
const timePeriod = dayjs().subtract(7, "days"); const timePeriod = dayjs().subtract(7, "days");
const lastUpdate = dayjs(user.imageUpdatedAt); const lastUpdate = dayjs(user.imageUpdatedAt);
@ -48,7 +48,7 @@ export async function PATCH(request: NextRequest) {
// If there is no image, set the profile picture to the guest image // If there is no image, set the profile picture to the guest image
if (!image) { if (!image) {
await prisma.user.update({ await prisma.user.update({
where: { id: Number(session.user.id) }, where: { id: Number(session.user?.id) },
data: { image: `/guest.png`, imageUpdatedAt: new Date() }, data: { image: `/guest.png`, imageUpdatedAt: new Date() },
}); });
@ -65,7 +65,7 @@ export async function PATCH(request: NextRequest) {
try { try {
const buffer = Buffer.from(await image.arrayBuffer()); const buffer = Buffer.from(await image.arrayBuffer());
const pngBuffer = await sharp(buffer, { animated: true }).resize({ width: 128, height: 128 }).png({ quality: 85 }).toBuffer(); const pngBuffer = await sharp(buffer, { animated: true }).resize({ width: 128, height: 128 }).png({ quality: 85 }).toBuffer();
const fileLocation = path.join(uploadsDirectory, `${session.user.id}.png`); const fileLocation = path.join(uploadsDirectory, `${session.user?.id}.png`);
await fs.writeFile(fileLocation, pngBuffer); await fs.writeFile(fileLocation, pngBuffer);
} catch (error) { } catch (error) {
@ -76,8 +76,8 @@ export async function PATCH(request: NextRequest) {
try { try {
await prisma.user.update({ await prisma.user.update({
where: { id: Number(session.user.id) }, where: { id: Number(session.user?.id) },
data: { image: `/profile/${session.user.id}/picture`, imageUpdatedAt: new Date() }, data: { image: `/profile/${session.user?.id}/picture`, imageUpdatedAt: new Date() },
}); });
} catch (error) { } catch (error) {
console.error("Failed to update profile picture:", error); console.error("Failed to update profile picture:", error);

View file

@ -1,54 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import * as Sentry from "@sentry/nextjs";
import dayjs from "dayjs";
import { profanity } from "@2toad/profanity";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { usernameSchema } from "@/lib/schemas";
import { RateLimit } from "@/lib/rate-limit";
export async function PATCH(request: NextRequest) {
const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username });
const rateLimit = new RateLimit(request, 3);
const check = await rateLimit.handle();
if (check) return check;
const { username } = await request.json();
if (!username) return rateLimit.sendResponse({ error: "New username is required" }, 400);
// Check if username was updated in the last 90 days
const user = await prisma.user.findUnique({ where: { id: Number(session.user.id) } });
if (user && user.usernameUpdatedAt) {
const timePeriod = dayjs().subtract(90, "days");
const lastUpdate = dayjs(user.usernameUpdatedAt);
if (lastUpdate.isAfter(timePeriod)) return rateLimit.sendResponse({ error: "Username was changed in the last 90 days" }, 400);
}
const validation = usernameSchema.safeParse(username);
if (!validation.success) return rateLimit.sendResponse({ error: validation.error.issues[0].message }, 400);
// Check for inappropriate words
if (profanity.exists(username)) return rateLimit.sendResponse({ error: "Username contains inappropriate words" }, 400);
const existingUser = await prisma.user.findUnique({ where: { username } });
if (existingUser) return rateLimit.sendResponse({ error: "Username is already taken" }, 400);
try {
await prisma.user.update({
where: { id: Number(session.user.id) },
data: { username, usernameUpdatedAt: new Date() },
});
} catch (error) {
console.error("Failed to update username:", error);
Sentry.captureException(error, { extra: { stage: "update-username" } });
return rateLimit.sendResponse({ error: "Failed to update username" }, 500);
}
return rateLimit.sendResponse({ success: true });
}

View file

@ -14,7 +14,7 @@ const uploadsDirectory = path.join(process.cwd(), "uploads", "mii");
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 30, "/api/mii/delete"); const rateLimit = new RateLimit(request, 30, "/api/mii/delete");
const check = await rateLimit.handle(); const check = await rateLimit.handle();
@ -33,7 +33,7 @@ export async function DELETE(request: NextRequest, { params }: { params: Promise
}); });
if (!mii) return rateLimit.sendResponse({ error: "Mii not found" }, 404); if (!mii) return rateLimit.sendResponse({ error: "Mii not found" }, 404);
if (!(Number(session.user.id) === mii.userId || Number(session.user.id) === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID))) if (!(Number(session.user?.id) === mii.userId || Number(session.user?.id) === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)))
return rateLimit.sendResponse({ error: "You don't have ownership of that Mii" }, 403); return rateLimit.sendResponse({ error: "You don't have ownership of that Mii" }, 403);
const miiUploadsDirectory = path.join(uploadsDirectory, miiId.toString()); const miiUploadsDirectory = path.join(uploadsDirectory, miiId.toString());

View file

@ -29,7 +29,7 @@ const editSchema = z.object({
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 1); // no grouped pathname; edit each mii 1 time a minute const rateLimit = new RateLimit(request, 1); // no grouped pathname; edit each mii 1 time a minute
const check = await rateLimit.handle(); const check = await rateLimit.handle();
@ -49,7 +49,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
}); });
if (!mii) return rateLimit.sendResponse({ error: "Mii not found" }, 404); if (!mii) return rateLimit.sendResponse({ error: "Mii not found" }, 404);
if (!(Number(session.user.id) === mii.userId || Number(session.user.id) === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID))) if (!(Number(session.user?.id) === mii.userId || Number(session.user?.id) === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)))
return rateLimit.sendResponse({ error: "You don't have ownership of that Mii" }, 403); return rateLimit.sendResponse({ error: "You don't have ownership of that Mii" }, 403);
// Parse form data // Parse form data

View file

@ -22,7 +22,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
const existingLike = await tx.like.findUnique({ const existingLike = await tx.like.findUnique({
where: { where: {
userId_miiId: { userId_miiId: {
userId: Number(session.user.id), userId: Number(session.user?.id),
miiId, miiId,
}, },
}, },
@ -33,7 +33,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
await tx.like.delete({ await tx.like.delete({
where: { where: {
userId_miiId: { userId_miiId: {
userId: Number(session.user.id), userId: Number(session.user?.id),
miiId, miiId,
}, },
}, },
@ -42,7 +42,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
// Add a like if it doesn't exist // Add a like if it doesn't exist
await tx.like.create({ await tx.like.create({
data: { data: {
userId: Number(session.user.id), userId: Number(session.user?.id),
miiId, miiId,
}, },
}); });

View file

@ -19,7 +19,7 @@ const reportSchema = z.object({
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 2); const rateLimit = new RateLimit(request, 2);
const check = await rateLimit.handle(); const check = await rateLimit.handle();
@ -35,7 +35,7 @@ export async function POST(request: NextRequest) {
include: { include: {
user: { user: {
select: { select: {
username: true; name: true;
}; };
}; };
}; };
@ -48,7 +48,7 @@ export async function POST(request: NextRequest) {
include: { include: {
user: { user: {
select: { select: {
username: true, name: true,
}, },
}, },
}, },
@ -66,7 +66,7 @@ export async function POST(request: NextRequest) {
where: { where: {
targetId: id, targetId: id,
reportType: type.toUpperCase() as ReportType, reportType: type.toUpperCase() as ReportType,
authorId: Number(session.user.id), authorId: Number(session.user?.id),
}, },
}); });
@ -79,7 +79,7 @@ export async function POST(request: NextRequest) {
targetId: id, targetId: id,
reason: reason.toUpperCase() as ReportReason, reason: reason.toUpperCase() as ReportReason,
reasonNotes: notes, reasonNotes: notes,
authorId: Number(session.user.id), authorId: Number(session.user?.id),
creatorId: mii ? mii.userId : undefined, creatorId: mii ? mii.userId : undefined,
}, },
}); });
@ -92,11 +92,11 @@ export async function POST(request: NextRequest) {
// Send notification to ntfy // Send notification to ntfy
if (process.env.NTFY_URL) { if (process.env.NTFY_URL) {
// This is only shown if report type is MII // This is only shown if report type is MII
const miiCreatorMessage = mii ? `by @${mii.user.username} (ID: ${mii.userId})` : ""; const miiCreatorMessage = mii ? `by ${mii.user.name} (ID: ${mii.userId})` : "";
await fetch(process.env.NTFY_URL, { await fetch(process.env.NTFY_URL, {
method: "POST", method: "POST",
body: `Report by @${session.user.username} (ID: ${session.user.id}) on ${type.toUpperCase()} (ID: ${id}) ${miiCreatorMessage}`, body: `Report by ${session.user?.name} (ID: ${session.user?.id}) on ${type.toUpperCase()} (ID: ${id}) ${miiCreatorMessage}`,
headers: { headers: {
Title: "Report recieved - TomodachiShare", Title: "Report recieved - TomodachiShare",
Priority: "urgent", Priority: "urgent",

View file

@ -14,7 +14,7 @@ export async function DELETE(request: NextRequest) {
const activePunishment = await prisma.punishment.findFirst({ const activePunishment = await prisma.punishment.findFirst({
where: { where: {
userId: Number(session.user.id), userId: Number(session.user?.id),
returned: false, returned: false,
}, },
include: { include: {

View file

@ -37,7 +37,7 @@ const submitSchema = z.object({
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const session = await auth(); const session = await auth();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user.id, username: session.user.username }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 2); const rateLimit = new RateLimit(request, 2);
const check = await rateLimit.handle(); const check = await rateLimit.handle();
@ -108,7 +108,7 @@ export async function POST(request: NextRequest) {
// Create Mii in database // Create Mii in database
const miiRecord = await prisma.mii.create({ const miiRecord = await prisma.mii.create({
data: { data: {
userId: Number(session.user.id), userId: Number(session.user?.id),
name, name,
tags, tags,
description, description,
@ -169,7 +169,7 @@ export async function POST(request: NextRequest) {
const codeFileLocation = path.join(miiUploadsDirectory, "qr-code.png"); const codeFileLocation = path.join(miiUploadsDirectory, "qr-code.png");
await fs.writeFile(codeFileLocation, codePngBuffer); await fs.writeFile(codeFileLocation, codePngBuffer);
await generateMetadataImage(miiRecord, session.user.name!); await generateMetadataImage(miiRecord, session.user?.name!);
} catch (error) { } catch (error) {
// Clean up if something went wrong // Clean up if something went wrong
await prisma.mii.delete({ where: { id: miiRecord.id } }); await prisma.mii.delete({ where: { id: miiRecord.id } });

View file

@ -1,38 +0,0 @@
import { Metadata } from "next";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import UsernameForm from "@/components/username-form";
export const metadata: Metadata = {
title: "Create your Username - TomodachiShare",
description: "Pick a unique username to start using TomodachiShare",
robots: {
index: false,
follow: false,
},
};
export default async function CreateUsernamePage() {
const session = await auth();
// If the user is not logged in or already has a username, redirect
if (!session || session?.user.username) {
redirect("/");
}
return (
<div className="grow flex items-center justify-center">
<div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg px-10 py-12 max-w-md text-center">
<h1 className="text-3xl font-bold mb-4">Welcome to the island!</h1>
<div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mb-6">
<hr className="grow border-zinc-300" />
<span>Please create a username</span>
<hr className="grow border-zinc-300" />
</div>
<UsernameForm />
</div>
</div>
);
}

View file

@ -44,7 +44,7 @@ export default async function MiiPage({ params }: Props) {
}); });
// Check ownership // Check ownership
if (!mii || (Number(session?.user.id) !== mii.userId && Number(session?.user.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID))) redirect("/404"); if (!mii || (Number(session?.user?.id) !== mii.userId && Number(session?.user?.id) !== Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID))) redirect("/404");
return <EditForm mii={mii} likes={mii._count.likedBy} />; return <EditForm mii={mii} likes={mii._count.likedBy} />;
} }

View file

@ -12,9 +12,7 @@ export default async function LoginPage() {
const session = await auth(); const session = await auth();
// If the user is already logged in, redirect // If the user is already logged in, redirect
if (session) { if (session) redirect("/");
redirect("/");
}
return ( return (
<div className="grow flex items-center justify-center"> <div className="grow flex items-center justify-center">

View file

@ -30,7 +30,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
include: { include: {
user: { user: {
select: { select: {
username: true, name: true,
}, },
}, },
_count: { _count: {
@ -44,28 +44,28 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const metadataImageUrl = `/mii/${mii.id}/image?type=metadata`; const metadataImageUrl = `/mii/${mii.id}/image?type=metadata`;
const username = `@${mii.user.username}`; const name = `@${mii.user.name}`;
return { return {
metadataBase: new URL(process.env.NEXT_PUBLIC_BASE_URL!), metadataBase: new URL(process.env.NEXT_PUBLIC_BASE_URL!),
title: `${mii.name} - TomodachiShare`, title: `${mii.name} - TomodachiShare`,
description: `Check out '${mii.name}', a Tomodachi Life Mii created by ${username} on TomodachiShare. From ${mii.islandName} Island with ${mii._count.likedBy} likes.`, description: `Check out '${mii.name}', a Tomodachi Life Mii created by ${name} on TomodachiShare. From ${mii.islandName} Island with ${mii._count.likedBy} likes.`,
keywords: ["mii", "tomodachi life", "nintendo", "tomodachishare", "tomodachi-share", "mii creator", "mii collection", ...mii.tags], keywords: ["mii", "tomodachi life", "nintendo", "tomodachishare", "tomodachi-share", "mii creator", "mii collection", ...mii.tags],
creator: username, creator: name,
openGraph: { openGraph: {
type: "article", type: "article",
title: `${mii.name} - TomodachiShare`, title: `${mii.name} - TomodachiShare`,
description: `Check out '${mii.name}', a Tomodachi Life Mii created by ${username} on TomodachiShare. From ${mii.islandName} Island with ${mii._count.likedBy} likes.`, description: `Check out '${mii.name}', a Tomodachi Life Mii created by ${name} on TomodachiShare. From ${mii.islandName} Island with ${mii._count.likedBy} likes.`,
images: [{ url: metadataImageUrl, alt: `${mii.name}, ${mii.tags.join(", ")} ${mii.gender} Mii character` }], images: [{ url: metadataImageUrl, alt: `${mii.name}, ${mii.tags.join(", ")} ${mii.gender} Mii character` }],
publishedTime: mii.createdAt.toISOString(), publishedTime: mii.createdAt.toISOString(),
authors: username, authors: name,
}, },
twitter: { twitter: {
card: "summary_large_image", card: "summary_large_image",
title: `${mii.name} - TomodachiShare`, title: `${mii.name} - TomodachiShare`,
description: `Check out '${mii.name}', a Tomodachi Life Mii created by ${username} on TomodachiShare. From ${mii.islandName} Island with ${mii._count.likedBy} likes.`, description: `Check out '${mii.name}', a Tomodachi Life Mii created by ${name} on TomodachiShare. From ${mii.islandName} Island with ${mii._count.likedBy} likes.`,
images: [{ url: metadataImageUrl, alt: `${mii.name}, ${mii.tags.join(", ")} ${mii.gender} Mii character` }], images: [{ url: metadataImageUrl, alt: `${mii.name}, ${mii.tags.join(", ")} ${mii.gender} Mii character` }],
creator: username, creator: name,
}, },
alternates: { alternates: {
canonical: `/mii/${mii.id}`, canonical: `/mii/${mii.id}`,
@ -85,7 +85,6 @@ export default async function MiiPage({ params }: Props) {
user: { user: {
select: { select: {
name: true, name: true,
username: true,
}, },
}, },
likedBy: session?.user likedBy: session?.user
@ -215,7 +214,7 @@ export default async function MiiPage({ params }: Props) {
{/* Buttons */} {/* Buttons */}
<div className="flex gap-3 w-fit bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 text-3xl text-orange-400 max-md:place-self-center *:size-12 *:flex *:flex-col *:items-center *:gap-1 **:transition-discrete **:duration-150 *:hover:brightness-75 *:hover:scale-[1.08] *:[&_span]:text-xs"> <div className="flex gap-3 w-fit bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 text-3xl text-orange-400 max-md:place-self-center *:size-12 *:flex *:flex-col *:items-center *:gap-1 **:transition-discrete **:duration-150 *:hover:brightness-75 *:hover:scale-[1.08] *:[&_span]:text-xs">
{session && (Number(session.user.id) === mii.userId || Number(session.user.id) === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) && ( {session && (Number(session.user?.id) === mii.userId || Number(session.user?.id) === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID)) && (
<> <>
<Link aria-label="Edit Mii" href={`/edit/${mii.id}`}> <Link aria-label="Edit Mii" href={`/edit/${mii.id}`}>
<Icon icon="mdi:pencil" /> <Icon icon="mdi:pencil" />

View file

@ -39,9 +39,6 @@ export default async function Page({ searchParams }: Props) {
const session = await auth(); const session = await auth();
const { page, tags } = await searchParams; const { page, tags } = await searchParams;
if (session?.user && !session.user.username) {
redirect("/create-username");
}
if (session?.user) { if (session?.user) {
const activePunishment = await prisma.punishment.findFirst({ const activePunishment = await prisma.punishment.findFirst({
where: { where: {

View file

@ -32,8 +32,8 @@ export default function PrivacyPage() {
<p className="mb-2">The following types of information are stored when you use this website:</p> <p className="mb-2">The following types of information are stored when you use this website:</p>
<ul className="list-disc list-inside"> <ul className="list-disc list-inside">
<li> <li>
<strong>Account Information:</strong> When you sign up or log in using Discord or Github, your username, e-mail, and profile picture are <strong>Account Information:</strong> When you sign up or log in using Discord or Github, your name, e-mail, and profile picture are collected.
collected. Your authentication tokens may also be temporarily stored to maintain your login session. Your authentication tokens may also be temporarily stored to maintain your login session.
</li> </li>
<li> <li>
<strong>Miis:</strong> We store any Miis you submit, including associated images (such as a picture of your Mii, QR codes, and custom images). <strong>Miis:</strong> We store any Miis you submit, including associated images (such as a picture of your Mii, QR codes, and custom images).
@ -77,7 +77,7 @@ export default function PrivacyPage() {
</p> </p>
<ul className="list-disc list-inside ml-4"> <ul className="list-disc list-inside ml-4">
<li>Errors and performance data is collected.</li> <li>Errors and performance data is collected.</li>
<li>Only your user ID and username are sent, no other personally identifiable information is collected.</li> <li>Only your user ID and name are sent, no other personally identifiable information is collected.</li>
<li>You can use ad blockers or browser privacy features to opt out.</li> <li>You can use ad blockers or browser privacy features to opt out.</li>
</ul> </ul>
</section> </section>

View file

@ -39,24 +39,23 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
return { return {
metadataBase: new URL(process.env.NEXT_PUBLIC_BASE_URL!), metadataBase: new URL(process.env.NEXT_PUBLIC_BASE_URL!),
title: `${user.name} (@${user.username}) - TomodachiShare`, title: `${user.name} - TomodachiShare`,
description: `View ${user.name}'s profile on TomodachiShare. Creator of ${user._count.miis} Miis. Member since ${joinDate}.`, description: `View ${user.name}'s profile on TomodachiShare. Creator of ${user._count.miis} Miis. Member since ${joinDate}.`,
keywords: ["mii", "tomodachi life", "nintendo", "mii creator", "mii collection", "profile"], keywords: ["mii", "tomodachi life", "nintendo", "mii creator", "mii collection", "profile"],
creator: user.username, creator: user.name,
openGraph: { openGraph: {
type: "profile", type: "profile",
title: `${user.name} (@${user.username}) - TomodachiShare`, title: `${user.name} - TomodachiShare`,
description: `View ${user.name}'s profile on TomodachiShare. Creator of ${user._count.miis} Miis. Member since ${joinDate}.`, description: `View ${user.name}'s profile on TomodachiShare. Creator of ${user._count.miis} Miis. Member since ${joinDate}.`,
images: [user.image ?? "/guest.png"], images: [user.image ?? "/guest.png"],
username: user.username, username: user.name,
firstName: user.name,
}, },
twitter: { twitter: {
card: "summary", card: "summary",
title: `${user.name} (@${user.username}) - TomodachiShare`, title: `${user.name} - TomodachiShare`,
description: `View ${user.name}'s profile on TomodachiShare. Creator of ${user._count.miis} Miis. Member since ${joinDate}.`, description: `View ${user.name}'s profile on TomodachiShare. Creator of ${user._count.miis} Miis. Member since ${joinDate}.`,
images: [user.image ?? "/guest.png"], images: [user.image ?? "/guest.png"],
creator: user.username!, creator: user.name,
}, },
alternates: { alternates: {
canonical: `/profile/${user.id}`, canonical: `/profile/${user.id}`,

View file

@ -21,7 +21,7 @@ export default async function ProfileSettingsPage() {
if (!session) redirect("/login"); if (!session) redirect("/login");
const user = await prisma.user.findUnique({ where: { id: Number(session.user.id!) }, select: { description: true } }); const user = await prisma.user.findUnique({ where: { id: Number(session.user?.id!) }, select: { description: true } });
return ( return (
<div> <div>

View file

@ -5,18 +5,7 @@ export default function robots(): MetadataRoute.Robots {
rules: { rules: {
userAgent: "*", userAgent: "*",
allow: "/", allow: "/",
disallow: [ disallow: ["/*?*page=", "/profile*?*tags=", "/edit/*", "/profile/settings", "/random", "/submit", "/report/mii/*", "/report/user/*", "/admin"],
"/*?*page=",
"/profile*?*tags=",
"/create-username",
"/edit/*",
"/profile/settings",
"/random",
"/submit",
"/report/mii/*",
"/report/user/*",
"/admin",
],
}, },
sitemap: `${process.env.NEXT_PUBLIC_BASE_URL}/sitemap.xml`, sitemap: `${process.env.NEXT_PUBLIC_BASE_URL}/sitemap.xml`,
}; };

View file

@ -22,10 +22,9 @@ export default async function SubmitPage() {
const session = await auth(); const session = await auth();
if (!session) redirect("/login"); if (!session) redirect("/login");
if (!session.user.username) redirect("/create-username");
const activePunishment = await prisma.punishment.findFirst({ const activePunishment = await prisma.punishment.findFirst({
where: { where: {
userId: Number(session?.user.id), userId: Number(session?.user?.id),
returned: false, returned: false,
}, },
}); });

View file

@ -14,7 +14,6 @@ import PunishmentDeletionDialog from "./punishment-deletion-dialog";
interface ApiResponse { interface ApiResponse {
success: boolean; success: boolean;
name: string; name: string;
username: string;
image: string; image: string;
createdAt: string; createdAt: string;
punishments: Prisma.PunishmentGetPayload<{ punishments: Prisma.PunishmentGetPayload<{
@ -115,7 +114,7 @@ export default function Punishments() {
<ProfilePicture src={user.image} width={96} height={96} className="rounded-full border-2 border-orange-400" /> <ProfilePicture src={user.image} width={96} height={96} className="rounded-full border-2 border-orange-400" />
<div className="p-2 flex flex-col"> <div className="p-2 flex flex-col">
<p className="text-xl font-bold">{user.name}</p> <p className="text-xl font-bold">{user.name}</p>
<p className="text-black/60 text-sm font-medium">@{user.username}</p> <p className="text-black/60 text-sm font-medium">@{user.name}</p>
<p className="text-sm mt-auto"> <p className="text-sm mt-auto">
<span className="font-medium">Created:</span>{" "} <span className="font-medium">Created:</span>{" "}
{new Date(user.createdAt).toLocaleString("en-GB", { {new Date(user.createdAt).toLocaleString("en-GB", {

View file

@ -7,7 +7,7 @@ export default function LoginButtons() {
return ( return (
<div className="flex flex-col items-center gap-2"> <div className="flex flex-col items-center gap-2">
<button <button
onClick={() => signIn("discord", { redirectTo: "/create-username" })} onClick={() => signIn("discord", { redirectTo: "/" })}
aria-label="Login with Discord" aria-label="Login with Discord"
className="pill button gap-2 px-3! bg-indigo-400! border-indigo-500! hover:bg-indigo-500!" className="pill button gap-2 px-3! bg-indigo-400! border-indigo-500! hover:bg-indigo-500!"
> >
@ -15,7 +15,7 @@ export default function LoginButtons() {
Login with Discord Login with Discord
</button> </button>
<button <button
onClick={() => signIn("github", { redirectTo: "/create-username" })} onClick={() => signIn("github", { redirectTo: "/" })}
aria-label="Login with GitHub" aria-label="Login with GitHub"
className="pill button gap-2 px-3! bg-zinc-700! border-zinc-800! hover:bg-zinc-800! text-white" className="pill button gap-2 px-3! bg-zinc-700! border-zinc-800! hover:bg-zinc-800! text-white"
> >

View file

@ -1,3 +1,4 @@
import { headers } from "next/headers";
import Link from "next/link"; import Link from "next/link";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
@ -25,7 +26,6 @@ interface Props {
export default async function MiiList({ searchParams, userId, inLikesPage }: Props) { export default async function MiiList({ searchParams, userId, inLikesPage }: Props) {
const session = await auth(); const session = await auth();
const parsed = searchSchema.safeParse(searchParams); const parsed = searchSchema.safeParse(searchParams);
if (!parsed.success) return <h1>{parsed.error.issues[0].message}</h1>; if (!parsed.success) return <h1>{parsed.error.issues[0].message}</h1>;
@ -34,7 +34,7 @@ export default async function MiiList({ searchParams, userId, inLikesPage }: Pro
// My Likes page // My Likes page
let miiIdsLiked: number[] | undefined = undefined; let miiIdsLiked: number[] | undefined = undefined;
if (inLikesPage && session?.user.id) { if (inLikesPage && session?.user?.id) {
const likedMiis = await prisma.like.findMany({ const likedMiis = await prisma.like.findMany({
where: { userId: Number(session.user.id) }, where: { userId: Number(session.user.id) },
select: { miiId: true }, select: { miiId: true },
@ -67,7 +67,7 @@ export default async function MiiList({ searchParams, userId, inLikesPage }: Pro
user: { user: {
select: { select: {
id: true, id: true,
username: true, name: true,
}, },
}, },
}), }),
@ -210,11 +210,11 @@ export default async function MiiList({ searchParams, userId, inLikesPage }: Pro
{!userId && ( {!userId && (
<Link href={`/profile/${mii.user?.id}`} className="text-sm text-right overflow-hidden text-ellipsis"> <Link href={`/profile/${mii.user?.id}`} className="text-sm text-right overflow-hidden text-ellipsis">
@{mii.user?.username} @{mii.user?.name}
</Link> </Link>
)} )}
{userId && Number(session?.user.id) == userId && ( {userId && Number(session?.user?.id) == userId && (
<div className="flex gap-1 text-2xl justify-end text-zinc-400"> <div className="flex gap-1 text-2xl justify-end text-zinc-400">
<Link href={`/edit/${mii.id}`} title="Edit Mii" aria-label="Edit Mii" data-tooltip="Edit"> <Link href={`/edit/${mii.id}`} title="Edit Mii" aria-label="Edit Mii" data-tooltip="Edit">
<Icon icon="mdi:pencil" /> <Icon icon="mdi:pencil" />

View file

@ -15,7 +15,7 @@ interface Props {
export default async function ProfileInformation({ userId, page }: Props) { export default async function ProfileInformation({ userId, page }: Props) {
const session = await auth(); const session = await auth();
const id = userId ? userId : Number(session?.user.id); const id = userId ? userId : Number(session?.user?.id);
const user = await prisma.user.findUnique({ where: { id } }); const user = await prisma.user.findUnique({ where: { id } });
const likedMiis = await prisma.like.count({ where: { userId: id } }); const likedMiis = await prisma.like.count({ where: { userId: id } });
@ -23,7 +23,7 @@ export default async function ProfileInformation({ userId, page }: Props) {
const isAdmin = id === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID); const isAdmin = id === Number(process.env.NEXT_PUBLIC_ADMIN_USER_ID);
const isContributor = process.env.NEXT_PUBLIC_CONTRIBUTORS_USER_IDS?.split(",").includes(id.toString()); const isContributor = process.env.NEXT_PUBLIC_CONTRIBUTORS_USER_IDS?.split(",").includes(id.toString());
const isOwnProfile = Number(session?.user.id) === id; const isOwnProfile = Number(session?.user?.id) === id;
return ( return (
<div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex gap-4 mb-2 max-md:flex-col"> <div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex gap-4 mb-2 max-md:flex-col">
@ -47,7 +47,7 @@ export default async function ProfileInformation({ userId, page }: Props) {
</div> </div>
)} )}
</div> </div>
<h2 className="text-black/60 text-sm font-semibold wrap-break-word">@{user?.username}</h2> <h2 className="text-black/60 text-sm font-semibold wrap-break-word">ID: {user?.id}</h2>
<div className="mt-3 text-sm flex gap-8"> <div className="mt-3 text-sm flex gap-8">
<h4 title={`${user.createdAt.toLocaleTimeString("en-GB", { timeZone: "UTC" })} UTC`}> <h4 title={`${user.createdAt.toLocaleTimeString("en-GB", { timeZone: "UTC" })} UTC`}>

View file

@ -7,7 +7,7 @@ export default async function ProfileOverview() {
return ( return (
<li title="Your profile"> <li title="Your profile">
<Link href={`/profile/${session?.user.id}`} aria-label="Go to profile" className="pill button gap-2! p-0! h-full max-w-64" data-tooltip="Your Profile"> <Link href={`/profile/${session?.user?.id}`} aria-label="Go to profile" className="pill button gap-2! p-0! h-full max-w-64" data-tooltip="Your Profile">
<Image <Image
src={session?.user?.image ?? "/guest.png"} src={session?.user?.image ?? "/guest.png"}
alt="profile picture" alt="profile picture"
@ -15,7 +15,7 @@ export default async function ProfileOverview() {
height={40} height={40}
className="rounded-full aspect-square object-cover h-full bg-white outline-2 outline-orange-400" className="rounded-full aspect-square object-cover h-full bg-white outline-2 outline-orange-400"
/> />
<span className="pr-4 overflow-hidden whitespace-nowrap text-ellipsis w-full">{session?.user?.username ?? "unknown"}</span> <span className="pr-4 overflow-hidden whitespace-nowrap text-ellipsis w-full">{session?.user?.name ?? "unknown"}</span>
</Link> </Link>
</li> </li>
); );

View file

@ -2,9 +2,8 @@
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import dayjs from "dayjs";
import { displayNameSchema, usernameSchema } from "@/lib/schemas"; import { userNameSchema } from "@/lib/schemas";
import ProfilePictureSettings from "./profile-picture"; import ProfilePictureSettings from "./profile-picture";
import SubmitDialogButton from "./submit-dialog-button"; import SubmitDialogButton from "./submit-dialog-button";
@ -19,14 +18,10 @@ export default function ProfileSettings({ currentDescription }: Props) {
const router = useRouter(); const router = useRouter();
const [description, setDescription] = useState(currentDescription); const [description, setDescription] = useState(currentDescription);
const [displayName, setDisplayName] = useState(""); const [name, setName] = useState("");
const [username, setUsername] = useState("");
const [descriptionChangeError, setDescriptionChangeError] = useState<string | undefined>(undefined); const [descriptionChangeError, setDescriptionChangeError] = useState<string | undefined>(undefined);
const [displayNameChangeError, setDisplayNameChangeError] = useState<string | undefined>(undefined); const [nameChangeError, setNameChangeError] = useState<string | undefined>(undefined);
const [usernameChangeError, setUsernameChangeError] = useState<string | undefined>(undefined);
const usernameDate = dayjs().add(90, "days");
const handleSubmitDescriptionChange = async (close: () => void) => { const handleSubmitDescriptionChange = async (close: () => void) => {
const parsed = z.string().trim().max(256).safeParse(description); const parsed = z.string().trim().max(256).safeParse(description);
@ -51,45 +46,22 @@ export default function ProfileSettings({ currentDescription }: Props) {
router.refresh(); router.refresh();
}; };
const handleSubmitDisplayNameChange = async (close: () => void) => { const handleSubmitNameChange = async (close: () => void) => {
const parsed = displayNameSchema.safeParse(displayName); const parsed = userNameSchema.safeParse(name);
if (!parsed.success) { if (!parsed.success) {
setDisplayNameChangeError(parsed.error.issues[0].message); setNameChangeError(parsed.error.issues[0].message);
return; return;
} }
const response = await fetch("/api/auth/display-name", { const response = await fetch("/api/auth/name", {
method: "PATCH", method: "PATCH",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ displayName }), body: JSON.stringify({ name }),
}); });
if (!response.ok) { if (!response.ok) {
const { error } = await response.json(); const { error } = await response.json();
setDisplayNameChangeError(error); setNameChangeError(error);
return;
}
close();
router.refresh();
};
const handleSubmitUsernameChange = async (close: () => void) => {
const parsed = usernameSchema.safeParse(username);
if (!parsed.success) {
setUsernameChangeError(parsed.error.issues[0].message);
return;
}
const response = await fetch("/api/auth/username", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username }),
});
if (!response.ok) {
const { error } = await response.json();
setUsernameChangeError(error);
return; return;
} }
@ -101,7 +73,7 @@ export default function ProfileSettings({ currentDescription }: Props) {
<div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex flex-col gap-4"> <div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex flex-col gap-4">
<div> <div>
<h2 className="text-2xl font-bold">Profile Settings</h2> <h2 className="text-2xl font-bold">Profile Settings</h2>
<p className="text-sm text-zinc-500">Update your account info, and username.</p> <p className="text-sm text-zinc-500">Update your profile picture, description, name, etc.</p>
</div> </div>
{/* Separator */} {/* Separator */}
@ -146,58 +118,21 @@ export default function ProfileSettings({ currentDescription }: Props) {
{/* Change Name */} {/* Change Name */}
<div className="grid grid-cols-5 gap-4 max-lg:grid-cols-1"> <div className="grid grid-cols-5 gap-4 max-lg:grid-cols-1">
<div className="col-span-3"> <div className="col-span-3">
<label className="font-semibold">Change Display Name</label> <label className="font-semibold">Change Name</label>
<p className="text-sm text-zinc-500">This is a display name shown on your profile feel free to change it anytime</p> <p className="text-sm text-zinc-500">This is your name shown on your profile and miis feel free to change it anytime</p>
</div> </div>
<div className="flex justify-end gap-1 h-min col-span-2"> <div className="flex justify-end gap-1 h-min col-span-2">
<input type="text" className="pill input flex-1" placeholder="Type here..." value={displayName} onChange={(e) => setDisplayName(e.target.value)} /> <input type="text" className="pill input flex-1" placeholder="Type here..." value={name} onChange={(e) => setName(e.target.value)} />
<SubmitDialogButton <SubmitDialogButton
title="Confirm Display Name Change" title="Confirm Name Change"
description="Are you sure? This will only be visible on your profile. You can change it again later." description="Are you sure? You can change it again later."
error={displayNameChangeError} error={nameChangeError}
onSubmit={handleSubmitDisplayNameChange} onSubmit={handleSubmitNameChange}
> >
<div className="bg-orange-100 rounded-xl border-2 border-amber-500 mt-4 px-2 py-1"> <div className="bg-orange-100 rounded-xl border-2 border-amber-500 mt-4 px-2 py-1">
<p className="font-semibold">New display name:</p> <p className="font-semibold">New name:</p>
<p className="indent-4">&apos;{displayName}&apos;</p> <p className="indent-4">&apos;{name}&apos;</p>
</div>
</SubmitDialogButton>
</div>
</div>
{/* Change Username */}
<div className="grid grid-cols-5 gap-4 max-lg:grid-cols-1">
<div className="col-span-3">
<label className="font-semibold">Change Username</label>
<p className="text-sm text-zinc-500">Your unique tag on the site. Can only be changed once every 90 days</p>
</div>
<div className="flex justify-end gap-1 col-span-2">
<div className="relative flex-1">
<input
type="text"
className="pill input w-full indent-4"
placeholder="Type here..."
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<span className="absolute top-1/2 -translate-y-1/2 left-4 select-none">@</span>
</div>
<SubmitDialogButton
title="Confirm Username Change"
description="Are you sure? Your username is your unique indentifier and can only be changed every 90 days."
error={usernameChangeError}
onSubmit={handleSubmitUsernameChange}
>
<p className="text-sm text-zinc-500 mt-2">
After submitting, you can change it again on{" "}
{usernameDate.toDate().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}.
</p>
<div className="bg-orange-100 rounded-xl border-2 border-amber-500 mt-4 px-2 py-1">
<p className="font-semibold">New username:</p>
<p className="indent-4">&apos;@{username}&apos;</p>
</div> </div>
</SubmitDialogButton> </SubmitDialogButton>
</div> </div>

View file

@ -44,10 +44,7 @@ export default function ReportUserForm({ user }: Props) {
<div className="bg-orange-100 rounded-xl border-2 border-orange-400 flex p-4 gap-4"> <div className="bg-orange-100 rounded-xl border-2 border-orange-400 flex p-4 gap-4">
<ProfilePicture src={user.image ?? "/guest.png"} width={96} height={96} className="aspect-square rounded-full border-2 border-orange-400" /> <ProfilePicture src={user.image ?? "/guest.png"} width={96} height={96} className="aspect-square rounded-full border-2 border-orange-400" />
<div className="flex flex-col justify-center">
<p className="text-xl font-bold overflow-hidden text-ellipsis">{user.name}</p> <p className="text-xl font-bold overflow-hidden text-ellipsis">{user.name}</p>
<p className="text-sm font-bold overflow-hidden text-ellipsis">@{user.username}</p>
</div>
</div> </div>
<div className="w-full grid grid-cols-3 items-center"> <div className="w-full grid grid-cols-3 items-center">

View file

@ -1,46 +0,0 @@
"use client";
import { useState } from "react";
import { redirect } from "next/navigation";
import { usernameSchema } from "@/lib/schemas";
import SubmitButton from "./submit-button";
export default function UsernameForm() {
const [username, setUsername] = useState("");
const [error, setError] = useState<string | undefined>(undefined);
const handleSubmit = async () => {
const parsed = usernameSchema.safeParse(username);
if (!parsed.success) setError(parsed.error.issues[0].message);
const response = await fetch("/api/auth/username", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username }),
});
if (!response.ok) {
const { error } = await response.json();
setError(error);
return;
}
redirect("/");
};
return (
<form className="flex flex-col items-center">
<input
type="text"
placeholder="Type your username..."
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="pill input w-96 mb-2"
/>
<SubmitButton onClick={handleSubmit} />
{error && <p className="text-red-400 font-semibold mt-4">Error: {error}</p>}
</form>
);
}

View file

@ -15,7 +15,6 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
async session({ session, user }) { async session({ session, user }) {
if (user) { if (user) {
session.user.id = user.id; session.user.id = user.id;
session.user.username = user.username;
session.user.email = user.email; session.user.email = user.email;
} }
return session; return session;

View file

@ -102,7 +102,7 @@ export class RateLimit {
async handle(): Promise<NextResponse<object | unknown> | undefined> { async handle(): Promise<NextResponse<object | unknown> | undefined> {
const session = await auth(); const session = await auth();
const ip = this.request.headers.get("CF-Connecting-IP") || this.request.headers.get("X-Forwarded-For")?.split(",")[0]; const ip = this.request.headers.get("CF-Connecting-IP") || this.request.headers.get("X-Forwarded-For")?.split(",")[0];
const identifier = (session ? session.user.id : ip) ?? "anonymous"; const identifier = (session ? session.user?.id : ip) ?? "anonymous";
this.data = await this.check(identifier); this.data = await this.check(identifier);

View file

@ -73,19 +73,11 @@ export const searchSchema = z.object({
seed: z.coerce.number({ error: "Seed must be a number" }).int({ error: "Seed must be an integer" }).optional(), seed: z.coerce.number({ error: "Seed must be a number" }).int({ error: "Seed must be an integer" }).optional(),
}); });
// Account Info export const userNameSchema = z
export const usernameSchema = z
.string() .string()
.trim() .trim()
.min(3, "Username must be at least 3 characters long") .min(2, { error: "Name must be at least 2 characters long" })
.max(20, "Username cannot be more than 20 characters long") .max(64, { error: "Name cannot be more than 64 characters long" })
.regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores");
export const displayNameSchema = z
.string()
.trim()
.min(2, { error: "Display name must be at least 2 characters long" })
.max(64, { error: "Display name cannot be more than 64 characters long" })
.regex(/^[a-zA-Z0-9-_. ']+$/, { .regex(/^[a-zA-Z0-9-_. ']+$/, {
error: "Display name can only contain letters, numbers, dashes, underscores, apostrophes, and spaces.", error: "Name can only contain letters, numbers, dashes, underscores, apostrophes, and spaces.",
}); });

14
src/types.d.ts vendored
View file

@ -1,14 +0,0 @@
import { Prisma } from "@prisma/client";
import { DefaultSession } from "next-auth";
declare module "next-auth" {
interface Session {
user: {
username?: string;
} & DefaultSession["user"];
}
interface User {
username?: string;
}
}