logggai
Version:
AI-powered CLI for transforming your development work into professional content
117 lines β’ 4.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureValidSession = ensureValidSession;
exports.withAuth = withAuth;
exports.isTokenExpired = isTokenExpired;
exports.getTokenExpiration = getTokenExpiration;
exports.refreshAccessToken = refreshAccessToken;
const config_1 = require("./config");
const chalk = require("chalk");
const inquirer_1 = require("inquirer");
const login_1 = require("../commands/login");
const api_1 = require("./api");
const config = require('./config');
function getTokenExpiration() {
const expiresAt = (0, config_1.getConfig)('tokenExpiresAt');
if (!expiresAt)
return null;
return new Date(expiresAt);
}
function isTokenExpired() {
const exp = getTokenExpiration();
if (!exp)
return true;
// 5 min margin to avoid race conditions
return exp.getTime() < Date.now() + 5 * 60 * 1000;
}
/**
* Attempts to refresh the access token using the refresh token
* @returns true if refresh was successful, false otherwise
*/
async function refreshAccessToken() {
const sessionToken = config.getSessionToken();
if (!sessionToken) {
return false;
}
try {
console.log(chalk.default.blue('π Refreshing authentication token...'));
const response = await api_1.apiClient.refreshToken(sessionToken);
// Update stored tokens
config.setConfig('sessionToken', response.access_token);
// Garder le refresh_token existant si pas de nouveau fourni (Clerk gère nativement)
if (response.refresh_token) {
config.setConfig('refreshToken', response.refresh_token);
}
config.setConfig('tokenExpiresAt', Date.now() + (response.expires_in * 1000));
console.log(chalk.default.green('β
Token refreshed successfully'));
return true;
}
catch (error) {
if (error.message === 'REFRESH_TOKEN_EXPIRED') {
console.log(chalk.default.yellow('π Refresh token expired, please log in again'));
// Clear expired tokens
config.setConfig('sessionToken', undefined);
config.setConfig('refreshToken', undefined);
config.setConfig('tokenExpiresAt', undefined);
return false;
}
console.error(chalk.default.red('β Failed to refresh token:', error.message));
return false;
}
}
/**
* Ensures a valid session by checking token expiration and refreshing if needed
* @param relaunchFn Function to call after login (replays the command)
*/
async function ensureValidSession(relaunchFn) {
// Check if user is logged in
if (!config.isLoggedIn()) {
console.log(chalk.default.yellow('\nπ You need to log in first.'));
await (0, login_1.loginCommand)(false);
if (typeof relaunchFn === 'function') {
await relaunchFn();
return false;
}
return true;
}
// Check if token is expired or will expire soon
if (isTokenExpired()) {
console.log(chalk.default.yellow('\nβ° Your session will expire soon, attempting to refresh...'));
// Try to refresh the token
const refreshSuccess = await refreshAccessToken();
if (refreshSuccess) {
// Token refreshed successfully, continue
return true;
}
// Refresh failed, prompt for re-login
console.log(chalk.default.yellow('\nπ Please log in again to continue.'));
const { relog } = await inquirer_1.default.prompt([
{ type: 'confirm', name: 'relog', message: 'Do you want to log in now?', default: true }
]);
if (relog) {
await (0, login_1.loginCommand)(true); // force login
if (typeof relaunchFn === 'function') {
await relaunchFn();
return false; // Stop current command, relaunch has occurred
}
}
else {
process.exit(1);
}
}
return true;
}
/**
* Wrapper function to automatically handle authentication for commands
* @param commandFn The command function to execute
*/
async function withAuth(commandFn) {
const sessionValid = await ensureValidSession();
// Only execute the command if session validation didn't trigger a relaunch
if (sessionValid) {
return await commandFn();
}
// If relaunch occurred, exit gracefully
process.exit(0);
}
//# sourceMappingURL=auth.js.map