-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
99 lines (83 loc) · 2.93 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { NextResponse, type NextMiddleware } from "next/server";
import { type NullableAuthResponse } from "./models/AuthModel";
import { exchangeRefreshTokenForAuthTokens } from "psn-api";
import { cookies } from "next/headers";
import { createClient } from "./utils/supabase/middleware";
const SB_KEY = process.env.NEXT_PUBLIC_SUPABASE_KEY ?? null;
const publicPages = new Set<string>([
"/signIn",
"/signUp",
"/setPassword",
"/forgot",
]);
export const config = {
matcher: "/((?!api|static|.*\\..*|_next|favicon.ico).*)",
};
const refreshTokens = async (token: string): Promise<NullableAuthResponse> => {
let authorization: NullableAuthResponse = null;
try {
console.info("refresh token", token);
authorization = await exchangeRefreshTokenForAuthTokens(token);
console.info("refreshed auth", authorization);
} catch (error) {
console.error("unable to refresh tokens", error);
}
return authorization;
};
const resetCookies = (res: NextResponse): NextResponse => {
const allCookies = cookies().getAll();
console.info("cookies before reset", JSON.stringify(allCookies));
res.cookies.delete("psn-access-token");
res.cookies.delete("psn-refresh-token");
if (SB_KEY != null) res.cookies.delete(`sb-${SB_KEY}-auth-token`);
return res;
};
export const middleware: NextMiddleware = async (req) => {
const { supabase, res } = createClient(req);
const {
data: { session },
} = await supabase.auth.getSession();
let refreshed_auth: NullableAuthResponse = null;
let access_token = req.cookies.get("psn-access-token")?.value;
let refresh_token = req.cookies.get("psn-refresh-token")?.value;
const pathname = req.nextUrl.pathname;
const isPublicPage = publicPages.has(pathname);
const isHomePage = pathname === "/";
if (access_token === undefined && refresh_token !== undefined) {
refreshed_auth = await refreshTokens(refresh_token);
if (refreshed_auth != null) {
const { accessToken, refreshToken } = refreshed_auth;
access_token = accessToken;
refresh_token = refreshToken;
}
}
const isAuth = access_token !== undefined && session != null;
console.info(
"middleware user",
pathname,
session?.user?.email,
session?.expires_at,
req.headers.get("user-agent"),
);
console.info(
"middleware token",
access_token !== undefined ? access_token.slice(-5) : undefined,
refresh_token !== undefined ? refresh_token.slice(-5) : undefined,
refreshed_auth === null,
);
if (!isAuth && isHomePage) {
return resetCookies(res);
}
if (!isAuth && !isPublicPage) {
const redirectRes = NextResponse.redirect(new URL("/signIn", req.url));
return resetCookies(redirectRes);
}
if (isAuth && isPublicPage) {
return NextResponse.redirect(new URL("/", req.url));
}
if (refreshed_auth != null) {
const { accessToken, expiresIn } = refreshed_auth;
res.cookies.set("psn-access-token", accessToken, { maxAge: expiresIn });
}
return res;
};