-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
75 lines (60 loc) · 2.34 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { jwtVerify } from "jose";
import * as jose from 'jose';
import { NextResponse } from "next/server";
const AUTH_PAGES = ["/login", "/register"];
const isAuthPages = (url: string) => AUTH_PAGES.some((page) => page.startsWith(url));
const auth0JWKSUrl = process.env.NEXT_PUBLIC_AUTH0_JWKS_URL as string
const secret = process.env.NEXT_PUBLIC_ACCESS_SECRET_KEY as string
async function verifyAuth0(token: string) {
const jwks = jose.createRemoteJWKSet(new URL(auth0JWKSUrl!));
try {
await jose.jwtVerify(token.replace('Bearer ', ''), jwks);
return NextResponse.next();
} catch (e) {
console.error('Authentication failed: Token could not be verified')
const response = NextResponse.next();
response.cookies.delete("token");
response.cookies.delete("provider");
NextResponse.redirect(new URL(`/`));
return response;
}
}
export async function middleware(request: any) {
const { url, nextUrl, cookies } = request;
const { value: token } = cookies.get("accessToken") ?? { value: null };
const { value: provider } = cookies.get("provider") ?? { value: null };
let hasVerifiedToken;
// parse Auth0 token
if (provider === 'auth0') {
hasVerifiedToken = token && (await verifyAuth0(token));
// parse JWT token
} else if (provider === 'jwt') {
try {
const decodedToken = await jwtVerify(token, new TextEncoder().encode(secret));
hasVerifiedToken = !!decodedToken;
} catch (error) {
const response = NextResponse.next();
NextResponse.redirect(new URL(`/`, url));
return response;
}
}
const isAuthPageRequested = isAuthPages(nextUrl.pathname);
if (isAuthPageRequested) {
if (!hasVerifiedToken) {
const response = NextResponse.next();
return response;
}
const response = NextResponse.redirect(new URL(`/`, url));
return response;
}
if (!hasVerifiedToken) {
const searchParams = new URLSearchParams(nextUrl.searchParams);
searchParams.set("next", nextUrl.pathname);
const response = NextResponse.redirect(
new URL(`/login?${searchParams}`, url)
);
return response;
}
return NextResponse.next();
}
export const config = { matcher: ["/login", "/register", "/users/:path*", '/profile/:path*', '/companies/:path*'] };