Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ✨ feat(admin-example): Update UI components and add admin examples #25

Merged
merged 1 commit into from
Jan 13, 2024
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
14 changes: 14 additions & 0 deletions actions/admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"use server";

import { currentRole } from "@/lib/auth";
import { UserRole } from "@prisma/client";

export const admin = async () => {
const role = await currentRole();

if (role === UserRole.ADMIN) {
return { success: "Allowed Server Action!" };
}

return { error: "Forbidden Server Action!" };
};
3 changes: 2 additions & 1 deletion app/(protected)/_components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ const Navbar = () => {
const pathName = usePathname();

return (
<nav className="bg-secondary flex justify-between items-center p-4 rounded-xl w-[600px]">
// TODO: Mobile navbar
<nav className="w-full fixed bg-secondary flex justify-between items-center p-4">
<div className="flex gap-x-2">
{NAV_LINKS.map((link, index) => (
<Button
Expand Down
17 changes: 17 additions & 0 deletions app/(protected)/admin/@client/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use client";

import { useCurrentRole } from "@/hooks/use-current-role";
import PageTypeCard from "../_components/page-type-card";

export default function AdminPage() {
const role = useCurrentRole();

return (
<div>
<PageTypeCard
title="Admin Client Page"
role={role}
/>
</div>
);
}
15 changes: 15 additions & 0 deletions app/(protected)/admin/@server/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { currentRole } from "@/lib/auth";
import PageTypeCard from "../_components/page-type-card";

export default async function AdminPage() {
const role = await currentRole();

return (
<div>
<PageTypeCard
title="Admin Server Page"
role={role}
/>
</div>
);
}
27 changes: 27 additions & 0 deletions app/(protected)/admin/_components/page-type-card.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { UserRole } from "@prisma/client";

type PageTypeCardProps = {
title: string;
role: UserRole;
};

const PageTypeCard = ({ title, role }: PageTypeCardProps) => {
return (
<Card className="w-auto">
<CardHeader>
<p className="text-2xl font-semibold text-center">{title}</p>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex flex-row items-center justify-between rounded-lg border p-3">
<p className="text-sm font-medium">Role</p>
<p className="truncate text-xs max-w-[180px] p-1 bg-sky-400 text-primary-foreground rounded-md">
{role}
</p>
</div>
</CardContent>
</Card>
);
};

export default PageTypeCard;
21 changes: 21 additions & 0 deletions app/(protected)/admin/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Toaster } from "@/components/ui/sonner";

export default function AdminLayout(props: {
children: React.ReactNode;
client: React.ReactNode;
server: React.ReactNode;
}) {
return (
<div className="w-full flex-col items-center justify-center">
<Toaster
richColors
closeButton
/>
{props.children}
<div className="flex justify-around mt-6">
{props.client}
{props.server}
</div>
</div>
);
}
79 changes: 79 additions & 0 deletions app/(protected)/admin/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"use client";

import { MdOutlineAdminPanelSettings } from "react-icons/md";
import { UserRole } from "@prisma/client";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import RoleGate from "@/components/auth/role-gate";
import FormSuccess from "@/components/form-success";
import { admin } from "@/actions/admin";

export default function AdminPage() {
const handleApiRoute = async () => {
try {
const response = await fetch("/api/admin");

if (response.ok) {
toast.success("Allowed API Route!");
} else {
toast.error("Forbidden API Route!");
}
} catch (error) {
console.error("An error occurred while fetching the API:", error);
}
};

const handleServerAction = async () => {
try {
const data = await admin();

if (data.error) {
toast.error(data.error);
}

if (data.success) {
toast.success(data.success);
}
} catch (error) {
console.error("An error occurred during the server action:", error);
}
};

return (
<Card className="w-auto">
<CardHeader className="flex-row items-center justify-center gap-x-4">
<span>
<MdOutlineAdminPanelSettings className="h-10 w-10 text-sky-400" />
</span>
<p className="text-2xl font-semibold text-center">Admin</p>
</CardHeader>
<CardContent className="space-y-4">
<RoleGate allowedRole={UserRole.ADMIN}>
<FormSuccess message="Allowed, your role give you permissions see this content!" />

<div className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-md">
<p className="text-sm font-medium">Admin-only API Route</p>
<Button
className=" hover:bg-sky-400"
onClick={handleApiRoute}
>
Test it here
</Button>
</div>

<div className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-md">
<p className="text-sm font-medium">Admin-only Server Action</p>
<Button
className=" hover:bg-sky-400"
onClick={handleServerAction}
>
Test it here
</Button>
</div>
</RoleGate>
</CardContent>
</Card>
);
}
6 changes: 4 additions & 2 deletions app/(protected)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ export default async function ProtectedLayout({

return (
<SessionProvider session={session}>
<div className="h-full w-full flex flex-col gap-y-10 items-center justify-center">
<div className="h-full w-full flex">
<Navbar />
{children}
<div className="w-full flex items-center justify-center mx-5">
{children}
</div>
</div>
</SessionProvider>
);
Expand Down
2 changes: 1 addition & 1 deletion app/(protected)/server/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import UserInfo from "@/components/user-info";
import { currentUser } from "@/lib/auth";
import UserInfo from "@/components/user-info";

export default async function ServerPage() {
const user = await currentUser();
Expand Down
14 changes: 14 additions & 0 deletions app/api/admin/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { UserRole } from "@prisma/client";
import { NextResponse } from "next/server";

import { currentRole } from "@/lib/auth";

export async function GET() {
const role = await currentRole();

if (role === UserRole.ADMIN) {
return new NextResponse(null, { status: 200 });
}

return new NextResponse(null, { status: 403 });
}
25 changes: 25 additions & 0 deletions components/auth/role-gate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"use client";

import { UserRole } from "@prisma/client";

import { useCurrentRole } from "@/hooks/use-current-role";
import FormError from "@/components/form-error";

interface RoleGateProps {
children: React.ReactNode;
allowedRole: UserRole;
}

const RoleGate = ({ children, allowedRole }: RoleGateProps) => {
const role = useCurrentRole();

if (role !== allowedRole) {
return (
<FormError message="Not allowed, you do not have permission to view this content!" />
);
}

return <>{children}</>;
};

export default RoleGate;
31 changes: 31 additions & 0 deletions components/ui/sonner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use client"

import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"

type ToasterProps = React.ComponentProps<typeof Sonner>

const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()

return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}

export { Toaster }
7 changes: 5 additions & 2 deletions components/user-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const UserInfo = ({ user, label }: UserInfoProps) => {
};

return (
<Card className="w-[600px]">
<Card className="w-auto">
<CardHeader>
<p className="text-2xl font-semibold text-center">{label}</p>
</CardHeader>
Expand All @@ -29,7 +29,10 @@ const UserInfo = ({ user, label }: UserInfoProps) => {
>
<p className="text-sm font-medium">{key}</p>
{key === "Two Factor Authentication" ? (
<Badge variant={value ? "success" : "destructive"}>
<Badge
variant={value ? "success" : "destructive"}
className="ml-4"
>
{value ? "Enabled" : "Disabled"}
</Badge>
) : (
Expand Down
7 changes: 7 additions & 0 deletions hooks/use-current-role.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { useSession } from "next-auth/react";

export const useCurrentRole = () => {
const session = useSession();

return session.data?.user?.role;
};
6 changes: 6 additions & 0 deletions lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ export const currentUser = async () => {

return session?.user;
};

export const currentRole = async () => {
const session = await auth();

return session?.user?.role;
};
21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@
"clsx": "^2.1.0",
"next": "14.0.4",
"next-auth": "^5.0.0-beta.4",
"next-themes": "^0.2.1",
"react": "^18",
"react-dom": "^18",
"react-hook-form": "^7.49.2",
"react-icons": "^5.0.1",
"resend": "^2.1.0",
"sonner": "^1.3.1",
"tailwind-merge": "^2.2.0",
"tailwindcss-animate": "^1.0.7",
"uuid": "^9.0.1",
Expand Down
Loading