Authentication & Authorization
The application uses Better Auth for authentication, providing a robust and flexible system for managing user sessions and identity.
Configuration
Client-side Authentication (src/lib/auth/auth-client.ts)
The client is initialized with several plugins, including emailOTPClient and inferAdditionalFields to extend the user profile with custom fields like role, subscribed, and country.
import { API_URL } from "@/lib/constant";
import { emailOTPClient, inferAdditionalFields } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({
baseURL: API_URL + "/auth",
plugins: [
emailOTPClient(),
inferAdditionalFields({
user: {
user_id: { type: "string", input: false },
full_name: { type: "string", input: false },
role: { type: "string", input: false },
subscribed: { type: "boolean", input: true },
country: { type: "string", input: true },
},
}),
],
fetchOptions: {
credentials: "include",
onError: (e) => {
// Global error handling, e.g., Rate limiting (429)
},
},
});Server-side Authentication (src/lib/auth/auth-server.ts)
For server components and middleware, we use a helper to extract session information from headers.
import { headers } from "next/headers";
import { authClient } from "./auth-client";
export const getAuth = async (request?: Request) => {
const fetchHeaders = request ? request.headers : await headers();
const { data } = await authClient.getSession({
fetchOptions: {
headers: fetchHeaders,
},
});
return data;
};Route Protection
Protected routes are managed via a ProtectedLayoutWrapper component which ensures the user is authenticated before rendering the children.
// src/layouts/partials/protected-layout-wrapper.tsx
export default function ProtectedLayoutWrapper({ children }) {
const { data: auth, isPending } = authClient.useSession();
const router = useRouter();
useEffect(() => {
if (!isPending && !auth) {
router.replace("/login");
}
}, [auth, isPending, router]);
if (isPending || !auth) {
return <Loading />;
}
return <>{children}</>;
}User Roles & Permissions
The application implements role-based access control (RBAC):
- Owner: Full access to organization and all projects.
- Admin: Can manage projects and members within organization.
- Editor: Can edit content but not manage organization settings or users.
Last updated on