1
1
mirror of https://github.com/leon-ai/leon.git synced 2024-12-24 17:23:23 +03:00
leon/scripts/generate/generate-http-api-key.js

78 lines
1.8 KiB
JavaScript
Raw Normal View History

import fs from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import dotenv from 'dotenv'
import { prompt } from 'inquirer'
2022-01-16 17:22:49 +03:00
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
*/
2023-04-27 15:24:16 +03:00
const generateHTTPAPIKey = () =>
2022-09-03 14:12:41 +03:00
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'
2023-04-02 21:34:50 +03:00
let content = await fs.promises.readFile(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
2023-04-02 21:34:50 +03:00
await fs.promises.writeFile(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 === ''
) {
2023-04-27 15:24:16 +03:00
await generateHTTPAPIKey()
2022-09-03 14:12:41 +03:00
} else if (!process.env.IS_DOCKER) {
const answer = await prompt({
type: 'confirm',
2023-04-27 15:24:16 +03:00
name: 'generate.httpAPIKey',
2022-09-03 14:12:41 +03:00
message: 'Do you want to regenerate the HTTP API key?',
default: false
})
2023-04-27 15:24:16 +03:00
if (answer.generate.httpAPIKey === true) {
await generateHTTPAPIKey()
2022-09-03 14:12:41 +03:00
}
2022-01-16 17:22:49 +03:00
}
2022-09-03 14:12:41 +03:00
resolve()
} catch (e) {
reject(e)
}
})