-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathindex.ts
379 lines (346 loc) · 10.6 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/**
*
* :::warning
* `@auth/qwik` is currently experimental. The API _will_ change in the future.
* :::
*
* Qwik Auth is the official Qwik integration for Auth.js.
* It provides a simple way to add authentication to your Qwik app in a few lines of code.
*
* ## Installation
* ```bash npm2yarn
* npm install @auth/qwik
* ```
*
* ## Usage
*
* ### Provider Configuration
*
* Create a `[email protected]` file in the routes folder
*
* import { QwikAuth$ } from "@auth/qwik"
* import GitHub from "@auth/qwik/providers/github"
*
* export const {
* onRequest, useSession, useSignIn, useSignOut
* } = QwikAuth$(() => ({ providers: [GitHub] }))
*
* ## Signing in and signing out
*
* Sign In via form
*
* import { component$ } from '@builder.io/qwik';
* import { Form } from '@builder.io/qwik-city';
* import { useSignIn } from '~/routes/plugin@auth';
*
* export default component$(() => {
* const signIn = useSignIn();
* return (
* <Form action={signIn}>
* <input type="hidden" name="providerId" value="github" />
* <input type="hidden" name="options.redirectTo" value="http://qwik-auth-example.com/dashboard" />
* <button>Sign In</button>
* </Form>
* );
* });
*
* Sign In via code
*
* import { component$ } from '@builder.io/qwik';
* import { useSignIn } from '~/routes/plugin@auth';
*
* export default component$(() => {
* const signIn = useSignIn();
* return (
* <button onClick$={() => signIn.submit({ providerId: 'github', options: { redirectTo: 'http://qwik-auth-example.com/dashboard' } })}>Sign In</button>
* );
* });
*
* Sign out via form
*
* import { component$ } from '@builder.io/qwik';
* import { Form } from '@builder.io/qwik-city';
* import { useSignOut } from '~/routes/plugin@auth';
*
* export default component$(() => {
* const signOut = useSignOut();
* return (
* <Form action={signOut}>
* <input type="hidden" name="redirectTo" value="/signedout" />
* <button>Sign Out</button>
* </Form>
* );
* });
*
* Sign out via code
*
* import { component$ } from '@builder.io/qwik';
* import { useSignOut } from '~/routes/plugin@auth';
*
* export default component$(() => {
* const signOut = useSignOut();
* return <button onClick$={() => signOut.submit({ redirectTo: '/signedout' })}>Sign Out</button>;
* });
*
* ## Managing the session
*
* import { component$ } from '@builder.io/qwik';
* import { useSession } from '~/routes/plugin@auth';
*
* export default component$(() => {
* const session = useSession();
* return <p>{session.value?.user?.email}</p>;
* });
*
* ## Authorization
*
* Session data can be accessed via the route event.sharedMap.
* So a route can be protected and redirect using something like this located in a layout.tsx or page index.tsx:
*
* export const onRequest: RequestHandler = (event) => {
* const session = event.sharedMap.get("session")
* if (!session || new Date(session.expires) < new Date()) {
* throw event.redirect(302, `/auth/signin?redirectTo=${event.url.pathname}`);
* }
* };
*
* ```
*
* @module @auth/qwik
*/
import type { AuthConfig } from "@auth/core"
import { Auth, isAuthAction, skipCSRFCheck, customFetch } from "@auth/core"
import { AuthAction, Session } from "@auth/core/types"
import { implicit$FirstArg, type QRL } from "@builder.io/qwik"
import {
globalAction$,
routeLoader$,
z,
zod$,
type RequestEventCommon,
} from "@builder.io/qwik-city"
import { EnvGetter } from "@builder.io/qwik-city/middleware/request-handler"
import { isServer } from "@builder.io/qwik/build"
import { parseString, splitCookiesString } from "set-cookie-parser"
export { customFetch }
export { AuthError, CredentialsSignin } from "@auth/core/errors"
export type {
Account,
DefaultSession,
Profile,
Session,
User,
} from "@auth/core/types"
/** Configure the {@link QwikAuth$} method. */
export interface QwikAuthConfig extends Omit<AuthConfig, "raw"> {}
export type GetSessionResult = Promise<{ data: Session | null; cookie: any }>
/** @internal */
export function QwikAuthQrl(
authOptions: QRL<(ev: RequestEventCommon) => QwikAuthConfig>
) {
const useSignIn = globalAction$(
async (
{ providerId, redirectTo: _redirectTo, options, authorizationParams },
req
) => {
const { redirectTo = _redirectTo ?? defaultRedirectTo(req), ...rest } =
options ?? {}
const isCredentials = providerId === "credentials"
const authOpts = await authOptions(req)
setEnvDefaults(req.env, authOpts)
const body = new URLSearchParams({ callbackUrl: redirectTo })
Object.entries(rest).forEach(([key, value]) => {
body.set(key, String(value))
})
const baseSignInUrl = `/auth/${isCredentials ? "callback" : "signin"}${
providerId ? `/${providerId}` : ""
}`
const signInUrl = `${baseSignInUrl}?${new URLSearchParams(
authorizationParams
)}`
const data = await authAction(body, req, signInUrl, authOpts)
if (data.url) {
throw req.redirect(301, data.url)
}
},
zod$({
providerId: z.string().optional(),
redirectTo: z.string().optional(),
options: z
.object({
redirectTo: z.string(),
})
.passthrough()
.partial()
.optional(),
authorizationParams: z
.union([z.string(), z.custom<URLSearchParams>(), z.record(z.string())])
.optional(),
})
)
const useSignOut = globalAction$(
async ({ redirectTo }, req) => {
redirectTo ??= defaultRedirectTo(req)
const authOpts = await authOptions(req)
setEnvDefaults(req.env, authOpts)
const body = new URLSearchParams({ callbackUrl: redirectTo })
await authAction(body, req, `/auth/signout`, authOpts)
},
zod$({
redirectTo: z.string().optional(),
})
)
const useSession = routeLoader$((req) => {
return req.sharedMap.get("session") as Session | null
})
const onRequest = async (req: RequestEventCommon) => {
if (isServer) {
const prefix: string = "/auth"
const action = req.url.pathname
.slice(prefix.length + 1)
.split("/")[0] as AuthAction
const authOpts = await authOptions(req)
setEnvDefaults(req.env, authOpts)
if (isAuthAction(action) && req.url.pathname.startsWith(prefix + "/")) {
const res = (await Auth(req.request, authOpts)) 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, authOpts)
req.sharedMap.set("session", data)
if (cookie) {
req.headers.set("set-cookie", cookie)
fixCookies(req)
}
}
}
}
return { useSignIn, useSignOut, useSession, onRequest }
}
/**
* Initialize Qwik Auth.
*
* @example
* ```ts title="[email protected]"
* import { QwikAuth } from "@auth/qwik"
* import GitHub from "@auth/qwik/providers/github"
*
* export const {
* onRequest, useSession, useSignIn, useSignOut
* } = QwikAuth$(() => ({ providers: [GitHub] }))
* ```
*/
export const QwikAuth$ = /*#__PURE__*/ implicit$FirstArg(QwikAuthQrl)
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")
const res = (await Auth(request, authOptions)) 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 {
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)
})
}
}
const defaultRedirectTo = (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("/auth/session", req.url)
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)
}
export const setEnvDefaults = (env: EnvGetter, config: AuthConfig) => {
config.basePath = "/auth"
if (!config.secret?.length) {
config.secret = []
const secret = env.get("AUTH_SECRET")
if (secret) {
config.secret.push(secret)
}
for (const i of [1, 2, 3]) {
const secret = env.get(`AUTH_SECRET_${i}`)
if (secret) {
config.secret.unshift(secret)
}
}
}
config.redirectProxyUrl ??= env.get("AUTH_REDIRECT_PROXY_URL")
config.trustHost ??= !!(
env.get("AUTH_URL") ??
env.get("AUTH_TRUST_HOST") ??
env.get("VERCEL") ??
env.get("CF_PAGES") ??
env.get("NODE_ENV") !== "production"
)
config.skipCSRFCheck = skipCSRFCheck
config.providers = config.providers.map((p) => {
const finalProvider = typeof p === "function" ? p({}) : p
const ID = finalProvider.id.toUpperCase().replace(/-/g, "_")
if (finalProvider.type === "oauth" || finalProvider.type === "oidc") {
finalProvider.clientId ??= env.get(`AUTH_${ID}_ID`)
finalProvider.clientSecret ??= env.get(`AUTH_${ID}_SECRET`)
if (finalProvider.type === "oidc") {
finalProvider.issuer ??= env.get(`AUTH_${ID}_ISSUER`)
}
} else if (finalProvider.type === "email") {
finalProvider.apiKey ??= env.get(`AUTH_${ID}_KEY`)
}
return finalProvider
})
}