Skip to content

Instantly share code, notes, and snippets.

@andresgutgon
Created August 2, 2021 08:02
Show Gist options
  • Save andresgutgon/6bf8eae1e9848ed20779c94244a9d58c to your computer and use it in GitHub Desktop.
Save andresgutgon/6bf8eae1e9848ed20779c94244a9d58c to your computer and use it in GitHub Desktop.
Blitz.js Admin is ROLE 'SUPERADMIN'
import { Suspense, ReactNode } from 'react'
import { Routes, RedirectError, useSession } from "blitz"
import cn from "classnames"
import Layout from "app/core/layouts/Layout"
import type { LayoutProps } from "app/core/layouts/Layout"
const SUPERADMIN_ROLE = 'SUPERADMIN' as never
type CheckIsAdminProps = { children: ReactNode }
const CheckIsAdmin = ({ children }: CheckIsAdminProps) => {
const session = useSession()
const roles = session?.roles || []
if (!roles.includes(SUPERADMIN_ROLE)) {
const url = new URL(Routes.LoginPage().pathname, window.location.href)
url.searchParams.append("next", window.location.pathname)
const error = new RedirectError(url.toString())
error.stack = null!
throw error
}
return <>{children}</>
}
type Props = LayoutProps & {
headerTitle: string
}
const AdminLayout = ({ headerTitle, title, children }: Props) => {
return (
<Layout title={title}>
<Suspense fallback={null}>
<CheckIsAdmin>
<h1 className='text-lg font-semibold mb-4 px-6'>{headerTitle}</h1>
<div className="rounded-md shadow-sm bg-white p-6">{children}</div>
</CheckIsAdmin>
</Suspense>
</Layout>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment