forked from PalisadoesFoundation/talawa-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.ts
1142 lines (1023 loc) · 34.3 KB
/
setup.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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { MAXIMUM_IMAGE_SIZE_LIMIT_KB } from "./src/constants";
import dotenv from "dotenv";
import fs from "fs";
import path from "path";
import * as cryptolib from "crypto";
import inquirer from "inquirer";
import mongodb from "mongodb";
import * as redis from "redis";
import { exec } from "child_process";
import nodemailer from "nodemailer";
import type { ExecException } from "child_process";
dotenv.config();
// Check if all the fields in .env.sample are present in .env
/**
* The function `checkEnvFile` checks if any fields are missing in the .env file compared to the .env.sample file, and
* if so, it copies the missing fields from .env.sampale to .env.
*/
function checkEnvFile(): void {
const env = dotenv.parse(fs.readFileSync(".env"));
const envSample = dotenv.parse(fs.readFileSync(".env.sample"));
const misplaced = Object.keys(envSample).filter((key) => !(key in env));
if (misplaced.length > 0) {
// copy the missing fields from .env.sample to .env
for (const key of misplaced) {
fs.appendFileSync(".env", `${key}=${envSample[key]}\n`);
}
}
}
// Update the value of an environment variable in .env file
/**
* The function `updateEnvVariable` updates the values of environment variables in a .env file based on the provided
* configuration object.
* @param config - An object that contains key-value pairs where the keys are strings and the values
* can be either strings or numbers. These key-value pairs represent the environment variables that
* need to be updated.
*/
function updateEnvVariable(config: { [key: string]: string | number }): void {
const existingContent: string = fs.readFileSync(".env", "utf8");
let updatedContent: string = existingContent;
for (const key in config) {
const regex = new RegExp(`^${key}=.*`, "gm");
updatedContent = updatedContent.replace(regex, `${key}=${config[key]}`);
}
fs.writeFileSync(".env", updatedContent, "utf8");
}
// Get the node environment
/**
* The function `getNodeEnvironment` is an asynchronous function that prompts the user to select a Node
* environment (either "development" or "production") and returns the selected environment as a string.
* @returns a Promise that resolves to a string representing the selected Node environment.
*/
async function getNodeEnvironment(): Promise<string> {
const { nodeEnv } = await inquirer.prompt([
{
type: "list",
name: "nodeEnv",
message: "Select Node environment:",
choices: ["development", "production"],
default: "development",
},
]);
return nodeEnv;
}
/**
* The function `setNodeEnvironment` sets the Node environment by reading the value from a file, updating the process
* environment variable, and updating a configuration file.
*/
async function setNodeEnvironment(): Promise<void> {
try {
const nodeEnv = await getNodeEnvironment();
process.env.NODE_ENV = nodeEnv;
const config = dotenv.parse(fs.readFileSync(".env"));
config.NODE_ENV = nodeEnv;
updateEnvVariable(config);
} catch (err) {
console.error(err);
abort();
}
}
// Generate and update the access and refresh token secrets in .env
/**
* The function `accessAndRefreshTokens` generates and updates access and refresh tokens if they are
* null.
* @param accessTokenSecret - A string representing the access token secret. It is
* initially set to `null` and will be generated if it is `null`.
* @param refreshTokenSecret - The `refreshTokenSecret` parameter is a string that
* represents the secret key used to generate and verify refresh tokens. Refresh tokens are typically
* used in authentication systems to obtain new access tokens without requiring the user to
* re-authenticate.
*/
async function accessAndRefreshTokens(
accessTokenSecret: string | null,
refreshTokenSecret: string | null,
): Promise<void> {
const config = dotenv.parse(fs.readFileSync(".env"));
if (accessTokenSecret === null) {
accessTokenSecret = cryptolib.randomBytes(32).toString("hex");
config.ACCESS_TOKEN_SECRET = accessTokenSecret;
updateEnvVariable(config);
}
if (refreshTokenSecret === null) {
refreshTokenSecret = cryptolib.randomBytes(32).toString("hex");
config.REFRESH_TOKEN_SECRET = refreshTokenSecret;
updateEnvVariable(config);
}
}
//set the image size upload environment variable
/**
* The function `setImageUploadSize` sets the image upload size environment variable and changes the .env file
* @returns The function `checkExistingRedis` returns a void Promise.
*/
async function setImageUploadSize(size: number): Promise<void> {
if (size > MAXIMUM_IMAGE_SIZE_LIMIT_KB) {
size = MAXIMUM_IMAGE_SIZE_LIMIT_KB;
}
const config = dotenv.parse(fs.readFileSync(".env"));
config.IMAGE_SIZE_LIMIT_KB = size.toString();
fs.writeFileSync(".env", "");
for (const key in config) {
fs.appendFileSync(".env", `${key}=${config[key]}\n`);
}
}
function transactionLogPath(logPath: string | null): void {
const config = dotenv.parse(fs.readFileSync(".env"));
config.LOG = "true";
if (!logPath) {
// Check if the logs/transaction.log file exists, if not, create it
const defaultLogPath = path.resolve(__dirname, "logs");
const defaultLogFile = path.join(defaultLogPath, "transaction.log");
if (!fs.existsSync(defaultLogPath)) {
console.log("Creating logs/transaction.log file...");
fs.mkdirSync(defaultLogPath);
}
config.LOG_PATH = defaultLogFile;
} else {
// Remove the logs files, if exists
const logsDirPath = path.resolve(__dirname, "logs");
if (fs.existsSync(logsDirPath)) {
fs.readdirSync(logsDirPath).forEach((file: string) => {
if (file !== "README.md") {
const curPath = path.join(logsDirPath, file);
fs.unlinkSync(curPath);
}
});
}
config.LOG_PATH = logPath;
}
}
async function askForTransactionLogPath(): Promise<string> {
let logPath: string | null;
// Keep asking for path, until user gives a valid path
// eslint-disable-next-line no-constant-condition
while (true) {
const response = await inquirer.prompt([
{
type: "input",
name: "logPath",
message: "Enter absolute path of log file:",
default: null,
},
]);
logPath = response.logPath;
if (logPath && fs.existsSync(logPath)) {
try {
fs.accessSync(logPath, fs.constants.R_OK | fs.constants.W_OK);
break;
} catch {
console.error(
"The file is not readable/writable. Please enter a valid file path.",
);
}
} else {
console.error(
"Invalid path or file does not exist. Please enter a valid file path.",
);
}
}
return logPath;
}
// Check connection to Redis with the specified URL.
/**
* The function `checkRedisConnection` checks if a connection to Redis can be established using the
* provided URL.
* @param url - The `url` parameter is a string that represents the URL of the Redis server.
* It is used to establish a connection to the Redis server.
* @returns a Promise that resolves to a boolean value.
*/
async function checkRedisConnection(url: string): Promise<boolean> {
let response = false;
const client = redis.createClient({ url });
console.log("\nChecking Redis connection....");
try {
await client.connect();
response = true;
} catch (error) {
console.log(`\nConnection to Redis failed. Please try again.\n`);
} finally {
client.quit();
}
return response;
}
// Redis url prompt
/**
* The function `askForRedisUrl` prompts the user to enter the Redis hostname, port, and password, and
* returns an object with these values.
* @returns The function `askForRedisUrl` returns a promise that resolves to an object with the
* properties `host`, `port`, and `password`.
*/
async function askForRedisUrl(): Promise<{
host: string;
port: number;
password: string;
}> {
const { host, port, password } = await inquirer.prompt([
{
type: "input",
name: "host",
message: "Enter Redis hostname (default: localhost):",
default: "localhost",
},
{
type: "input",
name: "port",
message: "Enter Redis port (default: 6379):",
default: 6379,
},
{
type: "password",
name: "password",
message:
"Enter Redis password (optional : Leave empty for local connections) :",
},
]);
return { host, port, password };
}
//check existing redis url
/**
* The function `checkExistingRedis` checks if there is an existing Redis connection by iterating
* through a list of Redis URLs and testing the connection.
* @returns The function `checkExistingRedis` returns a Promise that resolves to a string or null.
*/
async function checkExistingRedis(): Promise<string | null> {
const existingRedisURL = ["redis://localhost:6379"];
for (const url of existingRedisURL) {
if (!url) {
continue;
}
const isConnected = await checkRedisConnection(url);
if (isConnected) {
return url;
}
}
return null;
}
// get the redis url
/**
* The `redisConfiguration` function updates the Redis configuration by prompting the user for the
* Redis URL, checking the connection, and updating the environment variables and .env file
* accordingly.
*/
async function redisConfiguration(): Promise<void> {
try {
let host!: string;
let port!: number;
let password!: string;
let url = await checkExistingRedis();
let isConnected = url !== null;
if (isConnected) {
console.log("Redis URL detected: " + url);
const { keepValues } = await inquirer.prompt({
type: "confirm",
name: "keepValues",
message: `Do you want to connect to the detected Redis URL?`,
default: true,
});
if (keepValues) {
console.log("Keeping existing Redis URL: " + url);
host = "localhost";
port = 6379;
password = "";
} else {
isConnected = false;
}
}
url = "";
while (!isConnected) {
const result = await askForRedisUrl();
host = result.host;
port = result.port;
password = result.password;
url = `redis://${password ? password + "@" : ""}${host}:${port}`;
isConnected = await checkRedisConnection(url);
}
if (isConnected) {
console.log("\nConnection to Redis successful! 🎉");
}
// Set the Redis parameters in process.env
process.env.REDIS_HOST = host;
process.env.REDIS_PORT = port.toString();
process.env.REDIS_PASSWORD = password;
// Update the .env file
const config = dotenv.parse(fs.readFileSync(".env"));
config.REDIS_HOST = host;
config.REDIS_PORT = port.toString();
config.REDIS_PASSWORD = password;
updateEnvVariable(config);
} catch (err) {
console.error(err);
abort();
}
}
//LAST_RESORT_SUPERADMIN_EMAIL prompt
/**
* The function `askForSuperAdminEmail` asks the user to enter an email address and returns it as a promise.
* @returns The email entered by the user is being returned.
*/
async function askForSuperAdminEmail(): Promise<string> {
console.log(
"\nPlease make sure to register with this email before logging in.\n",
);
const { email } = await inquirer.prompt([
{
type: "input",
name: "email",
message:
"Enter the email which you wish to assign as the Super Admin of last resort :",
validate: (input: string) =>
isValidEmail(input) || "Invalid email. Please try again.",
},
]);
return email;
}
// Get the super admin email
/**
* The function `superAdmin` prompts the user for a super admin email, updates a configuration file
* with the email, and handles any errors that occur.
*/
async function superAdmin(): Promise<void> {
try {
const email = await askForSuperAdminEmail();
const config = dotenv.parse(fs.readFileSync(".env"));
config.LAST_RESORT_SUPERADMIN_EMAIL = email;
updateEnvVariable(config);
} catch (err) {
console.log(err);
abort();
}
}
// Function to check if Existing MongoDB instance is running
/**
* The function `checkExistingMongoDB` checks for an existing MongoDB connection by iterating through a
* list of URLs and testing the connection using the `checkConnection` function.
* @returns The function `checkExistingMongoDB` returns a promise that resolves to a string or null.
*/
async function checkExistingMongoDB(): Promise<string | null> {
const existingMongoDbUrls = [
process.env.MONGO_DB_URL,
"mongodb://localhost:27017",
];
for (const url of existingMongoDbUrls) {
if (!url) {
continue;
}
const isConnected = await checkConnection(url);
if (isConnected) {
return url;
}
}
return null;
}
// Check the connection to MongoDB with the specified URL.
/**
* The function `checkConnection` is an asynchronous function that checks the connection to a MongoDB
* database using the provided URL and returns a boolean value indicating whether the connection was
* successful or not.
* @param url - The `url` parameter is a string that represents the connection URL for the
* MongoDB server. It typically includes the protocol (e.g., `mongodb://`), the host and port
* information, and any authentication credentials if required.
* @returns a Promise that resolves to a boolean value. The boolean value indicates whether the
* connection to the MongoDB server was successful (true) or not (false).
*/
async function checkConnection(url: string): Promise<boolean> {
console.log("\nChecking MongoDB connection....");
try {
const connection = await mongodb.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 1000,
});
await connection.close();
return true;
} catch (error) {
console.log(`\nConnection to MongoDB failed. Please try again.\n`);
return false;
}
}
//Mongodb url prompt
/**
* The function `askForMongoDBUrl` prompts the user to enter a MongoDB URL and returns the entered URL
* as a string.
* @returns a Promise that resolves to a string.
*/
async function askForMongoDBUrl(): Promise<string> {
const { url } = await inquirer.prompt([
{
type: "input",
name: "url",
message: "Enter your MongoDB URL:",
default: process.env.MONGO_DB_URL,
},
]);
return url;
}
// Get the mongodb url
/**
* The `mongoDB` function connects to a MongoDB database by asking for a URL, checking the connection,
* and updating the environment variable with the URL.
*/
async function mongoDB(): Promise<void> {
let DB_URL = process.env.MONGO_DB_URL;
try {
let url = await checkExistingMongoDB();
let isConnected = url !== null;
if (isConnected) {
console.log("MongoDB URL detected: " + url);
const { keepValues } = await inquirer.prompt({
type: "confirm",
name: "keepValues",
message: `Do you want to connect to the detected MongoDB URL?`,
default: true,
});
if (keepValues) {
console.log("Keeping existing MongoDB URL: " + url);
} else {
isConnected = false;
}
}
while (!isConnected) {
url = await askForMongoDBUrl();
isConnected = await checkConnection(url);
}
if (isConnected) {
console.log("\nConnection to MongoDB successful! 🎉");
}
DB_URL = `${url?.endsWith("/talawa-api") ? url : `${url}/talawa-api`}`;
const config = dotenv.parse(fs.readFileSync(".env"));
config.MONGO_DB_URL = DB_URL;
// Modifying the environment variable to be able to access the URL in importData function.
process.env.MONGO_DB_URL = DB_URL;
updateEnvVariable(config);
} catch (err) {
console.error(err);
abort();
}
}
// Function to ask if the user wants to keep the entered values
/**
* The function `askToKeepValues` prompts the user with a confirmation message and returns a boolean
* indicating whether the user wants to keep the entered key.
* @returns a boolean value, either true or false.
*/
async function askToKeepValues(): Promise<boolean> {
const { keepValues } = await inquirer.prompt({
type: "confirm",
name: "keepValues",
message: `Would you like to keep the entered key? `,
default: true,
});
return keepValues;
}
//Get recaptcha details
/**
* The function `recaptcha` prompts the user to enter a reCAPTCHA secret key, validates the input, and
* allows the user to choose whether to keep the entered value or try again.
*/
async function recaptcha(): Promise<void> {
const { recaptchaSecretKey } = await inquirer.prompt([
{
type: "input",
name: "recaptchaSecretKey",
message: "Enter your reCAPTCHA secret key:",
validate: async (input: string): Promise<boolean | string> => {
if (validateRecaptcha(input)) {
return true;
}
return "Invalid reCAPTCHA secret key. Please try again.";
},
},
]);
const shouldKeepDetails = await askToKeepValues();
if (shouldKeepDetails) {
const config = dotenv.parse(fs.readFileSync(".env"));
config.RECAPTCHA_SECRET_KEY = recaptchaSecretKey;
updateEnvVariable(config);
} else {
await recaptcha();
}
}
/**
* The function `recaptchaSiteKey` prompts the user to enter a reCAPTCHA site key, validates the input,
* and updates the environment variable if the user chooses to keep the entered value.
*/
async function recaptchaSiteKey(): Promise<void> {
if (process.env.RECAPTCHA_SITE_KEY) {
console.log(
`\nreCAPTCHA site key already exists with the value ${process.env.RECAPTCHA_SITE_KEY}`,
);
}
const { recaptchaSiteKeyInp } = await inquirer.prompt([
{
type: "input",
name: "recaptchaSiteKeyInp",
message: "Enter your reCAPTCHA site key:",
validate: async (input: string): Promise<boolean | string> => {
if (validateRecaptcha(input)) {
return true;
}
return "Invalid reCAPTCHA site key. Please try again.";
},
},
]);
const shouldKeepDetails = await askToKeepValues();
if (shouldKeepDetails) {
const config = dotenv.parse(fs.readFileSync(".env"));
config.RECAPTCHA_SITE_KEY = recaptchaSiteKeyInp;
updateEnvVariable(config);
} else {
await recaptchaSiteKey();
}
}
/**
* The function `isValidEmail` checks if a given email address is valid according to a specific pattern.
* @param email - The `email` parameter is a string that represents an email address.
* @returns a boolean value. It returns true if the email passed as an argument matches the specified
* pattern, and false otherwise.
*/
function isValidEmail(email: string): boolean {
const pattern = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
const match = email.match(pattern);
return match !== null && match[0] === email;
}
/**
* The function validates whether a given string matches the pattern of a reCAPTCHA token.
* @param string - The `string` parameter represents the input string that needs to be
* validated. In this case, it is expected to be a string containing a Recaptcha response token.
* @returns a boolean value.
*/
function validateRecaptcha(string: string): boolean {
const pattern = /^[a-zA-Z0-9_-]{40}$/;
return pattern.test(string);
}
/**
* The function validates whether a given image size is less than 20 and greater than 0.
* @param string - The `number` parameter represents the input size of the string
* validated. In this case, it is expected to be a number less than 20 and greater than 0.
* @returns a boolean value.
*/
function validateImageFileSize(size: number): boolean {
return size > 0;
}
/**
* The `abort` function logs a message and exits the process.
*/
function abort(): void {
console.log("\nSetup process aborted. 🫠");
process.exit(1);
}
//Get mail username and password
/**
* The function `twoFactorAuth` prompts the user to set up Two-Factor Authentication Google Account and
* then collects their email and generated password to update environment variables.
*/
async function twoFactorAuth(): Promise<void> {
console.log("\nIMPORTANT");
console.log(
"\nEnsure that you have Two-Factor Authentication set up on your Google Account.",
);
console.log("\nVisit Url: https://myaccount.google.com");
console.log(
"\nSelect Security and under Signing in to Google section select App Passwords.",
);
console.log(
"\nClick on Select app section and choose Other(Custom name), enter talawa as the custom name and press Generate button.",
);
const { email, password } = await inquirer.prompt([
{
type: "input",
name: "email",
message: "Enter your email:",
validate: (input: string) =>
isValidEmail(input) || "Invalid email. Please try again.",
},
{
type: "password",
name: "password",
message: "Enter the generated password:",
},
]);
const config = dotenv.parse(fs.readFileSync(".env"));
config.MAIL_USERNAME = email;
config.MAIL_PASSWORD = password;
updateEnvVariable(config);
}
//Checks if the data exists and ask for deletion
/**
* The function `shouldWipeExistingData` checks if there is existing data in a MongoDB database and prompts the user to delete
* it before importing new data.
* @param url - The `url` parameter is a string that represents the connection URL for the
* MongoDB database. It is used to establish a connection to the database using the `MongoClient` class
* from the `mongodb` package.
* @returns The function returns a Promise<boolean>.
*/
async function shouldWipeExistingData(url: string): Promise<boolean> {
let shouldImport = false;
const client = new mongodb.MongoClient(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
try {
await client.connect();
const db = client.db();
const collections = await db.listCollections().toArray();
if (collections.length > 0) {
const { confirmDelete } = await inquirer.prompt({
type: "confirm",
name: "confirmDelete",
message:
"We found data in the database. Do you want to delete the existing data before importing?",
});
if (confirmDelete) {
for (const collection of collections) {
await db.collection(collection.name).deleteMany({});
}
console.log("All existing data has been deleted.");
shouldImport = true;
} else {
console.log("Deletion & import operation cancelled.");
}
} else {
shouldImport = true;
}
} catch (error) {
console.error("Could not connect to database to check for data");
}
client.close();
return shouldImport;
}
//Import sample data
/**
* The function `importData` imports sample data into a MongoDB database if the database URL is provided and if it
* is determined that existing data should be wiped.
* @returns The function returns a Promise that resolves to `void`.
*/
async function importData(): Promise<void> {
if (!process.env.MONGO_DB_URL) {
console.log("Couldn't find mongodb url");
return;
}
const shouldImport = await shouldWipeExistingData(process.env.MONGO_DB_URL);
if (shouldImport) {
console.log("Importing sample data...");
await exec(
"npm run import:sample-data",
(error: ExecException | null, stdout: string, stderr: string) => {
if (error) {
console.error(`Error: ${error.message}`);
abort();
}
if (stderr) {
console.error(`Error: ${stderr}`);
abort();
}
console.log(`Output: ${stdout}`);
},
);
}
}
type VerifySmtpConnectionReturnType = {
success: boolean;
error: unknown;
};
/**
* The function `verifySmtpConnection` verifies the SMTP connection using the provided configuration
* and returns a success status and error message if applicable.
* @param config - The `config` parameter is an object that contains the configuration settings for the
* SMTP connection. It should have the following properties:
* @returns The function `verifySmtpConnection` returns a Promise that resolves to an object of type
* `VerifySmtpConnectionReturnType`. The `VerifySmtpConnectionReturnType` object has two properties:
* `success` and `error`. If the SMTP connection is verified successfully, the `success` property will
* be `true` and the `error` property will be `null`. If the SMTP connection verification fails
*/
async function verifySmtpConnection(
config: Record<string, string>,
): Promise<VerifySmtpConnectionReturnType> {
const transporter = nodemailer.createTransport({
host: config.SMTP_HOST,
port: Number(config.SMTP_PORT),
secure: config.SMTP_SSL_TLS === "true",
auth: {
user: config.SMTP_USERNAME,
pass: config.SMTP_PASSWORD,
},
});
try {
await transporter.verify();
console.log("SMTP connection verified successfully.");
return { success: true, error: null };
} catch (error: unknown) {
console.error("SMTP connection verification failed:");
return { success: false, error };
} finally {
transporter.close();
}
}
/**
* The function `configureSmtp` prompts the user to configure SMTP settings for sending emails through
* Talawa and saves the configuration in a .env file.
* @returns a Promise that resolves to void.
*/
async function configureSmtp(): Promise<void> {
const smtpConfig = await inquirer.prompt([
{
type: "input",
name: "SMTP_HOST",
message: "Enter SMTP host:",
},
{
type: "input",
name: "SMTP_PORT",
message: "Enter SMTP port:",
},
{
type: "input",
name: "SMTP_USERNAME",
message: "Enter SMTP username:",
},
{
type: "password",
name: "SMTP_PASSWORD",
message: "Enter SMTP password:",
},
{
type: "confirm",
name: "SMTP_SSL_TLS",
message: "Use SSL/TLS for SMTP?",
default: false,
},
]);
const isValidSmtpConfig =
smtpConfig.SMTP_HOST &&
smtpConfig.SMTP_PORT &&
smtpConfig.SMTP_USERNAME &&
smtpConfig.SMTP_PASSWORD;
if (!isValidSmtpConfig) {
console.error(
"Invalid SMTP configuration. Please provide all required parameters.",
);
return;
}
const { success, error } = await verifySmtpConnection(smtpConfig);
if (!success) {
console.error(
"SMTP configuration verification failed. Please check your SMTP settings.",
);
if (error instanceof Error) {
console.log(error.message);
}
return;
}
const config = dotenv.parse(fs.readFileSync(".env"));
config.IS_SMTP = "true";
Object.assign(config, smtpConfig);
updateEnvVariable(config);
console.log("SMTP configuration saved successfully.");
}
/**
* The main function sets up the Talawa API by prompting the user to configure various environment
* variables and import sample data if desired.
*/
async function main(): Promise<void> {
console.log("Welcome to the Talawa API setup! 🚀");
if (!fs.existsSync(".env")) {
fs.copyFileSync(".env.sample", ".env");
} else {
checkEnvFile();
}
if (process.env.NODE_ENV) {
console.log(`\nNode environment is already set to ${process.env.NODE_ENV}`);
}
await setNodeEnvironment();
let accessToken: string | null = "",
refreshToken: string | null = "";
if (process.env.ACCESS_TOKEN_SECRET) {
console.log(
`\nAccess token secret already exists with the value:\n${process.env.ACCESS_TOKEN_SECRET}`,
);
}
const { shouldGenerateAccessToken } = await inquirer.prompt({
type: "confirm",
name: "shouldGenerateAccessToken",
message: "Would you like to generate a new access token secret?",
default: process.env.ACCESS_TOKEN_SECRET ? false : true,
});
if (shouldGenerateAccessToken) {
accessToken = null;
}
if (process.env.REFRESH_TOKEN_SECRET) {
console.log(
`\nRefresh token secret already exists with the value:\n${process.env.REFRESH_TOKEN_SECRET}`,
);
}
const { shouldGenerateRefreshToken } = await inquirer.prompt({
type: "confirm",
name: "shouldGenerateRefreshToken",
message: "Would you like to generate a new refresh token secret?",
default: process.env.REFRESH_TOKEN_SECRET ? false : true,
});
if (shouldGenerateRefreshToken) {
refreshToken = null;
}
accessAndRefreshTokens(accessToken, refreshToken);
const { shouldLog } = await inquirer.prompt({
type: "confirm",
name: "shouldLog",
message: "Would you like to enable logging for the database transactions?",
default: true,
});
if (shouldLog) {
if (process.env.LOG_PATH) {
console.log(
`\n Log path already exists with the value:\n${process.env.LOG_PATH}`,
);
}
let logPath: string | null = null;
const { shouldUseCustomLogPath } = await inquirer.prompt({
type: "confirm",
name: "shouldUseCustomLogPath",
message: "Would you like to provide a custom path for storing logs?",
default: false,
});
if (shouldUseCustomLogPath) {
logPath = await askForTransactionLogPath();
}
transactionLogPath(logPath);
}
const { isDockerInstallation } = await inquirer.prompt({
type: "confirm",
name: "isDockerInstallation",
message: "Are you setting up this project using Docker?",
default: false,
});
if (isDockerInstallation) {
const DB_URL = "mongodb://localhost:27017/talawa-api";
const REDIS_HOST = "localhost";
const REDIS_PORT = "6379"; // default Redis port
const REDIS_PASSWORD = "";
const config = dotenv.parse(fs.readFileSync(".env"));
config.MONGO_DB_URL = DB_URL;
config.REDIS_HOST = REDIS_HOST;
config.REDIS_PORT = REDIS_PORT;
config.REDIS_PASSWORD = REDIS_PASSWORD;
process.env.MONGO_DB_URL = DB_URL;
process.env.REDIS_HOST = REDIS_HOST;
process.env.REDIS_PORT = REDIS_PORT;
process.env.REDIS_PASSWORD = REDIS_PASSWORD;
updateEnvVariable(config);
console.log(`Your MongoDB URL is:\n${process.env.MONGO_DB_URL}`);
console.log(`Your Redis host is:\n${process.env.REDIS_HOST}`);
console.log(`Your Redis port is:\n${process.env.REDIS_PORT}`);
}
if (!isDockerInstallation) {
// Redis configuration
if (process.env.REDIS_HOST && process.env.REDIS_PORT) {
const redisPasswordStr = process.env.REDIS_PASSWORD
? "X".repeat(process.env.REDIS_PASSWORD.length)
: "";
const url = `redis://${
process.env.REDIS_PASSWORD ? redisPasswordStr + "@" : ""
}${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`;
console.log(`\nRedis URL already exists with the value:\n${url}`);
const { shouldSetupRedis } = await inquirer.prompt({
type: "confirm",
name: "shouldSetupRedis",
message: "Would you like to change the existing Redis URL?",
default:
process.env.REDIS_HOST && process.env.REDIS_PORT ? false : true,
});
if (shouldSetupRedis) {
await redisConfiguration();
}
} else {
await redisConfiguration();
}
// MongoDB configuration
if (process.env.MONGO_DB_URL) {
console.log(
`\nMongoDB URL already exists with the value:\n${process.env.MONGO_DB_URL}`,