refactor: streamline session state management using configuration functions
This commit is contained in:
@@ -2,10 +2,11 @@
|
||||
|
||||
import open, { apps } from "open";
|
||||
import fs from "node:fs";
|
||||
import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
|
||||
import { writeFile, mkdir, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { PublicClientApplication } from "@azure/msal-node";
|
||||
import { getConfig, getConfigDir } from "@slawek/sk-tools";
|
||||
import type {
|
||||
AccountInfo,
|
||||
AuthenticationResult,
|
||||
@@ -27,6 +28,7 @@ const LOGIN_REQUIRED_MESSAGE = "Login required. Run: sk-az-tools login";
|
||||
const BROWSER_KEYWORDS = Object.keys(apps).sort();
|
||||
const OPEN_APPS = apps as Record<string, string | readonly string[]>;
|
||||
const CHROMIUM_BROWSERS = new Set(["edge", "chrome", "brave"]);
|
||||
const CONFIG_FILE_NAME = "config";
|
||||
|
||||
type SessionState = {
|
||||
activeAccountUpn: string | null;
|
||||
@@ -86,37 +88,26 @@ function getCacheRoot(): string {
|
||||
: path.join(userRoot, ".config", "sk-az-tools");
|
||||
}
|
||||
|
||||
function getSessionFilePath(): string {
|
||||
return path.join(getCacheRoot(), "login-session.json");
|
||||
}
|
||||
|
||||
async function readSessionState(): Promise<SessionState> {
|
||||
try {
|
||||
const sessionJson = await readFile(getSessionFilePath(), "utf8");
|
||||
const parsed = JSON.parse(sessionJson) as { activeAccountUpn?: unknown };
|
||||
const parsed = (await getConfig("sk-az-tools", CONFIG_FILE_NAME)) as { activeAccountUpn?: unknown };
|
||||
return {
|
||||
activeAccountUpn:
|
||||
typeof parsed?.activeAccountUpn === "string"
|
||||
? parsed.activeAccountUpn
|
||||
: null,
|
||||
};
|
||||
} catch (err) {
|
||||
if ((err as { code?: string } | null)?.code === "ENOENT") {
|
||||
return { activeAccountUpn: null };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeSessionState(state: SessionState): Promise<void> {
|
||||
const sessionPath = getSessionFilePath();
|
||||
const sessionPath = path.join(getConfigDir("sk-az-tools"), `${CONFIG_FILE_NAME}.json`);
|
||||
await mkdir(path.dirname(sessionPath), { recursive: true });
|
||||
await writeFile(sessionPath, JSON.stringify(state, null, 2), "utf8");
|
||||
}
|
||||
|
||||
async function clearSessionState(): Promise<void> {
|
||||
try {
|
||||
await unlink(getSessionFilePath());
|
||||
const sessionPath = path.join(getConfigDir("sk-az-tools"), `${CONFIG_FILE_NAME}.json`);
|
||||
await unlink(sessionPath);
|
||||
} catch (err) {
|
||||
if ((err as { code?: string } | null)?.code !== "ENOENT") {
|
||||
throw err;
|
||||
|
||||
Reference in New Issue
Block a user