weaver-frontend-cli
Version:
🕷️ Weaver CLI - Generador completo de arquitectura Clean Architecture para entidades CRUD y flujos de negocio desde OpenAPI/Swagger
199 lines • 8.12 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthManager = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const chalk_1 = __importDefault(require("chalk"));
const inquirer_1 = __importDefault(require("inquirer"));
class AuthManager {
/**
* Verifica si el usuario está autenticado
*/
static async isAuthenticated() {
const configPath = path.join(this.CONFIG_DIR, this.CONFIG_FILE);
try {
if (await fs.pathExists(configPath)) {
const configData = await fs.readFile(configPath, 'utf8');
const config = JSON.parse(configData);
// Verificar que la clave almacenada sea válida y no haya expirado
if (config.key === this.VALID_KEY && config.timestamp) {
const now = new Date().getTime();
const authTime = new Date(config.timestamp).getTime();
const thirtyDays = 30 * 24 * 60 * 60 * 1000; // 30 días en milisegundos
// La autenticación es válida por 30 días
if (now - authTime < thirtyDays) {
return true;
}
}
}
}
catch (error) {
// Si hay error leyendo el archivo, considerar no autenticado
console.log(chalk_1.default.yellow('⚠️ Error verificando autenticación, reautenticación requerida'));
}
return false;
}
/**
* Solicita la clave de acceso al usuario
*/
static async requestAuthentication() {
console.log(chalk_1.default.blue.bold('\n🔐 Autenticación Requerida'));
console.log(chalk_1.default.gray('🕷️ Weaver CLI requiere una clave de acceso\n'));
const { accessKey } = await inquirer_1.default.prompt([
{
type: 'password',
name: 'accessKey',
message: 'Ingresa la clave de acceso:',
mask: '*',
validate: (input) => {
if (!input.trim()) {
return 'La clave de acceso es requerida';
}
return true;
}
}
]);
if (accessKey === this.VALID_KEY) {
await this.saveAuthentication();
console.log(chalk_1.default.green('✅ Autenticación exitosa!'));
console.log(chalk_1.default.gray('La sesión será válida por 30 días\n'));
return true;
}
else {
console.log(chalk_1.default.red('❌ Clave de acceso incorrecta'));
const { retry } = await inquirer_1.default.prompt([
{
type: 'confirm',
name: 'retry',
message: '¿Intentar nuevamente?',
default: true
}
]);
if (retry) {
return await this.requestAuthentication();
}
else {
console.log(chalk_1.default.yellow('🚪 Saliendo del generador'));
process.exit(0);
}
}
}
/**
* Guarda la autenticación en el sistema
*/
static async saveAuthentication() {
const configPath = path.join(this.CONFIG_DIR, this.CONFIG_FILE);
const config = {
key: this.VALID_KEY,
timestamp: new Date().toISOString(),
version: '1.0.0'
};
try {
await fs.writeFile(configPath, JSON.stringify(config, null, 2));
// Hacer el archivo legible solo por el usuario (permisos 600)
await fs.chmod(configPath, 0o600);
}
catch (error) {
console.log(chalk_1.default.yellow('⚠️ No se pudo guardar la autenticación, requerirá clave en cada uso'));
}
}
/**
* Cierra la sesión del usuario
*/
static async logout() {
const configPath = path.join(this.CONFIG_DIR, this.CONFIG_FILE);
try {
if (await fs.pathExists(configPath)) {
await fs.remove(configPath);
console.log(chalk_1.default.green('✅ Sesión cerrada exitosamente'));
}
else {
console.log(chalk_1.default.yellow('⚠️ No hay sesión activa'));
}
}
catch (error) {
console.log(chalk_1.default.red('❌ Error cerrando sesión'));
}
}
/**
* Muestra información de la sesión actual
*/
static async showSessionInfo() {
const configPath = path.join(this.CONFIG_DIR, this.CONFIG_FILE);
try {
if (await fs.pathExists(configPath)) {
const configData = await fs.readFile(configPath, 'utf8');
const config = JSON.parse(configData);
console.log(chalk_1.default.blue('\n📊 Información de Sesión:'));
console.log(chalk_1.default.gray(`Autenticado: ${await this.isAuthenticated() ? 'Sí' : 'No'}`));
console.log(chalk_1.default.gray(`Fecha de autenticación: ${new Date(config.timestamp).toLocaleString()}`));
console.log(chalk_1.default.gray(`Versión: ${config.version}`));
const now = new Date().getTime();
const authTime = new Date(config.timestamp).getTime();
const daysLeft = Math.max(0, 30 - Math.floor((now - authTime) / (24 * 60 * 60 * 1000)));
console.log(chalk_1.default.gray(`Días restantes: ${daysLeft}`));
}
else {
console.log(chalk_1.default.yellow('⚠️ No hay sesión activa'));
}
}
catch (error) {
console.log(chalk_1.default.red('❌ Error obteniendo información de sesión'));
}
}
/**
* Middleware de autenticación que debe ejecutarse antes del menú principal
*/
static async authenticate() {
console.log(chalk_1.default.blue('🔍 Verificando autenticación...'));
if (await this.isAuthenticated()) {
console.log(chalk_1.default.green('✅ Autenticado correctamente\n'));
return true;
}
else {
return await this.requestAuthentication();
}
}
}
exports.AuthManager = AuthManager;
AuthManager.VALID_KEY = 'soyia';
AuthManager.CONFIG_FILE = '.weaver-cli-auth';
AuthManager.CONFIG_DIR = os.homedir();
//# sourceMappingURL=auth-manager.js.map