-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Redirect user if missing auth cookie (#211)
- Loading branch information
1 parent
7e635d9
commit 8ecbb3a
Showing
2 changed files
with
28 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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).*)"] }; |