37 lines
999 B
JavaScript
37 lines
999 B
JavaScript
import { getSession } from '@zen/core/features/auth/actions';
|
|
import { hasPermission, PERMISSIONS } from '@zen/core/users';
|
|
import { redirect } from 'next/navigation';
|
|
|
|
/**
|
|
* Protect an admin page - requires authentication and admin.access permission.
|
|
* Use this in server components to require admin access.
|
|
*/
|
|
async function protectAdmin(options = {}) {
|
|
const { redirectTo = '/auth/login', forbiddenRedirect = '/' } = options;
|
|
|
|
const session = await getSession();
|
|
|
|
if (!session) {
|
|
redirect(redirectTo);
|
|
}
|
|
|
|
const allowed = await hasPermission(session.user.id, PERMISSIONS.ADMIN_ACCESS);
|
|
if (!allowed) {
|
|
redirect(forbiddenRedirect);
|
|
}
|
|
|
|
return session;
|
|
}
|
|
|
|
/**
|
|
* Check if the current user has admin.access permission.
|
|
* Non-redirecting check for conditional rendering.
|
|
*/
|
|
async function isAdmin() {
|
|
const session = await getSession();
|
|
if (!session) return false;
|
|
return hasPermission(session.user.id, PERMISSIONS.ADMIN_ACCESS);
|
|
}
|
|
|
|
export { protectAdmin, isAdmin };
|