This repository has been archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathinstructions.ts
590 lines (513 loc) · 18.8 KB
/
instructions.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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import { join } from "path";
import ms from "ms";
import { generateKeyPair } from "crypto";
import * as sinkStatic from "@adonisjs/sink";
import { string } from "@poppinss/utils/build/helpers";
import { ApplicationContract } from "@ioc:Adonis/Core/Application";
import {
IndentationText,
NewLineKind,
Project,
PropertyAssignment,
SyntaxKind,
Writers,
} from "ts-morph";
import { parse as parseEditorConfig } from "editorconfig";
type InstructionsState = {
persistJwt: boolean;
jwtDefaultExpire: string;
refreshTokenDefaultExpire: string;
usersTableName?: string;
usersModelName?: string;
usersModelNamespace?: string;
tokensTableName: string;
tokensSchemaName: string;
provider: "lucid" | "database";
providerConfiguredName?: string;
providerConfiguredModel?: string;
tokensProvider: "database" | "redis";
};
type DefinedProviders = {
[name: string]: {
type: "lucid" | "database";
model?: string;
};
};
/**
* Prompt choices for the tokens provider selection
*/
const TOKENS_PROVIDER_PROMPT_CHOICES = [
{
name: "database" as const,
message: "Database",
hint: " (Uses SQL table for storing JWT tokens)",
},
{
name: "redis" as const,
message: "Redis",
hint: " (Uses Redis for storing JWT tokens)",
},
];
/**
* Returns absolute path to the stub relative from the templates
* directory. This path is correct when files are in /build folder
*/
function getStub(...relativePaths: string[]) {
return join(__dirname, "templates", ...relativePaths);
}
/**
*
* @returns
*/
async function getIntendationConfigForTsMorph(projectRoot: string) {
const indentConfig = await parseEditorConfig(projectRoot + "/.editorconfig");
let indentationText:IndentationText;
if (indentConfig.indent_style === "space" && indentConfig.indent_size === 2) {
indentationText = IndentationText.TwoSpaces;
} else if (indentConfig.indent_style === "space" && indentConfig.indent_size === 4) {
indentationText = IndentationText.FourSpaces;
} else if (indentConfig.indent_style === "tab") {
indentationText = IndentationText.Tab;
} else {
indentationText = IndentationText.FourSpaces;
}
let newLineKind:NewLineKind;
if (indentConfig.end_of_line === "lf") {
newLineKind = NewLineKind.LineFeed;
} else if (indentConfig.end_of_line === "crlf") {
newLineKind = NewLineKind.CarriageReturnLineFeed;
} else {
newLineKind = NewLineKind.LineFeed;
}
return { indentationText, newLineKind };
}
async function getTsMorphProject(projectRoot: string) {
const { indentationText, newLineKind } = await getIntendationConfigForTsMorph(projectRoot);
return new Project({
tsConfigFilePath: projectRoot + "/tsconfig.json",
manipulationSettings: {
indentationText: indentationText,
newLineKind: newLineKind,
useTrailingCommas: true,
},
});
}
/**
* Create the migration file
*/
function makeTokensMigration(
projectRoot: string,
app: ApplicationContract,
sink: typeof sinkStatic,
state: InstructionsState
) {
const migrationsDirectory = app.directoriesMap.get("migrations") || "database";
const migrationPath = join(migrationsDirectory, `${Date.now()}_${state.tokensTableName}.ts`);
let templateFile = "migrations/jwt_tokens.txt";
if (!state.persistJwt) {
templateFile = "migrations/jwt_refresh_tokens.txt";
}
const template = new sink.files.MustacheFile(projectRoot, migrationPath, getStub(templateFile));
if (template.exists()) {
sink.logger.action("create").skipped(`${migrationPath} file already exists`);
return;
}
template.apply(state).commit();
sink.logger.action("create").succeeded(migrationPath);
}
/**
*
* @param projectRoot
* @param app
* @returns
*/
async function getDefinedProviders(projectRoot: string, app: ApplicationContract) {
const contractsDirectory = app.directoriesMap.get("contracts") || "contracts";
const contractPath = join(contractsDirectory, "auth.ts");
//Instantiate ts-morph
const project = await getTsMorphProject(projectRoot);
const authContractFile = project.getSourceFileOrThrow(contractPath);
//Doesn't work without single quotes wrapping the module name
const authModule = authContractFile?.getModuleOrThrow("'@ioc:Adonis/Addons/Auth'");
const definedProviders: DefinedProviders = {};
const providersInterface = authModule.getInterfaceOrThrow("ProvidersList");
const userProviders = providersInterface.getProperties();
for (const provider of userProviders) {
let providerType: "lucid" | "database" | undefined;
let providerLucidModel = "";
const providerTypeJs = provider.getTypeNodeOrThrow().getFullText();
if (providerTypeJs?.indexOf("LucidProviderContract") !== -1) {
providerType = "lucid";
const matches = /typeof ([^>]+)/g.exec(providerTypeJs);
if (matches && matches.length) {
providerLucidModel = matches[1];
} else {
sinkStatic.logger.warning(`Unable to find model name for provider ${provider}. Skipping it`);
continue;
}
} else if (providerTypeJs?.indexOf("DatabaseProviderContract") !== -1) {
providerType = "database";
} else {
continue;
}
definedProviders[provider.getName()] = {
type: providerType,
};
if (providerLucidModel) {
definedProviders[provider.getName()].model = providerLucidModel;
}
}
if (!Object.keys(definedProviders).length) {
throw new Error(
"No provider implementation found in ProvidersList. Maybe you didn't configure @adonisjs/auth first?"
);
}
return definedProviders;
}
/**
* Creates the contract file
*/
async function editContract(
projectRoot: string,
app: ApplicationContract,
sink: typeof sinkStatic,
state: InstructionsState
) {
const contractsDirectory = app.directoriesMap.get("contracts") || "contracts";
const contractPath = join(contractsDirectory, "auth.ts");
//Instantiate ts-morph
const project = await getTsMorphProject(projectRoot);
const authContractFile = project.getSourceFileOrThrow(contractPath);
//Remove JWT import, if already present
authContractFile.getImportDeclaration("@ioc:Adonis/Addons/Jwt")?.remove();
//Add JWT import
authContractFile.addImportDeclaration({
namedImports: ["JWTGuardConfig", "JWTGuardContract"],
moduleSpecifier: "@ioc:Adonis/Addons/Jwt",
});
//Doesn't work without single quotes wrapping the module name
const authModule = authContractFile?.getModuleOrThrow("'@ioc:Adonis/Addons/Auth'");
let providerName = "";
const providersInterface = authModule.getInterfaceOrThrow("ProvidersList");
if (state.providerConfiguredName && providersInterface.getProperty(state.providerConfiguredName)) {
providerName = state.providerConfiguredName;
} else {
providerName = `user_using_${state.provider}`;
let implementation = "";
let config = "";
if (state.provider === "lucid") {
implementation = `LucidProviderContract<typeof ${state.usersModelName}>`;
config = `LucidProviderConfig<typeof ${state.usersModelName}>`;
} else {
implementation = `DatabaseProviderContract<DatabaseProviderRow>`;
config = `DatabaseProviderConfig`;
}
//Insert provider in last position
providersInterface.addProperty({
name: providerName,
type: `{
implementation: ${implementation},
config: ${config},
}`,
});
}
const guardsInterface = authModule.getInterfaceOrThrow("GuardsList");
//Remove JWT guard, if already present
guardsInterface.getProperty("jwt")?.remove();
//Insert JWT guard in second position (first parameter)
guardsInterface.addProperty({
name: "jwt",
type: `{
implementation: JWTGuardContract<'${providerName}', 'api'>,
config: JWTGuardConfig<'${providerName}'>,
}`,
});
authContractFile.formatText();
await authContractFile?.save();
sink.logger.action("update").succeeded(contractPath);
}
/**
* Makes the auth config file
*/
async function editConfig(
projectRoot: string,
app: ApplicationContract,
sink: typeof sinkStatic,
state: InstructionsState
) {
const configDirectory = app.directoriesMap.get("config") || "config";
const configPath = join(configDirectory, "auth.ts");
let tokenProvider;
if (state.tokensProvider === "redis") {
tokenProvider = Writers.object({
type: "'jwt'",
driver: "'redis'",
redisConnection: "'local'",
foreignKey: "'user_id'",
});
} else {
tokenProvider = Writers.object({
type: "'api'",
driver: "'database'",
table: "'jwt_tokens'",
foreignKey: "'user_id'",
});
}
let provider;
if (state.provider === "database") {
provider = Writers.object({
driver: "'database'",
identifierKey: "'id'",
uids: "['email']",
usersTable: `'${state.usersTableName}'`,
});
} else if (state.provider === "lucid") {
provider = Writers.object({
driver: '"lucid"',
identifierKey: '"id"',
uids: "[]",
model: `() => import('${state.usersModelNamespace}')`,
});
} else {
throw new Error(`Invalid state.provider: ${state.provider}`);
}
//Instantiate ts-morph
const project = await getTsMorphProject(projectRoot);
const authConfigFile = project.getSourceFileOrThrow(configPath);
//Remove Env import, if already present
authConfigFile.getImportDeclaration("@ioc:Adonis/Core/Env")?.remove();
//Add Env import
authConfigFile.addImportDeclaration({
defaultImport: "Env",
moduleSpecifier: "@ioc:Adonis/Core/Env",
});
const variable = authConfigFile
?.getVariableDeclarationOrThrow("authConfig")
.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
let guardsProperty = variable?.getPropertyOrThrow("guards") as PropertyAssignment;
let guardsObject = guardsProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
//Remove JWT config, if already present
guardsObject.getProperty("jwt")?.remove();
//Add JWT config
guardsObject?.addPropertyAssignment({
name: "jwt",
initializer: Writers.object({
driver: '"jwt"',
publicKey: `Env.get('JWT_PUBLIC_KEY', '').replace(/\\\\n/g, '\\n')`,
privateKey: `Env.get('JWT_PRIVATE_KEY', '').replace(/\\\\n/g, '\\n')`,
persistJwt: `${state.persistJwt ? "true" : "false"}`,
jwtDefaultExpire: `'${state.jwtDefaultExpire}'`,
refreshTokenDefaultExpire: `'${state.refreshTokenDefaultExpire}'`,
tokenProvider: tokenProvider,
provider: provider,
}),
});
authConfigFile.formatText();
await authConfigFile?.save();
sink.logger.action("update").succeeded(configPath);
}
async function makeKeys(
projectRoot: string,
_app: ApplicationContract,
sink: typeof sinkStatic,
_state: InstructionsState
) {
await new Promise((resolve, reject) => {
generateKeyPair(
"rsa",
{
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
},
(err, publicKey, privateKey) => {
if (err) {
return reject(err);
}
resolve({ publicKey, privateKey });
}
);
}).then(({ privateKey, publicKey }) => {
const env = new sink.files.EnvFile(projectRoot);
env.set("JWT_PRIVATE_KEY", privateKey.replace(/\n/g, "\\n"));
env.set("JWT_PUBLIC_KEY", publicKey.replace(/\n/g, "\\n"));
env.commit();
sink.logger.action("update").succeeded(".env,.env.example");
});
}
/**
* Prompts user to select the provider
*/
async function getProvider(
sink: typeof sinkStatic,
definedProviders: DefinedProviders
): Promise<"lucid" | "database" | string> {
let choices = {
lucid: {
name: "lucid",
message: "Lucid",
hint: " (Uses Data Models)",
},
database: {
name: "database",
message: "Database",
hint: " (Uses Database QueryBuilder, will be created in this configuration)",
},
};
for (const providerName in definedProviders) {
const { type: definedProviderType } = definedProviders[providerName];
if (choices[definedProviderType]) {
choices[definedProviderType].name = providerName;
choices[definedProviderType].message = `Already configured ${string.capitalCase(
definedProviderType
)} provider (${providerName})`;
}
}
const chosenProvider = await sink.getPrompt().choice("Select provider for finding users", Object.values(choices), {
validate(choice) {
return choice && choice.length ? true : "Select the provider for finding users";
},
});
return chosenProvider;
}
/**
* Prompts user to select the tokens provider
*/
async function getTokensProvider(sink: typeof sinkStatic) {
return sink.getPrompt().choice("Select the provider for storing JWT tokens", TOKENS_PROVIDER_PROMPT_CHOICES, {
validate(choice) {
return choice && choice.length ? true : "Select the provider for storing JWT tokens";
},
});
}
/**
* Prompts user for the model name
*/
async function getModelName(sink: typeof sinkStatic): Promise<string> {
return sink.getPrompt().ask("Enter model name to be used for authentication", {
validate(value) {
return !!value.trim().length;
},
});
}
/**
* Prompts user for the table name
*/
async function getTableName(sink: typeof sinkStatic): Promise<string> {
return sink.getPrompt().ask("Enter the database table name to look up users", {
validate(value) {
return !!value.trim().length;
},
});
}
/**
* Prompts user for the table name
*/
async function getMigrationConsent(sink: typeof sinkStatic, tableName: string): Promise<boolean> {
return sink.getPrompt().confirm(`Create migration for the ${sink.logger.colors.underline(tableName)} table?`);
}
function getModelNamespace(app: ApplicationContract, usersModelName) {
return `${app.namespacesMap.get("models") || "App/Models"}/${string.capitalCase(usersModelName)}`;
}
async function getPersistJwt(sink: typeof sinkStatic): Promise<boolean> {
return sink.getPrompt().confirm(`Do you want to persist JWT in database/redis (please read README.md beforehand)?`);
}
async function getJwtDefaultExpire(sink: typeof sinkStatic, state: InstructionsState): Promise<string> {
return sink.getPrompt().ask("Enter the default expire time for the JWT (10h = 10 hours, 5d = 5 days, etc)", {
default: state.jwtDefaultExpire,
validate(value) {
if (!value.match(/^[0-9]+[a-z]+$/)) {
return false;
}
return !!ms(value);
},
});
}
async function getRefreshTokenDefaultExpire(sink: typeof sinkStatic, state: InstructionsState): Promise<string> {
return sink
.getPrompt()
.ask("Enter the default expire time for the refresh token (10h = 10 hours, 5d = 5 days, etc)", {
default: state.refreshTokenDefaultExpire,
validate(value) {
if (!value.match(/^[0-9]+[a-z]+$/)) {
return false;
}
return !!ms(value);
},
});
}
/**
* Instructions to be executed when setting up the package.
*/
export default async function instructions(projectRoot: string, app: ApplicationContract, sink: typeof sinkStatic) {
const state: InstructionsState = {
persistJwt: false,
jwtDefaultExpire: "10m",
refreshTokenDefaultExpire: "10d",
tokensTableName: "jwt_tokens",
tokensSchemaName: "JwtTokens",
provider: "lucid",
tokensProvider: "database",
};
const definedProviders = await getDefinedProviders(projectRoot, app);
const chosenProvider = await getProvider(sink, definedProviders);
if (definedProviders[chosenProvider]) {
state.providerConfiguredName = chosenProvider;
state.provider = definedProviders[chosenProvider].type;
if (definedProviders[chosenProvider].model) {
state.usersModelName = definedProviders[chosenProvider].model;
state.usersModelNamespace = getModelNamespace(app, definedProviders[chosenProvider].model);
}
/**
* Prompt for the database table name. If it's using a Lucid provider, we already have
* the name of the model in the ProvidersList
*/
if (state.provider === "database") {
state.usersTableName = await getTableName(sink);
}
} else {
//Force type
state.provider = chosenProvider as "lucid" | "database";
/**
* Get model name when provider is lucid otherwise prompt for the database
* table name
*/
if (state.provider === "lucid") {
const usersModelName = await getModelName(sink);
state.usersModelName = usersModelName.replace(/(\.ts|\.js)$/, "");
state.usersTableName = string.pluralize(string.snakeCase(usersModelName));
state.usersModelNamespace = getModelNamespace(app, usersModelName);
} else if (state.provider === "database") {
state.usersTableName = await getTableName(sink);
}
}
state.persistJwt = await getPersistJwt(sink);
let tokensMigrationConsent = false;
state.tokensProvider = await getTokensProvider(sink);
if (state.tokensProvider === "database") {
tokensMigrationConsent = await getMigrationConsent(sink, state.tokensTableName);
}
state.jwtDefaultExpire = await getJwtDefaultExpire(sink, state);
state.refreshTokenDefaultExpire = await getRefreshTokenDefaultExpire(sink, state);
await makeKeys(projectRoot, app, sink, state);
/**
* Make tokens migration file
*/
if (tokensMigrationConsent) {
makeTokensMigration(projectRoot, app, sink, state);
}
/**
* Make contract file
*/
await editContract(projectRoot, app, sink, state);
/**
* Make config file
*/
await editConfig(projectRoot, app, sink, state);
}