-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
65 lines (61 loc) · 1.84 KB
/
middleware.ts
File metadata and controls
65 lines (61 loc) · 1.84 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { withAuth } from '@kinde-oss/kinde-auth-nextjs/middleware'
import { getKindeServerSession } from '@kinde-oss/kinde-auth-nextjs/server'
import { NextResponse } from 'next/server'
import { normalizeEmail } from '~/utils/misc'
export default withAuth(
async function middleware(req) {
const res = NextResponse.next()
// Add CORS headers for auth routes
if (req.nextUrl.pathname.startsWith('/api/auth/')) {
res.headers.set('Access-Control-Allow-Origin', '*')
res.headers.set(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS',
)
res.headers.set(
'Access-Control-Allow-Headers',
'Content-Type, Authorization',
)
}
// Check if user is authenticated and not the admin on admin paths
const { getUser } = getKindeServerSession()
const user = await getUser()
if (
req.nextUrl.pathname.startsWith('/admin') &&
user &&
normalizeEmail(user.email) !==
normalizeEmail(process.env.ADMIN_EMAIL || '')
) {
// Redirect to logout and home
const logoutUrl = new URL('/api/auth/logout', req.url)
logoutUrl.searchParams.set('post_logout_redirect_url', '/')
return NextResponse.redirect(logoutUrl)
}
return res
},
{
publicPaths: [
'/',
'/blog',
'/about',
'/projects',
'/snippets',
'/books',
'/movies',
'/tags',
'/api/activities',
// Allow Kinde auth routes without requiring a session (login/register/callback)
'/api/auth/:path*',
'/audio/',
],
},
)
export const config = {
matcher: [
// Only run middleware for admin pages and auth API routes. This prevents
// the middleware from intercepting unknown (gibberish) paths so Next's
// custom 404 can render normally.
'/admin/:path*',
'/api/auth/:path*',
],
}