import type { User } from './server' import { UserRole } from '@admin/types/auth' import { getAdminPostLoginPath } from '@admin/utils/auth/get-admin-post-login-path' import { isUserRole } from '@admin/utils/auth/is-user-role' import { headers } from 'next/headers' import { redirect } from 'next/navigation' import { connection } from 'next/server' import { cache } from 'react' import { auth } from './server' export { UserRole } from '@admin/types/auth' interface GetSessionOptions { disableCookieCache?: boolean } export const getSession = cache(async (options: GetSessionOptions = {}) => { // Better Auth checks the session expiry against `new Date()`. With // `partialPrefetching`, `headers()` already resolves during the runtime // prefetch, where Next rejects that read, so wait for the real request. await connection() const session = await auth.api.getSession({ query: options.disableCookieCache ? { disableCookieCache: true } : undefined, headers: await headers() }) return session }) export async function requireRole(allowedRoles: readonly UserRole[]): Promise { const session = await getSession({ disableCookieCache: true }) if (!session?.user) { redirect('/admin/login') } const user = session.user const role = isUserRole(user.role) ? user.role : UserRole.USER if (!allowedRoles.includes(role)) { redirect(getAdminPostLoginPath(role)) } return user }