-
-
Notifications
You must be signed in to change notification settings - Fork 823
/
setup.ts
1186 lines (1083 loc) · 36.8 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
/* eslint-disable no-restricted-imports */
import * as cryptolib from "crypto";
import dotenv from "dotenv";
import fs from "fs";
import inquirer from "inquirer";
import path from "path";
import type { ExecException } from "child_process";
import { exec } from "child_process";
import { MongoClient } from "mongodb";
import { MAXIMUM_IMAGE_SIZE_LIMIT_KB } from "./src/constants";
import {
askForMongoDBUrl,
checkConnection,
checkExistingMongoDB,
} from "./src/setup/MongoDB";
import { askToKeepValues } from "./src/setup/askToKeepValues";
import { getNodeEnvironment } from "./src/setup/getNodeEnvironment";
import { isValidEmail } from "./src/setup/isValidEmail";
import { validateRecaptcha } from "./src/setup/reCaptcha";
import {
askForRedisUrl,
checkExistingRedis,
checkRedisConnection,
} from "./src/setup/redisConfiguration";
import {
setImageUploadSize,
validateImageFileSize,
} from "./src/setup/setImageUploadSize";
import { askForSuperAdminEmail } from "./src/setup/superAdmin";
import { updateEnvVariable } from "./src/setup/updateEnvVariable";
import { verifySmtpConnection } from "./src/setup/verifySmtpConnection";
import { loadDefaultOrganiation } from "./src/utilities/loadDefaultOrg";
import { isMinioInstalled } from "./src/setup/isMinioInstalled";
import { installMinio } from "./src/setup/installMinio";
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.
*/
export function checkEnvFile(): void {
if (process.env.NODE_ENV === "test") {
const env = dotenv.parse(fs.readFileSync(".env_test"));
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_test", `${key}=${envSample[key]}\n`);
}
}
} else {
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`);
}
}
}
}
/**
* The function `setNodeEnvironment` sets the Node environment by reading the value from a file, updating the process
* environment variable, and updating a configuration file.
*/
export async function setNodeEnvironment(): Promise<void> {
if (process.env.NODE_ENV === "test") {
try {
const nodeEnv = await getNodeEnvironment();
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.NODE_ENV = nodeEnv;
updateEnvVariable(config);
} catch (err) {
console.error(err);
abort();
}
} else {
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.
*/
export async function accessAndRefreshTokens(
accessTokenSecret: string | null,
refreshTokenSecret: string | null,
): Promise<void> {
if (process.env.NODE_ENV === "test") {
const config = dotenv.parse(fs.readFileSync(".env_test"));
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);
}
} else {
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);
}
}
}
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 = null;
let isValidPath = false;
while (!isValidPath) {
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);
isValidPath = true;
} 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 as string;
}
//Wipes the existing data in the database
/**
* The function `wipeExistingData` deletes all existing data in a MongoDB database if the database URL is provided.
* @param url - A string representing the URL of the MongoDB database.
* @returns The function returns a Promise that resolves to `void`.
*/
export async function wipeExistingData(url: string): Promise<void> {
const client = new MongoClient(`${url}`);
try {
await client.connect();
const db = client.db();
const collections = await db.listCollections().toArray();
if (collections.length > 0) {
for (const collection of collections) {
await db.collection(collection.name).deleteMany({});
}
console.log("All existing data has been deleted.");
}
} catch {
console.error("Could not connect to database to check for data");
}
client.close();
// return shouldImport;
}
//Check if the database is empty
/**
* The function `checkDb` checks if a MongoDB database is empty by connecting to the database and checking if any
* collections exist.
* @param url - A string representing the URL of the MongoDB database.
* @returns The function returns a Promise that resolves to a boolean value.
*/
export async function checkDb(url: string): Promise<boolean> {
let dbEmpty = false;
const client = new MongoClient(`${url}`);
try {
await client.connect();
const db = client.db();
const collections = await db.listCollections().toArray();
if (collections.length > 0) {
console.log("Existing data found in the database");
dbEmpty = false;
} else {
dbEmpty = true;
}
} catch {
console.error("Could not connect to database to check for data");
}
client.close();
return dbEmpty;
}
//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`.
*/
export async function importData(): Promise<void> {
if (!process.env.MONGO_DB_URL) {
console.log("Couldn't find mongodb url");
return;
}
console.log("Importing sample data...");
if (process.env.NODE_ENV !== "test") {
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}`);
},
);
}
}
//Import Default data
/**
* The function `importDefaultData` imports default data into a MongoDB database if the database URL is provided.
* @returns The function returns a Promise that resolves to `void`.
*/
export async function importDefaultData(): Promise<void> {
if (!process.env.MONGO_DB_URL) {
console.log("Couldn't find mongodb url");
return;
}
console.log("Importing default data...");
if (process.env.NODE_ENV !== "test") {
await loadDefaultOrganiation();
}
}
// 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.
*/
export 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 .env_test
if (process.env.NODE_ENV === "test") {
// Update the .env_test file
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.REDIS_HOST = host;
config.REDIS_PORT = port.toString();
config.REDIS_PASSWORD = password;
updateEnvVariable(config);
} else {
// 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();
}
}
// 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.
*/
export async function superAdmin(): Promise<void> {
try {
const email = await askForSuperAdminEmail();
if (process.env.NODE_ENV === "test") {
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.LAST_RESORT_SUPERADMIN_EMAIL = email;
updateEnvVariable(config);
} else {
const config = dotenv.parse(fs.readFileSync(".env"));
config.LAST_RESORT_SUPERADMIN_EMAIL = email;
updateEnvVariable(config);
}
} catch (err) {
console.log(err);
abort();
}
}
// Get the mongodb url
/**
* The `mongoDB` function manages the connection to a MongoDB database.
* It performs the following steps:
* 1. Checks if there is an existing MongoDB URL in the environment variables.
* 2. If an existing URL is found, it attempts to establish a connection to the URL.
* - If the connection is successful, it returns the URL.
* - If the connection fails, it returns null.
* 3. If a URL is returned from the previous step (i.e., a successful connection was made), it prompts the user to either keep the existing URL or change it.
* 4. If null is returned from the previous step (i.e., no successful connection was made), it prompts the user to enter a new MongoDB URL.
* 5. It then enters a loop where it continues to prompt the user for a MongoDB URL until a successful connection can be made.
* 6. Once a successful connection is made, it saves the MongoDB URL to the environment variables.
* This function is part of the initial setup process and is designed to ensure a valid MongoDB connection before proceeding.
*/
export 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! 🎉");
}
if (process.env.NODE_ENV === "test") {
DB_URL = `${url?.endsWith("/talawa-api") ? url : `${url}/talawa-api`}`;
const config = dotenv.parse(fs.readFileSync(".env_test"));
// Not updating actual environmental variable when in testing environment.
config.MONGO_DB_URL = DB_URL;
updateEnvVariable(config);
} else {
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();
}
}
//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.
*/
export 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 (process.env.NODE_ENV === "test") {
if (shouldKeepDetails) {
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.RECAPTCHA_SECRET_KEY = recaptchaSecretKey;
updateEnvVariable(config);
}
} else {
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.
*/
export 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 (process.env.NODE_ENV === "test") {
if (shouldKeepDetails) {
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.RECAPTCHA_SITE_KEY = recaptchaSiteKeyInp;
updateEnvVariable(config);
}
} else {
if (shouldKeepDetails) {
const config = dotenv.parse(fs.readFileSync(".env"));
config.RECAPTCHA_SITE_KEY = recaptchaSiteKeyInp;
updateEnvVariable(config);
} else {
await recaptchaSiteKey();
}
}
}
/**
* The `abort` function logs a message and exits the process.
*/
export 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.
*/
export 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): string | boolean =>
isValidEmail(input) || "Invalid email. Please try again.",
},
{
type: "password",
name: "password",
message: "Enter the generated password:",
},
]);
if (process.env.NODE_ENV === "test") {
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.MAIL_USERNAME = email;
config.MAIL_PASSWORD = password;
updateEnvVariable(config);
} else {
const config = dotenv.parse(fs.readFileSync(".env"));
config.MAIL_USERNAME = email;
config.MAIL_PASSWORD = password;
updateEnvVariable(config);
}
}
/**
* 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.
*/
export 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;
}
if (process.env.NODE_ENV === "test") {
const config = dotenv.parse(fs.readFileSync(".env_test"));
config.IS_SMTP = "true";
Object.assign(config, smtpConfig);
updateEnvVariable(config);
} else {
const config = dotenv.parse(fs.readFileSync(".env"));
config.IS_SMTP = "true";
Object.assign(config, smtpConfig);
updateEnvVariable(config);
}
console.log("SMTP configuration saved successfully.");
}
/**
* Configures MinIO settings, including installation check, data directory, and credentials.
*
* This function performs the following steps:
* 1. Checks if MinIO is installed (for non-Docker installations)
* 2. Prompts for MinIO installation if not found
* 3. Checks for existing MinIO data directory configuration
* 4. Allows user to change the data directory if desired
* 5. Prompts for MinIO root user, password, and bucket name
* 6. Updates the environment variables with the new configuration
*
* @param isDockerInstallation - A boolean indicating whether the setup is for a Docker installation.
* @throws Will throw an error if there are issues with file operations or user input validation.
* @returns A Promise that resolves when the configuration is complete.
*/
export async function configureMinio(
isDockerInstallation: boolean,
): Promise<void> {
if (!isDockerInstallation) {
console.log("Checking MinIO installation...");
if (isMinioInstalled()) {
console.log("MinIO is already installed.");
} else {
console.log("MinIO is not installed on your system.");
const { installMinioNow } = await inquirer.prompt([
{
type: "confirm",
name: "installMinioNow",
message: "Would you like to install MinIO now?",
default: true,
},
]);
if (installMinioNow) {
console.log("Installing MinIO...");
try {
await installMinio();
console.log("Successfully installed MinIO on your system.");
} catch (err) {
console.error(err);
return;
}
} else {
console.log(
"MinIO installation skipped. Please install MinIO manually before proceeding.",
);
return;
}
}
}
const envFile = process.env.NODE_ENV === "test" ? ".env_test" : ".env";
const config = dotenv.parse(fs.readFileSync(envFile));
const currentDataDir = config.MINIO_DATA_DIR || process.env.MINIO_DATA_DIR;
let changeDataDir = false;
if (currentDataDir) {
console.log(
`[MINIO] Existing MinIO data directory found: ${currentDataDir}`,
);
const { confirmChange } = await inquirer.prompt([
{
type: "confirm",
name: "confirmChange",
message:
"Do you want to change the MinIO data directory? (Warning: All existing data will be lost)",
default: false,
},
]);
changeDataDir = confirmChange;
}
if (!currentDataDir || changeDataDir) {
const { MINIO_DATA_DIR } = await inquirer.prompt([
{
type: "input",
name: "MINIO_DATA_DIR",
message: "Enter MinIO data directory (press Enter for default):",
default: "./data",
validate: (input: string): boolean | string =>
input.trim() !== "" ? true : "MinIO data directory is required.",
},
]);
if (changeDataDir && currentDataDir) {
try {
fs.rmSync(currentDataDir, { recursive: true, force: true });
console.log(
`[MINIO] Removed existing data directory: ${currentDataDir}`,
);
} catch (err) {
console.error(`[MINIO] Error removing existing data directory: ${err}`);
}
}
config.MINIO_DATA_DIR = MINIO_DATA_DIR;
console.log(`[MINIO] MinIO data directory set to: ${MINIO_DATA_DIR}`);
let fullPath = MINIO_DATA_DIR;
if (!path.isAbsolute(MINIO_DATA_DIR)) {
fullPath = path.join(process.cwd(), MINIO_DATA_DIR);
}
if (!fs.existsSync(fullPath)) {
fs.mkdirSync(fullPath, { recursive: true });
}
}
const minioConfig = await inquirer.prompt([
{
type: "input",
name: "MINIO_ROOT_USER",
message: "Enter MinIO root user:",
default:
config.MINIO_ROOT_USER || process.env.MINIO_ROOT_USER || "talawa",
validate: (input: string): boolean | string =>
input.trim() !== "" ? true : "MinIO root user is required.",
},
{
type: "password",
name: "MINIO_ROOT_PASSWORD",
message: "Enter MinIO root password:",
default:
config.MINIO_ROOT_PASSWORD ||
process.env.MINIO_ROOT_PASSWORD ||
"talawa1234",
validate: (input: string): boolean | string =>
input.trim() !== "" ? true : "MinIO root password is required.",
},
{
type: "input",
name: "MINIO_BUCKET",
message: "Enter MinIO bucket name:",
default: config.MINIO_BUCKET || process.env.MINIO_BUCKET || "talawa",
validate: (input: string): boolean | string =>
input.trim() !== "" ? true : "MinIO bucket name is required.",
},
]);
const minioEndpoint = isDockerInstallation
? "http://minio:9000"
: "http://localhost:9000";
config.MINIO_ENDPOINT = minioEndpoint;
config.MINIO_ROOT_USER = minioConfig.MINIO_ROOT_USER;
config.MINIO_ROOT_PASSWORD = minioConfig.MINIO_ROOT_PASSWORD;
config.MINIO_BUCKET = minioConfig.MINIO_BUCKET;
updateEnvVariable(config);
console.log("[MINIO] MinIO configuration added successfully.\n");
}
/**
* 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 (!fs.existsSync(".env_test")) {
fs.copyFileSync(".env.sample", ".env_test");
} 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 us to auto-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 us to auto-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 MINIO_ENDPOINT = "http://minio:9000";
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;
config.MINIO_ENDPOINT = MINIO_ENDPOINT;
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;
process.env.MINIO_ENDPOINT = MINIO_ENDPOINT;
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}`);
console.log(`Your MinIO endpoint is:\n${process.env.MINIO_ENDPOINT}`);
}
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}`,
);
const { shouldSetupMongo } = await inquirer.prompt({
type: "confirm",
name: "shouldSetupMongo",
message: "Would you like to change the existing Mongo DB URL?",
default: false,
});
if (shouldSetupMongo) {
await mongoDB();
}
} else {
await mongoDB();
}
}
if (process.env.RECAPTCHA_SECRET_KEY) {
console.log(