Skip to content

Commit

Permalink
Redirect user if missing auth cookie (#211)
Browse files Browse the repository at this point in the history
  • Loading branch information
codetheweb authored Oct 13, 2023
1 parent 7e635d9 commit 8ecbb3a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/backend/auth/options.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
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,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}),
],
adapter: createPersistedAuthAdapter(db),
pages: {
signIn: "/signInPage",
},
});
21 changes: 21 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -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).*)"] };

0 comments on commit 8ecbb3a

Please sign in to comment.