You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

41 lines
1.2 KiB

import { DATA_PATH } from '../config';
import * as path from 'path';
import * as fs from 'fs';
import * as _ from 'lodash';
const API_KEYS_FILE = path.join(DATA_PATH, 'api-keys.json');
if(!fs.existsSync(API_KEYS_FILE)) {
console.log(`${API_KEYS_FILE} doesn't exist, creating`);
fs.writeFileSync(API_KEYS_FILE, JSON.stringify({}), 'utf8');
}
export function getApiKey(grafanaUrl: string): string | null {
const data = fs.readFileSync(API_KEYS_FILE, 'utf8');
const apiKey = JSON.parse(data)[grafanaUrl];
if(_.isNil(apiKey)) {
return null;
}
return apiKey;
}
export function upsertApiKey(grafanaUrl: string, apiKey: string): void {
const data = fs.readFileSync(API_KEYS_FILE, 'utf8');
const apiKeys = JSON.parse(data);
apiKeys[grafanaUrl] = apiKey;
fs.writeFileSync(API_KEYS_FILE, JSON.stringify(apiKeys), 'utf8');
}
// TODO: query Grafana API if a key exists && remove the key if it doesn't work for specified grafanaUrl
export function validateGrafanaUrl(grafanaUrl: string) {
const host = new URL(grafanaUrl).origin;
const apiKey = getApiKey(host);
if (_.isNil(apiKey) || apiKey === '') {
throw new Error(`Please configure API key for ${host}`);
}
}