Skip to content

Commit

Permalink
Conditional rendering of admin features (#156)
Browse files Browse the repository at this point in the history
* feat: init user memberships context

* feat: add user memberships context provider to main layout

* feat: add conditional rendering of create service button

* feat: extract main nav layout

* feat: add conditional rendering in side bar

* feat: implement conditional rendering of admin pages by restructuring folders and layouts

* refactor: rename context folder

* refactor: remove unused code
  • Loading branch information
Ziyang-98 authored May 30, 2024
1 parent 2d344e7 commit 3eefe96
Show file tree
Hide file tree
Showing 42 changed files with 197 additions and 51 deletions.
20 changes: 20 additions & 0 deletions frontend/src/app/(authenticated)/(main)/(admin)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"use client"

import NotFoundPage from "@/app/not-found"
import MainNavigationLayout from "@/components/layouts/main-navigation-layout"
import { useUserMemberships } from "@/contexts/user-memberships-context"
import { ReactNode, useState } from "react"

interface AdminLayoutProps {
children: ReactNode
}

export default function AdminLayout({ children }: AdminLayoutProps) {
const { isAdmin } = useUserMemberships()

return isAdmin ? (
<MainNavigationLayout>{children}</MainNavigationLayout>
) : (
<NotFoundPage />
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import MainNavigationLayout from "@/components/layouts/main-navigation-layout"

export default function NonAdminLayout({
children,
}: {
children: React.ReactNode
}) {
return <MainNavigationLayout>{children}</MainNavigationLayout>
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,26 @@ import HeaderAccessory from "@/components/ui/header-accessory"
import { useRouter } from "next/navigation"
import ServicesSkeletonView from "./_views/services-skeleton-view"
import ServicesView from "./_views/services-view"
import { useUserMemberships } from "@/contexts/user-memberships-context"

export default function ServiceCatalogPage() {
const { services, isServicesLoading } = useServices()
const router = useRouter()

const { isAdmin } = useUserMemberships()
return (
<>
<div className="flex flex-col justify-start py-10">
<HeaderAccessory />
<div className="flex items-baseline">
<p className="font-bold text-3xl pt-5">Service Catalog</p>
<Button
className="ml-auto"
onClick={() => router.push("/service-catalog/create-service")}
>
Create Service
</Button>
{isAdmin && (
<Button
className="ml-auto"
onClick={() => router.push("/service-catalog/create-service")}
>
Create Service
</Button>
)}
</div>
</div>
{isServicesLoading ? (
Expand Down
34 changes: 5 additions & 29 deletions frontend/src/app/(authenticated)/(main)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
"use client"

import Navbar from "@/components/layouts/navbar"
import Sidebar from "@/components/layouts/sidebar"
import { Toaster } from "@/components/ui/toaster"
import { useCurrentUserInfo } from "@/contexts/current-user-info-context"
import { getUserProfile } from "@/lib/auth0"
import { Auth0UserProfile } from "@/types/user-profile"
import { UserMembershipsProvider } from "@/contexts/user-memberships-context"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { getCookie, hasCookie } from "cookies-next"
import { hasCookie } from "cookies-next"
import { useRouter } from "next/navigation"
import { ReactNode, useEffect, useState } from "react"

Expand All @@ -28,33 +24,13 @@ export default function MainLayout({ children }: MainLayoutProps) {

const queryClient = new QueryClient()

const [isSidebarOpen, setIsSidebarOpen] = useState(true)
const toggleSidebar = () => {
setIsSidebarOpen((isSidebarOpen) => !isSidebarOpen)
}
const userInfo = useCurrentUserInfo()

return (
render && (
<QueryClientProvider client={queryClient}>
<div
className="flex flex-row w-full min-h-[100vh]"
suppressHydrationWarning
>
<Sidebar
className={` ${isSidebarOpen ? "min-w-[300px] w-[300px]" : "min-w-0 w-0"} overflow-x-hidden transition-width duration-300 ease-in-out`}
/>
<div className="w-full">
<Navbar
toggleSidebar={toggleSidebar}
username={userInfo?.name ?? ""}
/>
<div className="w-full h-full max-h-[90vh] flex justify-center items-center flex-col relative">
<div className="w-5/6 h-full relative">{children}</div>
</div>
</div>
<UserMembershipsProvider>
{children}
<Toaster />
</div>
</UserMembershipsProvider>
</QueryClientProvider>
)
)
Expand Down
51 changes: 51 additions & 0 deletions frontend/src/components/layouts/main-navigation-layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"use client"

import Navbar from "@/components/layouts/navbar"
import Sidebar from "@/components/layouts/sidebar"
import { getUserProfile } from "@/lib/auth0"
import { Auth0UserProfile } from "@/types/user-profile"
import { getCookie } from "cookies-next"
import { ReactNode, useEffect, useState } from "react"

interface MainNavigationLayoutProps {
children: ReactNode
name?: string
}

export default function MainNavigationLayout({
children,
name,
}: MainNavigationLayoutProps) {
const [isSidebarOpen, setIsSidebarOpen] = useState(true)
const toggleSidebar = () => {
setIsSidebarOpen((isSidebarOpen) => !isSidebarOpen)
}

const [userProfile, setUserProfile] = useState<Auth0UserProfile>()
useEffect(() => {
getUserProfile(getCookie("access_token") as string)
.then((userProfile) => setUserProfile(userProfile))
.catch((error) => {
console.log(error)
})
}, [])
return (
<div
className="flex flex-row w-full min-h-[100vh]"
suppressHydrationWarning
>
<Sidebar
className={` ${isSidebarOpen ? "min-w-[300px] w-[300px]" : "min-w-0 w-0"} overflow-x-hidden transition-width duration-300 ease-in-out`}
/>
<div className="w-full">
<Navbar
toggleSidebar={toggleSidebar}
username={userProfile?.nickname ?? ""}
/>
<div className="w-full h-full max-h-[90vh] flex justify-center items-center flex-col relative">
<div className="w-5/6 h-full relative">{children}</div>
</div>
</div>
</div>
)
}
38 changes: 23 additions & 15 deletions frontend/src/components/layouts/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Link from "next/link"
import React from "react"
import { buttonVariants } from "../ui/button"
import { LibraryBig, Workflow, LockKeyhole } from "lucide-react"
import { useUserMemberships } from "@/contexts/user-memberships-context"

type LinkType = {
title: string
Expand All @@ -17,6 +18,7 @@ type LinkType = {
| "secondary"
| null
| undefined
isAdminFeature?: boolean
}

const links: LinkType[] = [
Expand All @@ -37,6 +39,7 @@ const links: LinkType[] = [
icon: LockKeyhole,
href: "/admin-service-requests-dashboard",
variant: "ghost",
isAdminFeature: true,
},
]

Expand All @@ -45,6 +48,7 @@ interface SidebarProps {
}

export default function Sidebar({ className }: SidebarProps) {
const { isAdmin } = useUserMemberships()
return (
<div className={cn("group flex flex-col gap-4 border-r", className)}>
<nav className="grid gap-y-2">
Expand All @@ -61,21 +65,25 @@ export default function Sidebar({ className }: SidebarProps) {
</span>
</Link>
</div>
{links.map((link, index) => (
<Link
key={index}
href={link.href}
className={cn(
buttonVariants({ variant: link.variant, size: "sm" }),
link.variant === "default" &&
"dark:bg-muted dark:text-white dark:hover:bg-muted dark:hover:text-white",
"justify-start"
)}
>
<link.icon className="h-5 w-5 mr-2" />
<span className="inline">{link.title}</span>
</Link>
))}
{links.map((link, index) =>
link.isAdminFeature && !isAdmin ? (
<></>
) : (
<Link
key={index}
href={link.href}
className={cn(
buttonVariants({ variant: link.variant, size: "sm" }),
link.variant === "default" &&
"dark:bg-muted dark:text-white dark:hover:bg-muted dark:hover:text-white",
"justify-start"
)}
>
<link.icon className="h-5 w-5 mr-2" />
<span className="inline">{link.title}</span>
</Link>
)
)}
</nav>
</div>
)
Expand Down
56 changes: 56 additions & 0 deletions frontend/src/contexts/user-memberships-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import useOrganizationId from "@/hooks/use-organization-id"
import { getUserMemberships } from "@/lib/service"
import { Role, UserMemberships } from "@/types/membership"
import { createContext, useContext, useEffect, useMemo, useState } from "react"

interface MembershipContextValue {
isAdmin?: boolean
}

const MembershipContext = createContext<MembershipContextValue | null>(null)

export function UserMembershipsProvider({
children,
}: {
children: React.ReactNode
}) {
const [userMemberships, setUserMemberships] = useState<UserMemberships>()

useEffect(() => {
getUserMemberships()
.then(setUserMemberships)
.catch((err) => {
console.error(err)
})
}, [])
const { organizationId } = useOrganizationId()

const isAdminOfCurrentOrg = useMemo(() => {
return userMemberships?.memberships.some(
(membership) =>
membership.org_id === organizationId &&
(membership.role === Role.Admin || membership.role === Role.Owner)
)
}, [userMemberships, organizationId])

return (
<MembershipContext.Provider
value={{
isAdmin: isAdminOfCurrentOrg,
}}
>
{children}
</MembershipContext.Provider>
)
}

export function useUserMemberships() {
const context = useContext(MembershipContext)
if (!context) {
throw new Error(
"useUserMemberships must be used within a UserMembershipsProvider"
)
}

return context
}
5 changes: 5 additions & 0 deletions frontend/src/lib/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "@/types/service-request"
import { UserInfo } from "@/types/user-profile"
import apiClient from "./apiClient"
import { UserMemberships } from "@/types/membership"

/* Pipeline */

Expand Down Expand Up @@ -150,6 +151,10 @@ export async function getUserById(userId: string): Promise<UserInfo> {
return apiClient.get(`/user/${userId}`).then((res) => res.data)
}

export async function getUserMemberships(): Promise<UserMemberships> {
return apiClient.get(`/membership`).then((res) => res.data)
}

export async function login(): Promise<UserInfo> {
return apiClient.get("login").then((res) => res.data)
}
18 changes: 18 additions & 0 deletions frontend/src/types/membership.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
enum Role {
Owner = "Owner",
Admin = "Admin",
Member = "Member",
}

type Membership = {
org_id: number
role: Role
joined_on: string
}

type UserMemberships = {
user_id: string
memberships: Membership[]
}
export { Role }
export type { Membership, UserMemberships }

0 comments on commit 3eefe96

Please sign in to comment.