Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/app/adminDashboard/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";
import connectDB from "@/database/db";
import User from "@/database/userSchema";

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const { userId } = await auth();
if (!userId) {
return redirect("/login");
}

await connectDB();
// our userSchema is loosely typed, so we need to clarify what the role is when using lean()
const user = await User.findOne({ clerkId: userId }).lean<{ role: string } | null>();

if (!user || user.role !== "admin") {
return redirect("/playerDashboard");
}

return <>{children}</>;
}
33 changes: 33 additions & 0 deletions src/app/api/admin/[id]/role/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
import { auth, clerkClient } from "@clerk/nextjs/server";
import connectDB from "@/database/db";
import User from "@/database/userSchema";

export async function PATCH(req: Request, { params }: { params: { id: string } }) {
const { userId, sessionClaims } = await auth();
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

// IMPORTANT perhaps uncomment this in production
// if (sessionClaims?.role !== "admin") {
// return NextResponse.json({ error: "Forbidden" }, { status: 403 });
// }

const { role } = await req.json();

await connectDB();

// Update Mongo ( new: true will pass the updated document to mongo)
const updated = await User.findByIdAndUpdate(params.id, { role }, { new: true }).lean<{ clerkId: string } | null>();
if (!updated) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}

// Sync Clerk metadata
const client = await clerkClient();

await client.users.updateUserMetadata(updated.clerkId, {
publicMetadata: { role },
});

return NextResponse.json({ ok: true, user: updated }, { status: 200 });
}
21 changes: 20 additions & 1 deletion src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
export default function Dashboard() {}
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";

//Redirect the user to the proper dashboard

//ADD THESE TO ENV
//NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard
//NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/dashboard

export default async function Dashboard() {
const { sessionClaims } = await auth();

const role = sessionClaims?.role;

if (role === "admin") {
redirect("/adminDashboard");
}

redirect("/playerDashboard");
}
2 changes: 1 addition & 1 deletion src/components/ChakraButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function ChakraButton({ href, color, label, width, minW, iconSrc
minW={minW}
py={8}
position="relative"
overflow="hidden" // keeps the blue bottom highlight within the button
overflow="hidden" // keeps the bottom highlight stroke within the button
borderRadius="18px"
bg={`${color}.500`}
color="white"
Expand Down
2 changes: 1 addition & 1 deletion src/components/PlayerNavbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function PlayerNavbar({ role, name, coins = "0", avatarSrc }: NavbarProps

{/* Right side actions */}
<HStack>
<ChakraButton href="/" color="red" label="SHOP" width="140px" iconSrc="/Icons/FaShoppingBag.png" />
<ChakraButton href="/shop" color="red" label="SHOP" width="140px" iconSrc="/Icons/FaShoppingBag.png" />
<ChakraButton href="/" color="yellow" label={coins} width="140px" iconSrc="/Icons/FaStar.png" />
</HStack>
</HStack>
Expand Down
3 changes: 2 additions & 1 deletion src/database/userSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import mongoose, { Schema } from "mongoose";

// Updated UserSchema to match specifications
const UserSchema = new Schema({
clerkId: { type: String, required: true, unique: true },
name: { type: String, required: true, trim: true },
username: { type: String, required: true, trim: true },
role: { type: String, required: true, trim: true },
role: { type: String, required: true, trim: true, default: "player" },
email: { type: String, required: true, trim: true },
});

Expand Down
26 changes: 24 additions & 2 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
import { clerkMiddleware } from "@clerk/nextjs/server";
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";

export default clerkMiddleware();
const isPublicRoute = createRouteMatcher(["/login(.*)"]);
const isAdminRoute = createRouteMatcher(["/adminDashboard(.*)"]);

// !IMPORTANT, add this to your env:
// NEXT_PUBLIC_CLERK_SIGN_IN_URL=/login
//otherwise auth.protect() will default to clerks hosted login route.

//Keep in mind when you change roles, it wont appear until clerks session token refreshes.
//https://clerk.com/docs/guides/sessions/customize-session-tokens

export default clerkMiddleware(async (auth, req) => {
if (isPublicRoute(req)) return NextResponse.next();
const { sessionClaims } = await auth.protect();
const role = sessionClaims?.role;

// Protect admin routes (can pass a error instead)
if (isAdminRoute(req) && role !== "admin") {
return NextResponse.redirect(new URL("/playerDashboard", req.url));
}

return NextResponse.next();
});

export const config = {
matcher: [
Expand Down
Loading