2020-07-02 20:31:26 +02:00
|
|
|
const fs = require("fs")
|
2020-07-06 09:06:59 +02:00
|
|
|
const readline = require("readline")
|
|
|
|
const { budibaseAppsDir } = require("../../utilities/budibaseDir")
|
|
|
|
const ENV_FILE_PATH = "/.env"
|
2020-07-02 17:53:09 +02:00
|
|
|
|
2020-07-06 09:06:59 +02:00
|
|
|
exports.fetch = async function(ctx) {
|
|
|
|
ctx.status = 200
|
|
|
|
ctx.body = {
|
|
|
|
budibase: process.env.BUDIBASE_API_KEY,
|
|
|
|
sendgrid: process.env.SENDGRID_API_KEY,
|
|
|
|
}
|
2020-07-02 17:53:09 +02:00
|
|
|
}
|
|
|
|
|
2020-07-06 09:06:59 +02:00
|
|
|
exports.update = async function(ctx) {
|
|
|
|
const key = `${ctx.params.key.toUpperCase()}_API_KEY`
|
|
|
|
const value = ctx.request.body.value
|
|
|
|
// Set process.env
|
|
|
|
process.env[key] = value
|
2020-07-02 21:01:34 +02:00
|
|
|
|
2020-07-06 09:06:59 +02:00
|
|
|
// Write to file
|
|
|
|
await updateValues([key, value])
|
2020-07-02 21:01:34 +02:00
|
|
|
|
2020-07-06 09:06:59 +02:00
|
|
|
ctx.status = 200
|
|
|
|
ctx.message = `Updated ${ctx.params.key} API key succesfully.`
|
|
|
|
ctx.body = { [ctx.params.key]: ctx.request.body.value }
|
2020-07-02 17:53:09 +02:00
|
|
|
}
|
|
|
|
|
2020-07-06 09:06:59 +02:00
|
|
|
async function updateValues([key, value]) {
|
|
|
|
let newContent = ""
|
|
|
|
let keyExists = false
|
|
|
|
const readInterface = readline.createInterface({
|
|
|
|
input: fs.createReadStream(`${budibaseAppsDir()}/${ENV_FILE_PATH}`),
|
|
|
|
output: process.stdout,
|
|
|
|
console: false,
|
|
|
|
})
|
|
|
|
readInterface.on("line", function(line) {
|
|
|
|
// Mutate lines and change API Key
|
|
|
|
if (line.startsWith(key)) {
|
|
|
|
line = `${key}=${value}`
|
|
|
|
keyExists = true
|
|
|
|
}
|
|
|
|
newContent = `${newContent}\n${line}`
|
|
|
|
})
|
|
|
|
readInterface.on("close", function() {
|
|
|
|
// Write file here
|
|
|
|
if (!keyExists) {
|
|
|
|
// Add API Key if it doesn't exist in the file at all
|
|
|
|
newContent = `${newContent}\n${key}=${value}`
|
|
|
|
}
|
|
|
|
fs.writeFileSync(`${budibaseAppsDir()}/${ENV_FILE_PATH}`, newContent)
|
|
|
|
})
|
2020-07-02 17:53:09 +02:00
|
|
|
}
|