-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathwithMiddlewareAuth.ts
161 lines (152 loc) · 5.09 KB
/
withMiddlewareAuth.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import { NextResponse } from 'next/server';
import { NextMiddleware } from 'next/server';
import {
CookieOptions,
setCookies,
COOKIE_OPTIONS,
TOKEN_REFRESH_MARGIN,
NextRequestMiddlewareAdapter,
NextResponseMiddlewareAdapter,
jwtDecoder,
User
} from '@supabase/auth-helpers-shared';
class NoPermissionError extends Error {
constructor(message: string) {
super(message);
}
get name() { return this.constructor.name }
}
export interface withMiddlewareAuthOptions {
/**
* Path relative to the site root to redirect an
* unauthenticated visitor.
*
* The original request route will be appended via
* a `redirectedFrom` query parameter, ex: `?redirectedFrom=%2Fdashboard`
*/
redirectTo?: string;
cookieOptions?: CookieOptions;
tokenRefreshMargin?: number;
authGuard?: {
isPermitted: (user: User) => Promise<boolean>;
redirectTo: string;
};
}
export type withMiddlewareAuth = (
options?: withMiddlewareAuthOptions
) => NextMiddleware;
export const withMiddlewareAuth: withMiddlewareAuth =
(options: withMiddlewareAuthOptions = {}) =>
async (req) => {
try {
if (
!process.env.NEXT_PUBLIC_SUPABASE_URL ||
!process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
) {
throw new Error(
'NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables are required!'
);
}
if (!req.cookies) {
throw new Error('Not able to parse cookies!');
}
const cookieOptions = { ...COOKIE_OPTIONS, ...options.cookieOptions };
const tokenRefreshMargin =
options.tokenRefreshMargin ?? TOKEN_REFRESH_MARGIN;
const access_token = req.cookies[`${cookieOptions.name!}-access-token`];
const refresh_token = req.cookies[`${cookieOptions.name!}-refresh-token`];
const res = NextResponse.next();
const getUser = async (): Promise<{
user: any;
error: any;
}> => {
if (!access_token) {
throw new Error('No cookie found!');
}
// Get payload from access token.
const jwtUser = jwtDecoder(access_token);
if (!jwtUser?.exp) {
throw new Error('Not able to parse JWT payload!');
}
const timeNow = Math.round(Date.now() / 1000);
if (jwtUser.exp < timeNow + tokenRefreshMargin) {
if (!refresh_token) {
throw new Error('No refresh_token cookie found!');
}
const requestHeaders: HeadersInit = new Headers();
requestHeaders.set('accept', 'json');
requestHeaders.set(
'apiKey',
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
requestHeaders.set(
'authorization',
`Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`
);
const data = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/auth/v1/token?grant_type=refresh_token`,
{
method: 'POST',
headers: requestHeaders,
body: JSON.stringify({ refresh_token })
}
)
.then((res) => res.json())
.catch((e) => ({
error: String(e)
}));
setCookies(
new NextRequestMiddlewareAdapter(req),
new NextResponseMiddlewareAdapter(res),
[
{ key: 'access-token', value: data!.access_token },
{ key: 'refresh-token', value: data!.refresh_token! }
].map((token) => ({
name: `${cookieOptions.name}-${token.key}`,
value: token.value,
domain: cookieOptions.domain,
maxAge: cookieOptions.lifetime ?? 0,
path: cookieOptions.path,
sameSite: cookieOptions.sameSite
}))
);
return { user: data?.user ?? null, error: data?.error };
}
return { user: jwtUser, error: null };
};
const authResult = await getUser();
if (authResult.error) {
throw new Error(
`Authorization error, redirecting to login page: ${authResult.error.message}`
);
} else if (!authResult.user) {
throw new Error('No auth user, redirecting');
} else if (
options.authGuard &&
!(await options.authGuard.isPermitted(authResult.user))
) {
throw new NoPermissionError('User is not permitted, redirecting');
}
// Authentication successful, forward request to protected route
return res;
} catch (err: unknown) {
let { redirectTo = '/' } = options;
if (
err instanceof NoPermissionError &&
!!options?.authGuard?.redirectTo
) {
redirectTo = options.authGuard.redirectTo;
}
if (err instanceof Error) {
console.log(
`Could not authenticate request, redirecting to ${redirectTo}:`,
err
);
}
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = redirectTo;
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
// Authentication failed, redirect request
return NextResponse.redirect(redirectUrl);
}
};