Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions apps/app-portal/src/app/(admin)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,14 @@ export default async function AdminLayout({
redirect("/dashboard");
}

const email = user.email ?? "";

return (
<div className="flex min-h-screen">
<AdminSidebar />

<div className="flex flex-1 flex-col desktop:ml-64">
<header className="flex h-16 items-center justify-between border-b bg-white px-6">
<h1 className="text-xl font-semibold">Admin Portal</h1>
<UserMenu email={email} />
<UserMenu />
</header>

<main className="flex-1 p-6">{children}</main>
Expand Down
4 changes: 1 addition & 3 deletions apps/app-portal/src/app/(applicant)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ export default function ApplicantLayout({
}: {
children: React.ReactNode;
}): JSX.Element {
const email = "applicant@example.com";

return (
<div className="min-h-screen">
<header className="flex h-16 items-center justify-between border-b bg-white px-6">
Expand Down Expand Up @@ -54,7 +52,7 @@ export default function ApplicantLayout({
>
Application
</Link>
<UserMenu email={email} />
<UserMenu />
</div>
</header>

Expand Down
16 changes: 15 additions & 1 deletion apps/app-portal/src/app/api/v1/user/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
//GET current session user; returns 401 if no session
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/auth/guards";

export async function GET() {
return NextResponse.json({ error: "not implemented" }, { status: 501 });
try {
const user = (await requireUser()) as {
email?: string | null;
id?: string;
isAdmin?: boolean;
};
return NextResponse.json({
email: user.email ?? null,
id: user.id,
isAdmin: user.isAdmin ?? false,
});
} catch {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
}
21 changes: 12 additions & 9 deletions apps/app-portal/src/app/auth/signin/page.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
//magic-link email entry form
"use client";
//magic-link email entry — skips straight to /dashboard if already signed in
import React from "react";

import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth/session";
import { SignInForm } from "@/components/auth/SignInForm";
import {isAdminEmail} from "@/lib/auth/roles.ts";

export default async function Page(): Promise<JSX.Element> {
// read cookie - see if valid session in DB - if so, automatically redir user to logged in part
const session = await getSession();
if (session?.user) {
redirect(isAdminEmail(session.user.email) ? "/admin" : "/dashboard");
}

export default function Page(): JSX.Element {
return (
<>
<SignInForm />
</>
);
return <SignInForm />;
}
9 changes: 7 additions & 2 deletions apps/app-portal/src/components/auth/SignInForm.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"use client"
//email input form, calls signIn("email")
import React, { useEffect, useState } from "react";
import Image from "next/image";
Expand Down Expand Up @@ -102,10 +103,14 @@ export function SignInForm() {
) : status === "loading" ? (
<p className={"w-full text-[#AAAAAA] text-end"}>
Loading{".".repeat(dotCount)}
{" ".repeat(4 - dotCount)}
{" ".repeat(4 - dotCount)}
</p>
) : status === "sent" ? (
<p className={"w-full text-[rgb(120,255,150)] text-end"}>
<p
className={
"w-full text-[rgb(120,255,150)] text-end text-[12px] whitespace-nowrap"
}
>
{/*todo: change the green*/}
Check your email for a sign-in link!
</p>
Expand Down
16 changes: 7 additions & 9 deletions apps/app-portal/src/components/auth/UserMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"use client";
//avatar + sign-out dropdown for header
import React, { useEffect, useRef, useState } from "react";
import { signOut } from "next-auth/react";
import useCurrentUser from "@/lib/auth/useCurrentUser";

interface UserMenuProps {
/** Signed-in user's email. Shown in the dropdown; first letter is the avatar. */
email: string;
}

export default function UserMenu({ email }: UserMenuProps): JSX.Element {
export default function UserMenu(): JSX.Element {
const { user } = useCurrentUser();
const email = user?.email ?? "";
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);

Expand Down Expand Up @@ -40,9 +39,8 @@ export default function UserMenu({ email }: UserMenuProps): JSX.Element {

async function handleSignOut() {
setOpen(false);
// TODO: wire to NextAuth — signOut({ callbackUrl: "/" }) once next-auth is installed.
await fetch("/auth/signout", { method: "POST" }).catch(() => {});
window.location.href = "/";
// hits /auth/signout, NextAuth automatically invalidates the session
await signOut({ callbackUrl: "/" });
}

return (
Expand Down
17 changes: 4 additions & 13 deletions apps/app-portal/src/lib/auth/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const authOptions: NextAuthOptions = {
adapter: authAdapter,
providers: [MainEmailProvider],
secret: process.env.NEXTAUTH_SECRET,
session: { strategy: "jwt" },
session: { strategy: "database", maxAge: 30 * 24 * 60 * 60 },

pages: {
signIn: "/auth/signin",
Expand All @@ -22,21 +22,12 @@ export const authOptions: NextAuthOptions = {
async signIn() {
return true;
},
// Runs when the JWT (the cookie's contents) is created/updated.
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.isAdmin = isAdminEmail(user.email);
}
return token;
},
// Runs when app code reads the session; shapes what the app sees.
async session({ session, token }) {
async session({ session, user }) {
if (session.user) {
(session.user as { id?: string; isAdmin?: boolean }).id =
token.id as string;
(session.user as { id?: string; isAdmin?: boolean }).id = user.id;
(session.user as { id?: string; isAdmin?: boolean }).isAdmin =
token.isAdmin === true;
isAdminEmail(user.email);
}
return session;
},
Expand Down
8 changes: 8 additions & 0 deletions apps/app-portal/src/lib/auth/guards.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//requireUser() and requireAdmin() helpers for route handlers
import { getSession } from "./session";

/**
* Check if current user is signed in and signed in as (basic) user
* @throws Error if unauthorized
*/
export async function requireUser() {
const session = await getSession();
if (!session?.user) {
Expand All @@ -9,6 +13,10 @@ export async function requireUser() {
return session.user;
}

/**
* Check if current user is signed in, then checks if user is admin
* @throws Error if unauthorized or if not an admin
*/
export async function requireAdmin() {
const user = await requireUser();
if (!(user as { isAdmin?: boolean }).isAdmin) {
Expand Down
36 changes: 36 additions & 0 deletions apps/app-portal/src/lib/auth/useCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"use client";
//client hook: fetches the current user from /api/v1/user; 401 -> null
import { useEffect, useState } from "react";

export interface CurrentUser {
email: string | null;
id?: string;
isAdmin?: boolean;
}

export default function useCurrentUser() {
const [user, setUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
let active = true;

fetch("/api/v1/user", { cache: "no-store" })
.then((res) => (res.ok ? (res.json() as Promise<CurrentUser>) : null))
.then((data) => {
if (active) setUser(data);
})
.catch(() => {
if (active) setUser(null);
})
.finally(() => {
if (active) setLoading(false);
});

return () => {
active = false;
};
}, []);

return { user, loading };
}