Authorization
Authorize Access

Flexible Authorization with requireAuth Function

In your Full-Stack Kit, the requireAuth function serves as a powerful tool for handling user authorization, providing flexibility and fine-grained control over access to different pages within your application.

Why use requireAuth?

Default Authentication Check

By default, requireAuth checks whether the user is authenticated. If not, it redirects the user to the sign-in page. This behavior is not only convenient but also configurable in the app.config.ts file. You can easily specify a different redirect page if needed.

// Example in app.config.ts
redirects: {
  whenNotLoggedInAndAccessingProtectedPage: "/custom-page",
  // ... other redirect configurations
};

Role-Based Authorization

One of the standout features of the requireAuth() function is its ability to perform role-based authorization. When a roles array is provided to the function, it checks whether the current user possesses the specified roles. If the user authenticated but don't have the required roles, { authorized: false } is returned, preventing access to the page. On the other hand, if the user is authenticated and has the necessary roles, { authorized: true } is returned, granting access.

Example Usage

Example 1:

In this example, the requireAuth() function is used to ensure that the user is authenticated before rendering the page. If the user is not authenticated, the function redirects the user to the sign-in page. Else it fetches the user data and renders the page.

import { requireAuth } from "@/lib/auth";
 
export default async function Page() {
  await requireAuth();
 
  const data = await fetchUserData();
 
  return (
    <PlatformPageContainer pageHeaderTitle="My account">
      <AccountView data={data} />
    </PlatformPageContainer>
  );
}

Example 2:

In this example, the requireAuth() function is utilized with role-based authorization. It checks if the user has the Role.ADMIN role and renders the page accordingly. If the user is authenticated but is not authorized, which means the user do not have the Role.ADMIN role, the <Unauthorized /> component is rendered.

import { requireAuth } from "@/lib/auth";
import { Role } from "@/lib/auth/roles";
 
export default async function Page() {
  const { authorized } = await requireAuth([Role.ADMIN]);
 
  if (!authorized) return <Unauthorized />;
 
  return (
    <PlatformPageContainer pageHeaderTitle="Admin Dashboard">
      <AdminDashboard />
    </PlatformPageContainer>
  );
}

The requireAuth function offers a versatile and intuitive way to manage user authorization, making it an essential tool for ensuring secure and controlled access throughout your Full-Stack Kit application.

If you have question, feel free to join the community discord and ask for help. We are here to help you ship your app faster and with less bugs.

Full-Stack-Kit © 2024