-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
index.ts
233 lines (203 loc) · 7.38 KB
/
index.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import type { AuthConfig } from '@auth/core';
import { Auth, skipCSRFCheck } from '@auth/core';
import type { AuthAction, Session } from '@auth/core/types';
import { implicit$FirstArg, type QRL } from '@builder.io/qwik';
import {
globalAction$,
routeLoader$,
z,
zod$,
type RequestEvent,
type RequestEventCommon,
} from '@builder.io/qwik-city';
import { isServer } from '@builder.io/qwik';
import { parseString, splitCookiesString } from 'set-cookie-parser';
export type GetSessionResult = Promise<{ data: Session | null; cookie: any }>;
export type QwikAuthConfig = AuthConfig;
const actions: AuthAction[] = [
'providers',
'session',
'csrf',
'signin',
'signout',
'callback',
'verify-request',
'error',
];
export function serverAuthQrl(authOptions: QRL<(ev: RequestEventCommon) => QwikAuthConfig>) {
const useAuthSignin = globalAction$(
async ({ providerId, callbackUrl: deprecated, options, authorizationParams }, req) => {
if (deprecated) {
console.warn(
'\x1b[33mWARNING: callbackUrl is deprecated - use options.callbackUrl instead\x1b[0m'
);
}
const { callbackUrl = deprecated ?? defaultCallbackURL(req), ...rest } = options ?? {};
const isCredentials = providerId === 'credentials';
const auth = await patchAuthOptions(authOptions, req);
const body = new URLSearchParams({ callbackUrl: callbackUrl as string });
Object.entries(rest).forEach(([key, value]) => {
body.set(key, String(value));
});
const baseSignInUrl = `/api/auth/${isCredentials ? 'callback' : 'signin'}${
providerId ? `/${providerId}` : ''
}`;
const signInUrl = `${baseSignInUrl}?${new URLSearchParams(authorizationParams)}`;
const data = await authAction(body, req, signInUrl, auth);
// set authjs.callback-url cookie. Fix for https://github.com/QwikDev/qwik/issues/5227
req.cookie.set('authjs.callback-url', callbackUrl, {
path: '/',
});
if (data.url) {
throw req.redirect(301, data.url);
}
},
zod$({
providerId: z.string().optional(),
callbackUrl: z.string().optional(),
options: z
.object({
callbackUrl: z.string(),
})
.passthrough()
.partial()
.optional(),
authorizationParams: z
.union([z.string(), z.custom<URLSearchParams>(), z.record(z.string())])
.optional(),
})
);
const useAuthSignout = globalAction$(
async ({ callbackUrl }, req) => {
callbackUrl ??= defaultCallbackURL(req);
const auth = await patchAuthOptions(authOptions, req);
const body = new URLSearchParams({ callbackUrl });
await authAction(body, req, `/api/auth/signout`, auth);
},
zod$({
callbackUrl: z.string().optional(),
})
);
const useAuthSession = routeLoader$((req) => {
return req.sharedMap.get('session') as Session | null;
});
const onRequest = async (req: RequestEvent) => {
if (isServer) {
const prefix: string = '/api/auth';
const action = req.url.pathname.slice(prefix.length + 1).split('/')[0] as AuthAction;
const auth = await patchAuthOptions(authOptions, req);
if (actions.includes(action) && req.url.pathname.startsWith(prefix + '/')) {
// Casting to `Response` because, something is off with the types in `@auth/core` here:
// Without passing `raw`, it should know it's supposed to return a `Response` object, but it doesn't.
// https://github.com/nextauthjs/next-auth/blob/a67cfed64d96da1ecfc75f02e7106d9a403012be/packages/core/src/index.ts#L61-L69
const res = (await Auth(req.request, auth)) as Response;
const cookie = res.headers.get('set-cookie');
if (cookie) {
req.headers.set('set-cookie', cookie);
res.headers.delete('set-cookie');
fixCookies(req);
}
throw req.send(res);
} else {
const { data, cookie } = await getSessionData(req.request, auth);
req.sharedMap.set('session', data);
if (cookie) {
req.headers.set('set-cookie', cookie);
fixCookies(req);
}
}
}
};
return {
useAuthSignin,
useAuthSignout,
useAuthSession,
onRequest,
};
}
export const serverAuth$ = /*#__PURE__*/ implicit$FirstArg(serverAuthQrl);
async function authAction(
body: URLSearchParams | undefined,
req: RequestEventCommon,
path: string,
authOptions: QwikAuthConfig
) {
const request = new Request(new URL(path, req.request.url), {
method: req.request.method,
headers: req.request.headers,
body: body,
});
request.headers.set('content-type', 'application/x-www-form-urlencoded');
// Casting to `Response` because, something is off with the types in `@auth/core` here:
// Without passing `raw`, it should know it's supposed to return a `Response` object, but it doesn't.
// https://github.com/nextauthjs/next-auth/blob/a67cfed64d96da1ecfc75f02e7106d9a403012be/packages/core/src/index.ts#L61-L69
const res = (await Auth(request, {
...authOptions,
skipCSRFCheck,
})) as Response;
const cookies: string[] = [];
res.headers.forEach((value, key) => {
if (key === 'set-cookie') {
// while browsers would support setting multiple cookies, the fetch implementation does not, so we join them later.
cookies.push(value);
} else if (!req.headers.has(key)) {
req.headers.set(key, value);
}
});
if (cookies.length > 0) {
req.headers.set('set-cookie', cookies.join(', '));
}
fixCookies(req);
try {
return await res.json();
} catch (error) {
return await res.text();
}
}
const fixCookies = (req: RequestEventCommon) => {
req.headers.set('set-cookie', req.headers.get('set-cookie') || '');
const cookie = req.headers.get('set-cookie');
if (cookie) {
req.headers.delete('set-cookie');
splitCookiesString(cookie).forEach((cookie) => {
const { name, value, ...rest } = parseString(cookie);
req.cookie.set(name, value, rest as any);
});
}
};
export const ensureAuthMiddleware = (req: RequestEvent) => {
const isLoggedIn = req.sharedMap.has('session');
if (!isLoggedIn) {
throw req.error(403, 'sfs');
}
};
const defaultCallbackURL = (req: RequestEventCommon) => {
req.url.searchParams.delete('qaction');
return req.url.href;
};
async function getSessionData(req: Request, options: AuthConfig): GetSessionResult {
options.secret ??= process.env.AUTH_SECRET;
options.trustHost ??= true;
const url = new URL('/api/auth/session', req.url);
// Casting to `Response` because, something is off with the types in `@auth/core` here:
// Without passing `raw`, it should know it's supposed to return a `Response` object, but it doesn't.
// https://github.com/nextauthjs/next-auth/blob/a67cfed64d96da1ecfc75f02e7106d9a403012be/packages/core/src/index.ts#L61-L69
const response = (await Auth(new Request(url, { headers: req.headers }), options)) as Response;
const { status = 200 } = response;
const data = await response.json();
const cookie = response.headers.get('set-cookie');
if (!data || !Object.keys(data).length) {
return { data: null, cookie };
}
if (status === 200) {
return { data, cookie };
}
throw new Error(data.message);
}
const patchAuthOptions = async (
authOptions: QRL<(ev: RequestEventCommon) => QwikAuthConfig>,
req: RequestEventCommon
) => {
const options = await authOptions(req);
return { ...options, basePath: '/api/auth' };
};