-
-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Timothy Miller
committed
Nov 30, 2023
1 parent
c4b198a
commit 384985d
Showing
1 changed file
with
64 additions
and
0 deletions.
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 |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { NextResponse } from 'next/server' | ||
import type { NextRequest } from 'next/server' | ||
import jwt from '@tsndr/cloudflare-worker-jwt' | ||
|
||
export async function middleware(req: NextRequest) { | ||
console.log('middleware') | ||
|
||
const email = await getEmailFromCookie(req, 'auth-token') | ||
if (email === undefined) { | ||
return NextResponse.redirect('https://t4stack.com/sign-in') | ||
} | ||
|
||
// TODO: Check email is $50 donor tier | ||
// const isDonor = false | ||
// if (!isDonor) { | ||
// return NextResponse.redirect( | ||
// 'https://github.com/sponsors/timothymiller/sponsorships?sponsor=timothymiller&tier_id=40008&preview=false' | ||
// ) | ||
// } | ||
const res = NextResponse.next() | ||
return res | ||
} | ||
|
||
async function getEmailFromCookie( | ||
req: NextRequest, | ||
sessionTokenKey: string | ||
): Promise<string | undefined> { | ||
const JWT_VERIFICATION_KEY = process.env.JWT_VERIFICATION_KEY | ||
if (!JWT_VERIFICATION_KEY) { | ||
console.error('JWT_VERIFICATION_KEY is not set') | ||
return | ||
} | ||
|
||
try { | ||
const sessionToken = req.cookies.get(sessionTokenKey)?.value | ||
if (sessionToken === undefined) { | ||
return | ||
} | ||
const authorized = await jwt.verify(sessionToken, JWT_VERIFICATION_KEY, { | ||
algorithm: 'HS256', | ||
}) | ||
if (authorized === false) { | ||
return | ||
} | ||
|
||
const decodedToken = jwt.decode(sessionToken) | ||
|
||
// Check if token is expired | ||
const expirationTimestamp = decodedToken.payload.exp | ||
const currentTimestamp = Math.floor(Date.now() / 1000) | ||
if (!expirationTimestamp || expirationTimestamp < currentTimestamp) { | ||
return | ||
} | ||
|
||
const email = decodedToken?.payload?.email | ||
if (!email) { | ||
return | ||
} | ||
return email as string | ||
} catch (e) { | ||
console.error(e) | ||
return | ||
} | ||
} |