2022-01-16 17:22:49 +03:00
|
|
|
import dotenv from 'dotenv'
|
|
|
|
import crypto from 'crypto'
|
|
|
|
import fs from 'fs'
|
|
|
|
import { prompt } from 'inquirer'
|
|
|
|
import path from 'path'
|
|
|
|
|
2022-09-26 16:29:56 +03:00
|
|
|
import { LogHelper } from '@/helpers/log-helper'
|
2022-09-25 19:44:40 +03:00
|
|
|
import { StringHelper } from '@/helpers/string-helper'
|
2022-01-16 17:22:49 +03:00
|
|
|
|
|
|
|
dotenv.config()
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate HTTP API key script
|
|
|
|
* save it in the .env file
|
|
|
|
*/
|
2022-09-03 14:12:41 +03:00
|
|
|
const generateHttpApiKey = () =>
|
|
|
|
new Promise(async (resolve, reject) => {
|
2022-09-26 16:29:56 +03:00
|
|
|
LogHelper.info('Generating the HTTP API key...')
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
try {
|
|
|
|
const shasum = crypto.createHash('sha1')
|
2022-09-25 19:44:40 +03:00
|
|
|
const str = StringHelper.random(11)
|
2022-09-03 14:12:41 +03:00
|
|
|
const dotEnvPath = path.join(process.cwd(), '.env')
|
|
|
|
const envVarKey = 'LEON_HTTP_API_KEY'
|
|
|
|
let content = fs.readFileSync(dotEnvPath, 'utf8')
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
shasum.update(str)
|
|
|
|
const sha1 = shasum.digest('hex')
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
let lines = content.split('\n')
|
|
|
|
lines = lines.map((line) => {
|
|
|
|
if (line.indexOf(`${envVarKey}=`) !== -1) {
|
|
|
|
line = `${envVarKey}=${sha1}`
|
|
|
|
}
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
return line
|
|
|
|
})
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
content = lines.join('\n')
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
fs.writeFileSync(dotEnvPath, content)
|
2022-09-26 16:29:56 +03:00
|
|
|
LogHelper.success('HTTP API key generated')
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
resolve()
|
|
|
|
} catch (e) {
|
2022-09-26 16:29:56 +03:00
|
|
|
LogHelper.error(e.message)
|
2022-09-03 14:12:41 +03:00
|
|
|
reject(e)
|
|
|
|
}
|
|
|
|
})
|
2022-01-16 17:22:49 +03:00
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
export default () =>
|
|
|
|
new Promise(async (resolve, reject) => {
|
|
|
|
try {
|
|
|
|
if (
|
|
|
|
!process.env.LEON_HTTP_API_KEY ||
|
|
|
|
process.env.LEON_HTTP_API_KEY === ''
|
|
|
|
) {
|
2022-01-16 17:22:49 +03:00
|
|
|
await generateHttpApiKey()
|
2022-09-03 14:12:41 +03:00
|
|
|
} else if (!process.env.IS_DOCKER) {
|
|
|
|
const answer = await prompt({
|
|
|
|
type: 'confirm',
|
|
|
|
name: 'generate.httpApiKey',
|
|
|
|
message: 'Do you want to regenerate the HTTP API key?',
|
|
|
|
default: false
|
|
|
|
})
|
|
|
|
|
|
|
|
if (answer.generate.httpApiKey === true) {
|
|
|
|
await generateHttpApiKey()
|
|
|
|
}
|
2022-01-16 17:22:49 +03:00
|
|
|
}
|
|
|
|
|
2022-09-03 14:12:41 +03:00
|
|
|
resolve()
|
|
|
|
} catch (e) {
|
|
|
|
reject(e)
|
|
|
|
}
|
|
|
|
})
|