fix: auth ssr to rendering admin btn and username

This commit is contained in:
Rémi 2025-01-05 01:09:03 +01:00
parent ddd333e64a
commit a9d4fbedcf
7 changed files with 95 additions and 47 deletions

14
src/app/admin/page.tsx Normal file
View File

@ -0,0 +1,14 @@
import { Metadata } from "next";
import { AdminHeader } from "../components/Header/admin";
import { getServerSession } from "next-auth";
import { authOptions } from "@/authOptions";
export const metadata: Metadata = {
title: "Toogether Admin",
};
export default async function AdminPage() {
const session = await getServerSession(authOptions);
return <AdminHeader />;
}

View File

@ -0,0 +1,32 @@
"use client";
export const AdminHeader = () => {
return (
<>
<button
data-drawer-target="default-sidebar"
data-drawer-toggle="default-sidebar"
aria-controls="default-sidebar"
type="button"
className="inline-flex items-center p-2 mt-2 ms-3 text-sm text-gray-500 rounded-lg sm:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600"
>
<span className="sr-only">Open sidebar</span>
<p>test</p>
</button>
<aside className="fixed top-0 left-0 z-40 w-64 h-screen transition-transform -translate-x-full sm:translate-x-0">
<div className="h-full px-3 py-4 overflow-y-auto bg-gray-50 dark:bg-gray-800">
<ul className="space-y-2 font-medium">
<li>
<a
href="#"
className="flex items-center p-2 text-gray-900 rounded-lg dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700"
>
<span className="ms-3">Dashboard</span>
</a>
</li>
</ul>
</div>
</aside>
</>
);
};

View File

