1
1
mirror of https://github.com/leon-ai/leon.git synced 2024-12-25 01:31:47 +03:00
leon/scripts/generate/generate-http-api-key.js

77 lines
1.8 KiB
JavaScript
Raw Normal View History

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'
import { LogHelper } from '@/helpers/log-helper'
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) => {
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')
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)
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) {
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)
}
})