gcal-commander
Version:
A command-line interface for Google Calendar operations
79 lines (78 loc) • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCalendarAuth = getCalendarAuth;
exports.getCredentialsPath = getCredentialsPath;
exports.getTokenPath = getTokenPath;
const local_auth_1 = require("@google-cloud/local-auth");
const googleapis_1 = require("googleapis");
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const paths_1 = require("./utils/paths");
const SCOPES = ['https://www.googleapis.com/auth/calendar.events', 'https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = paths_1.AppPaths.getTokenPath();
const CREDENTIALS_PATH = paths_1.AppPaths.getCredentialsPath();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function loadSavedCredentialsIfExist() {
try {
const content = await (0, promises_1.readFile)(TOKEN_PATH, 'utf8');
const credentials = JSON.parse(content);
return googleapis_1.google.auth.fromJSON(credentials);
}
catch {
return null;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function saveCredentials(client) {
try {
const content = await (0, promises_1.readFile)(CREDENTIALS_PATH, 'utf8');
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
// eslint-disable-next-line camelcase
client_id: key.client_id,
// eslint-disable-next-line camelcase
client_secret: key.client_secret,
// eslint-disable-next-line camelcase
refresh_token: client.credentials.refresh_token,
type: 'authorized_user',
});
const tokenDir = (0, node_path_1.dirname)(TOKEN_PATH);
await (0, promises_1.mkdir)(tokenDir, { recursive: true });
await (0, promises_1.writeFile)(TOKEN_PATH, payload);
}
catch {
// Silently continue if credential saving fails - the auth will still work
// but the user will need to re-authenticate on next run
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function authorize() {
let client = await loadSavedCredentialsIfExist();
if (client) {
return client;
}
try {
client = await (0, local_auth_1.authenticate)({
keyfilePath: CREDENTIALS_PATH,
scopes: SCOPES,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}
catch (error) {
throw new Error(`Authentication failed: ${error}`);
}
}
async function getCalendarAuth() {
const client = await authorize();
return { client };
}
function getCredentialsPath() {
return CREDENTIALS_PATH;
}
function getTokenPath() {
return TOKEN_PATH;
}