This basically works, but some things can be improved or need to be looked at, cf the TODOs in the code. Co-authored-by: Armaël Guéneau <armael.gueneau@ens-lyon.org> Co-authored-by: Quentin Dufour <quentin@deuxfleurs.fr> Reviewed-on: Deuxfleurs/dfl#9 Co-authored-by: Armael <armael@noreply.localhost> Co-committed-by: Armael <armael@noreply.localhost>
81 lines
2.2 KiB
TypeScript
81 lines
2.2 KiB
TypeScript
import { Configuration, WebsiteApi } from "guichet-sdk-ts";
|
|
import { read } from 'read';
|
|
import path from 'node:path';
|
|
import fs from 'node:fs/promises';
|
|
|
|
function configPath(): string {
|
|
let path = ".dfl/config.json";
|
|
if (process.env.XDG_CONFIG_HOME) {
|
|
path = process.env.XDG_CONFIG_HOME + "/dfl/config.json";
|
|
} else if (process.env.HOME) {
|
|
path = process.env.HOME + "/.config/dfl/config.json";
|
|
}
|
|
return path
|
|
}
|
|
|
|
interface PersistedConfig {
|
|
username: string,
|
|
password: string,
|
|
}
|
|
|
|
export async function openApiConf() {
|
|
let strConf: string;
|
|
let dictConf: PersistedConfig;
|
|
|
|
const configFile = configPath();
|
|
|
|
try {
|
|
strConf = await fs.readFile(configFile, { encoding: 'utf8' });
|
|
} catch (err) {
|
|
console.error(err, `\n\nUnable to read ${configFile}, run 'dfl login' first.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
try {
|
|
dictConf = JSON.parse(strConf);
|
|
} catch (err) {
|
|
console.error(err, `\n\nUnable to parse ${configFile} as JSON, check your syntax. Did you manually edit this file?`);
|
|
process.exit(1);
|
|
}
|
|
|
|
// @FIXME: we do not validate that the dictConf object really contains a username or password field...
|
|
|
|
return new Configuration({
|
|
username: dictConf.username,
|
|
password: dictConf.password,
|
|
});
|
|
}
|
|
|
|
export async function login(username: string) {
|
|
const password = await read({
|
|
prompt: "password: ",
|
|
silent: true,
|
|
replace: "*"
|
|
});
|
|
|
|
// check config
|
|
const testConf = new Configuration({
|
|
username: username,
|
|
password: password,
|
|
});
|
|
const web = new WebsiteApi(testConf);
|
|
try {
|
|
await web.listWebsites();
|
|
} catch (err) {
|
|
console.error(err, `\n\nLogin failed. Is your username and password correct?`);
|
|
process.exit(1);
|
|
}
|
|
|
|
// create config folder if needed
|
|
const configFile = configPath();
|
|
const parent = path.dirname(configFile);
|
|
await fs.mkdir(parent, { recursive: true });
|
|
|
|
// create, serialize, save config data
|
|
const configData: PersistedConfig = { username, password };
|
|
const serializedConfig = JSON.stringify(configData);
|
|
await fs.writeFile(configFile, serializedConfig, { mode: 0o600 });
|
|
// @FIXME: we would like to avoid storing the password in clear text in the future.
|
|
|
|
console.log('ok')
|
|
}
|