MS Authentication - PROCEED-Labs/proceed GitHub Wiki
Authentication is the security process that verifies a user's identity before granting access to the application. In technology, we use authentication to confirm that users or services are who they claim to be.
For authentication in the MS, we use NextAuth. We configured it (in src/management-system-v2/lib/auth.ts) to store a user's session in their cookies as a JWT.
NextAuth stores user data in a session cookie in the user's browser. This cookie contains the user's database entry, which is updated when they modify their profile data. However, this information is not always reliable because users may update their profile from a different browser, and those changes won't be reflected in the session cookies of other browsers. The only reliable piece of information is the user's ID, which is immutable.
To access authentication information in the MS backend, use getCurrentUser. This function returns NextAuth's session object and, if the user is authenticated, also includes their database entry and system admin status.
// This does not include error handling!
export function Page() {
const { user, systemAdmin, session } = getCurrentUser();
if (systemAdmin) {
return <h1>You're a system admin with the role of {systemAdmin.role}</h1>;
}
if (user) {
return <h1>You're signed in and your email is {user.email}</h1>;
}
return <h1>You're not signed in</h1>;
}In client-side components, you can use the useSession hook to access NextAuth's session object. There are few cases where you'll need this.
"use client";
import { useSession } from "next-auth/react";
export function ClientComponent() {
const { data: session, status } = useSession();
if (status === "loading") {
return <h1>Loading...</h1>;
}
if (session?.user) {
return <h1>You're signed in and your email is {session.user.email}</h1>;
}
return <h1>You're not signed in</h1>;
}