forked from COSC-499-W2023/year-long-project-team-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
43 lines (40 loc) · 1.53 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { withAuth } from 'next-auth/middleware'
import { NextRequest, NextResponse } from 'next/server'
import logger from '@/utils/logger'
const protectedPages = ['/dashboard', '/submission-box', '/video']
export default withAuth(
async function middleware(request: NextRequest) {
// Check if we should redirect when a user's email isn't verified
const cookies = request.cookies
const isLoggedIn = cookies.has('next-auth.session-token')
if (
isLoggedIn &&
protectedPages.some(page => request.nextUrl.pathname.startsWith(page))
) {
const res = await fetch(process.env.NEXT_PUBLIC_BASE_URL + '/api/verify-email/is-verified', {
method: 'GET',
headers: {
'cookie': cookies.toString(),
},
})
const { isVerified } = await res.json()
if (!isVerified) {
const url = request.nextUrl.clone()
url.pathname = '/verify-email'
return NextResponse.redirect(url)
}
}
if (request.nextUrl.pathname.startsWith('/api')) {
logger.info(`API request: ${ request.nextUrl.pathname }`)
}
return NextResponse.next()
},
{
secret: process.env.NEXT_PUBLIC_NEXTAUTH_SECRET,
callbacks: {
authorized: ({ req, token }) => {
return !(token === null && protectedPages.some((page) => req.nextUrl.pathname.startsWith(page)))
},
},
}
)