-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathauth.js
458 lines (399 loc) · 12.6 KB
/
auth.js
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import fs from 'fs'
import path from 'path'
import execa from 'execa'
import Listr from 'listr'
import prompts from 'prompts'
import terminalLink from 'terminal-link'
import { getProject } from '@redwoodjs/structure'
import { errorTelemetry } from '@redwoodjs/telemetry'
import {
getPaths,
writeFilesTask,
transformTSToJS,
getGraphqlPath,
graphFunctionDoesExist,
} from '../../../lib'
import c from '../../../lib/colors'
const AUTH_PROVIDER_IMPORT = `import { AuthProvider } from '@redwoodjs/auth'`
const OUTPUT_PATHS = {
auth: path.join(
getPaths().api.lib,
getProject().isTypeScriptProject ? 'auth.ts' : 'auth.js'
),
function: path.join(
getPaths().api.functions,
getProject().isTypeScriptProject ? 'auth.ts' : 'auth.js'
),
}
const getWebAppPath = () => getPaths().web.app
const getSupportedProviders = () =>
fs
.readdirSync(path.resolve(__dirname, 'providers'))
.map((file) => path.basename(file, '.js'))
.filter((file) => file !== 'README.md')
const getTemplates = () =>
fs
.readdirSync(path.resolve(__dirname, 'templates'))
.reduce((templates, file) => {
if (file === 'auth.ts.template') {
return {
...templates,
base: [path.resolve(__dirname, 'templates', file)],
}
} else {
const provider = file.split('.')[0]
if (templates[provider]) {
templates[provider].push(path.resolve(__dirname, 'templates', file))
return { ...templates }
} else {
return {
...templates,
[provider]: [path.resolve(__dirname, 'templates', file)],
}
}
}
}, {})
// returns the content of App.{js,tsx} with import statements added
const addWebImports = (content, imports) => {
return `${AUTH_PROVIDER_IMPORT}\n` + imports.join('\n') + '\n' + content
}
// returns the content of App.{js,tsx} with init lines added (if there are any)
const addWebInit = (content, init) => {
if (init) {
const regex = /const App = \(.*\) => [({]/
const match = content.match(regex)
if (!match) {
return content
}
return content.replace(regex, `${init}\n\n${match[0]}`)
}
return content
}
const objectToComponentProps = (obj, options = { exclude: [] }) => {
let props = []
for (const [key, value] of Object.entries(obj)) {
if (!options.exclude.includes(key)) {
if (key === 'client') {
props.push(`${key}={${value}}`)
} else {
props.push(`${key}="${value}"`)
}
}
}
return props
}
// returns the content of App.{js,tsx} with <AuthProvider> added
const addWebRender = (content, authProvider) => {
const [
_,
newlineAndIndent,
redwoodProviderOpen,
redwoodProviderChildren,
redwoodProviderClose,
] = content.match(/(\s+)(<RedwoodProvider.*?>)(.*)(<\/RedwoodProvider>)/s)
const redwoodProviderChildrenLines = redwoodProviderChildren
.split('\n')
.map((line, index) => {
return `${index === 0 ? '' : ' '}` + line
})
// Wrap with custom components e.g.
// <RedwoodProvider titleTemplate="%PageTitle | %AppTitle">
// <FetchConfigProvider>
// <ApolloInjector>
// <AuthProvider client={ethereum} type="ethereum">
const customRenderOpen = (authProvider.render || []).reduce(
(acc, component) => acc + newlineAndIndent + ' ' + `<${component}>`,
''
)
const customRenderClose = (authProvider.render || []).reduce(
(acc, component) => newlineAndIndent + ' ' + `</${component}>` + acc,
''
)
const props = objectToComponentProps(authProvider, { exclude: ['render'] })
const renderContent =
newlineAndIndent +
redwoodProviderOpen +
customRenderOpen +
newlineAndIndent +
' ' +
`<AuthProvider ${props.join(' ')}>` +
redwoodProviderChildrenLines.join('\n') +
`</AuthProvider>` +
customRenderClose +
newlineAndIndent +
redwoodProviderClose
return content.replace(
/\s+<RedwoodProvider.*?>.*<\/RedwoodProvider>/s,
renderContent
)
}
// returns the content of App.{js,tsx} with <AuthProvider> updated
const updateWebRender = (content, authProvider) => {
const props = objectToComponentProps(authProvider)
const renderContent = `<AuthProvider ${props.join(' ')}>`
return content.replace(/<AuthProvider.*type=['"](.*)['"]>/s, renderContent)
}
// returns the content of App.{js,tsx} without the old auth import
const removeOldWebImports = (content, imports) => {
return content.replace(`${AUTH_PROVIDER_IMPORT}\n` + imports.join('\n'), '')
}
// returns the content of App.{js,tsx} without the old auth init
const removeOldWebInit = (content, init) => {
return content.replace(init, '')
}
// returns content with old auth provider removes
const removeOldAuthProvider = async (content) => {
// get the current auth provider
const [_, currentAuthProvider] = content.match(
/<AuthProvider.*type=['"](.*)['"]/s
)
let oldAuthProvider
try {
oldAuthProvider = await import(`./providers/${currentAuthProvider}`)
} catch (e) {
throw new Error('Could not replace existing auth provider init')
}
content = removeOldWebImports(content, oldAuthProvider.config.imports)
content = removeOldWebInit(content, oldAuthProvider.config.init)
return content
}
// check to make sure AuthProvider doesn't exist
const checkAuthProviderExists = async () => {
const content = fs.readFileSync(getWebAppPath()).toString()
if (content.includes(AUTH_PROVIDER_IMPORT)) {
throw new Error(
'Existing auth provider found.\nUse --force to override existing provider.'
)
}
}
// the files to create to support auth
export const files = ({ provider, webAuthn }) => {
const templates = getTemplates()
let files = {}
// look for any templates for this provider
for (const [templateProvider, templateFiles] of Object.entries(templates)) {
if (provider === templateProvider) {
templateFiles.forEach((templateFile) => {
const shouldUseTemplate =
(webAuthn && templateFile.match(/\.webAuthn\./)) ||
(!webAuthn && !templateFile.match(/\.webAuthn\./))
if (shouldUseTemplate) {
const outputPath =
OUTPUT_PATHS[path.basename(templateFile).split('.')[1]]
const content = fs.readFileSync(templateFile).toString()
files = Object.assign(files, {
[outputPath]: getProject().isTypeScriptProject
? content
: transformTSToJS(outputPath, content),
})
}
})
}
}
// if there are no provider-specific templates, just use the base auth one
if (Object.keys(files).length === 0) {
const content = fs.readFileSync(templates.base[0]).toString()
files = {
[OUTPUT_PATHS.auth]: getProject().isTypeScriptProject
? content
: transformTSToJS(templates.base[0], content),
}
}
return files
}
// actually inserts the required config lines into App.{js,tsx}
export const addConfigToApp = async (config, force, options = {}) => {
const { webAppPath: customWebAppPath } = options || {}
const webAppPath = customWebAppPath || getWebAppPath()
let content = fs.readFileSync(webAppPath).toString()
// update existing AuthProvider if --force else add new AuthProvider
if (content.includes(AUTH_PROVIDER_IMPORT) && force) {
content = await removeOldAuthProvider(content)
content = updateWebRender(content, config.authProvider)
} else {
content = addWebRender(content, config.authProvider)
}
content = addWebImports(content, config.imports)
content = addWebInit(content, config.init)
fs.writeFileSync(webAppPath, content)
}
export const addApiConfig = () => {
const graphqlPath = getGraphqlPath()
let content = fs.readFileSync(graphqlPath).toString()
// default to an array to avoid destructure errors
const [_, hasAuthImport] =
content.match(/(import {.*} from 'src\/lib\/auth.*')/s) || []
if (!hasAuthImport) {
// add import statement
content = content.replace(
/^(.*services.*)$/m,
`$1\n\nimport { getCurrentUser } from 'src/lib/auth'`
)
// add object to handler
content = content.replace(
/^(\s*)(loggerConfig:)(.*)$/m,
`$1getCurrentUser,\n$1$2$3`
)
fs.writeFileSync(graphqlPath, content)
}
}
export const isProviderSupported = (provider) => {
return getSupportedProviders().indexOf(provider) !== -1
}
export const apiSrcDoesExist = () => {
return fs.existsSync(path.join(getPaths().api.src))
}
export const webIndexDoesExist = () => {
return fs.existsSync(getWebAppPath())
}
export const command = 'auth <provider>'
export const description = 'Generate an auth configuration'
export const builder = (yargs) => {
yargs
.positional('provider', {
choices: getSupportedProviders(),
description: 'Auth provider to configure',
type: 'string',
})
.option('force', {
alias: 'f',
default: false,
description: 'Overwrite existing configuration',
type: 'boolean',
})
.epilogue(
`Also see the ${terminalLink(
'Redwood CLI Reference',
'https://redwoodjs.com/docs/cli-commands#setup-auth'
)}`
)
}
export const handler = async (yargs) => {
const { provider, rwVersion } = yargs
let force = yargs.force
let webAuthn = false
let providerData
// check if api/src/lib/auth.js already exists and if so, ask the user to overwrite
if (force === false) {
if (fs.existsSync(Object.keys(files(provider, yargs))[0])) {
const forceResponse = await prompts({
type: 'confirm',
name: 'answer',
message: `Overwrite existing ${getPaths().api.lib.replace(
getPaths().base,
''
)}/auth.[jt]s?`,
initial: false,
})
force = forceResponse.answer
}
}
// only dbAuth supports WebAuthn right now, but in theory it could work with
// any provider
if (provider === 'dbAuth') {
const webAuthnResponse = await prompts({
type: 'confirm',
name: 'answer',
message: `Enable WebAuthn support (TouchID/FaceID)? See https://redwoodjs.com/docs/auth/dbAuth#webAuthn`,
initial: false,
})
webAuthn = webAuthnResponse.answer
}
if (webAuthn) {
providerData = await import(`./providers/${provider}.webAuthn`)
} else {
providerData = await import(`./providers/${provider}`)
}
const tasks = new Listr(
[
{
title: 'Generating auth lib...',
task: (_ctx, task) => {
if (apiSrcDoesExist()) {
return writeFilesTask(files({ ...yargs, webAuthn }), {
overwriteExisting: force,
})
} else {
task.skip('api/src not found, skipping')
}
},
},
{
title: 'Adding auth config to web...',
task: (_ctx, task) => {
if (webIndexDoesExist()) {
addConfigToApp(providerData.config, force)
} else {
task.skip('web/src/App.{js,tsx} not found, skipping')
}
},
},
{
title: 'Adding auth config to GraphQL API...',
task: (_ctx, task) => {
if (graphFunctionDoesExist()) {
addApiConfig()
} else {
task.skip('GraphQL function not found, skipping')
}
},
},
{
title: 'Adding required web packages...',
task: async () => {
if (!isProviderSupported(provider)) {
throw new Error(`Unknown auth provider '${provider}'`)
}
await execa('yarn', [
'workspace',
'web',
'add',
...providerData.webPackages,
`@redwoodjs/auth@${rwVersion}`,
])
},
},
providerData.apiPackages.length > 0 && {
title: 'Adding required api packages...',
task: async () => {
if (!isProviderSupported(provider)) {
throw new Error(`Unknown auth provider '${provider}'`)
}
await execa('yarn', [
'workspace',
'api',
'add',
...providerData.apiPackages,
])
},
},
{
title: 'Installing packages...',
task: async () => {
await execa('yarn', ['install'])
},
},
providerData.task,
{
title: 'One more thing...',
task: (_ctx, task) => {
task.title = `One more thing...\n\n ${providerData.notes.join(
'\n '
)}\n`
},
},
].filter(Boolean),
{ collapse: false }
)
try {
// Don't throw existing provider error when --force exists
if (!force) {
await checkAuthProviderExists()
}
await tasks.run()
} catch (e) {
errorTelemetry(process.argv, e.message)
console.error(c.error(e.message))
process.exit(e?.exitCode || 1)
}
}