diff --git a/src/backend/auth/options.ts b/src/backend/auth/options.ts index 3508770c..a08fa6b5 100644 --- a/src/backend/auth/options.ts +++ b/src/backend/auth/options.ts @@ -1,8 +1,11 @@ import GoogleProvider from "next-auth/providers/google"; import { createPersistedAuthAdapter } from "@/backend/auth/adapter"; import { KyselyDatabaseInstance } from "../lib"; +import type { NextAuthOptions } from "next-auth"; -export const getNextAuthOptions = (db: KyselyDatabaseInstance) => ({ +export const getNextAuthOptions = ( + db: KyselyDatabaseInstance +): NextAuthOptions => ({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID as string, @@ -10,4 +13,7 @@ export const getNextAuthOptions = (db: KyselyDatabaseInstance) => ({ }), ], adapter: createPersistedAuthAdapter(db), + pages: { + signIn: "/signInPage", + }, }); diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 00000000..c2a6c0b7 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,21 @@ +import { NextRequest, NextResponse } from "next/server"; + +/** + * Our API routes are already protected, this middleware applies to UI routes like /students. + * If a user isn't logged in, we redirect them to sign-in. + * This **does not** check for the validity of the session, only that a cookie exists; so it shouldn't be generally used to protect routes. + * + * Ideally we would use NextAuth's built-in Next.js middleware: https://next-auth.js.org/configuration/nextjs#middleware + * However, their middleware doesn't yet work with database sessions. + */ +export function middleware(request: NextRequest) { + if (!request.cookies.get("next-auth.session-token")) { + const url = request.nextUrl.clone(); + url.pathname = "/signInPage"; + return NextResponse.redirect(url); + } + + return NextResponse.next(); +} + +export const config = { matcher: ["/((?!img|_next|api|signInPage).*)"] };