@ -1,4 +1,5 @@
"use client"; "use client";
import { User } from "@/app/types/next-auth";
import { import {
Avatar, Avatar,
Button, Button,
@ -11,11 +12,8 @@ import {
NavbarContent, NavbarContent,
NavbarItem, NavbarItem,
} from "@nextui-org/react"; } from "@nextui-org/react";
import { useSession } from "next-auth/react";
import { ThemeSwitcher } from "../ThemeSwitcher/ThemeSwitcher";
import { axiosInstance } from "@/app/lib/axios";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { ThemeSwitcher } from "../ThemeSwitcher/ThemeSwitcher";
const getInitials = (name: string) => { const getInitials = (name: string) => {
if (!name) return ""; if (!name) return "";
@ -31,31 +29,10 @@ const getInitials = (name: string) => {
return firstInitial + secondInitial; return firstInitial + secondInitial;
}; };
export const Header = () => { export const Header = ({ user }: { user?: User }) => {
const { data: session } = useSession();
const router = useRouter(); const router = useRouter();
const [userProfile, setUserProfile] = useState<{ const initials = user?.name ? getInitials(user.name) : "";
id: string;
username: string;
role: "ADMIN" | "STUDENT";
}>();
const initials = session?.user?.name ? getInitials(session.user.name) : "";
const fetchUserProfile = async () => {
return await axiosInstance<{
id: string;
username: string;
role: "ADMIN" | "STUDENT";
}>("/@me");
};
useEffect(() => {
fetchUserProfile().then((r) => {
setUserProfile(r.data);
});
}, []);
return ( return (
<Navbar className="mb-2"> <Navbar className="mb-2">
@ -64,7 +41,7 @@ export const Header = () => {
</NavbarBrand> </NavbarBrand>
<NavbarContent as="div" justify="end"> <NavbarContent as="div" justify="end">
{userProfile?.role === "ADMIN" ? ( {user?.roles.includes("admin") ? (
<NavbarItem> <NavbarItem>
<Button <Button
size="sm" size="sm"
@ -76,6 +53,7 @@ export const Header = () => {
</Button> </Button>
</NavbarItem> </NavbarItem>
) : null} ) : null}
<NavbarItem> <NavbarItem>
<ThemeSwitcher /> <ThemeSwitcher />
</NavbarItem> </NavbarItem>
@ -94,9 +72,7 @@ export const Header = () => {
<DropdownMenu aria-label="Profile Actions" variant="flat"> <DropdownMenu aria-label="Profile Actions" variant="flat">
<DropdownItem key="profile" className="h-14 gap-2"> <DropdownItem key="profile" className="h-14 gap-2">
<p>Signed in as</p> <p>Signed in as</p>
<p className="font-semibold"> <p className="font-semibold">{user?.name}</p>
{session?.user?.name}
</p>
</DropdownItem> </DropdownItem>
<DropdownItem key="settings">Settings</DropdownItem> <DropdownItem key="settings">Settings</DropdownItem>
<DropdownItem <DropdownItem

View File

@ -11,16 +11,18 @@ export const ThemeSwitcher = () => {
setMounted(true); setMounted(true);
}, []); }, []);
if (!mounted) return null;
return ( return (
<div>
<Button <Button
size="sm" size="sm"
variant="flat" variant="flat"
className="min-w-0" className="min-w-0"
onPress={() => setTheme(theme === "light" ? "dark" : "light")} onPress={() =>
mounted && setTheme(theme === "light" ? "dark" : "light")
}
> >
{theme === "light" ? "🌑" : "☀️"} {mounted && theme === "light" ? "🌑" : "☀️"}
</Button> </Button>
</div>
); );
}; };

View File

@ -1,4 +1,6 @@
import { authOptions } from "@/authOptions";
import { Metadata } from "next"; import { Metadata } from "next";
import { getServerSession } from "next-auth";
import { Header } from "./components/Header"; import { Header } from "./components/Header";
import { RoomTable } from "./components/Room/Table"; import { RoomTable } from "./components/Room/Table";
@ -8,10 +10,12 @@ export const metadata: Metadata = {
"Toogether is a platform that allows you to create and join rooms to study together.", "Toogether is a platform that allows you to create and join rooms to study together.",
}; };
export default function HomePage() { export default async function HomePage() {
const session = await getServerSession(authOptions);
return ( return (
<> <>
<Header /> <Header user={session?.user} />
<main className="flex flex-col gap-8 p-4"> <main className="flex flex-col gap-8 p-4">
<RoomTable /> <RoomTable />
</main> </main>

View File

@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
import { Moment } from "moment"; import { Moment } from "moment";
import NextAuth, { DefaultSession } from "next-auth"; import { DefaultSession } from "next-auth";
import { JWT } from "next-auth/jwt"; import "next-auth/jwt";
interface User { interface User {
id: string; id: string;
@ -10,6 +10,14 @@ interface User {
preferred_username: string; preferred_username: string;
given_name: string; given_name: string;
family_name: string; family_name: string;
email: string;
roles: string[];
}
export interface JWTDecoded {
realm_access: {
roles: string[];
};
} }
declare module "next-auth" { declare module "next-auth" {

View File

@ -2,6 +2,8 @@ import axios from "axios";
import moment from "moment"; import moment from "moment";
import { AuthOptions, Session } from "next-auth"; import { AuthOptions, Session } from "next-auth";
import { JWT } from "next-auth/jwt"; import { JWT } from "next-auth/jwt";
import jsonwebtoken from "jsonwebtoken";
import { JWTDecoded } from "./app/types/next-auth";
moment.locale("fr"); moment.locale("fr");
@ -16,7 +18,7 @@ export const authOptions: AuthOptions = {
authorization: { authorization: {
url: process.env.OAUTH_AUTHORIZATION_URL, url: process.env.OAUTH_AUTHORIZATION_URL,
params: { params: {
scope: "openid profile offline_access", scope: "openid email profile offline_access",
response_type: "code", response_type: "code",
}, },
}, },
@ -33,6 +35,7 @@ export const authOptions: AuthOptions = {
profile.name || profile.name ||
profile.preferred_username || profile.preferred_username ||
`${profile.given_name} ${profile.family_name}`, `${profile.given_name} ${profile.family_name}`,
email: profile.email,
}; };
}, },
}, },
@ -45,7 +48,16 @@ export const authOptions: AuthOptions = {
account.expires_at * 1000, account.expires_at * 1000,
).subtract(5, "s"); ).subtract(5, "s");
token.refreshToken = account.refresh_token; token.refreshToken = account.refresh_token;
token.user = user;
const accessTokenDecode = jsonwebtoken.decode(
account.access_token,
) as JWTDecoded;
token.user = {
...user,
roles: accessTokenDecode.realm_access.roles,
};
return token; return token;
} }