@vladimirdukelic/revolutionary-ui-factory
Version:
Revolutionary UI Factory System v2 - Generate ANY UI component for ANY framework with 60-95% code reduction
349 lines β’ 12.9 kB
JavaScript
;
/**
* Authentication Manager for Revolutionary UI Factory
* Handles user authentication, token storage, and premium feature access
*/
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/promises"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
const chalk_1 = __importDefault(require("chalk"));
class AuthManager {
static CONFIG_DIR = path.join(os.homedir(), '.revolutionary-ui');
static AUTH_FILE = 'auth.json';
static AUTH_PATH = path.join(AuthManager.CONFIG_DIR, AuthManager.AUTH_FILE);
static LOGIN_URL = 'https://revolutionary-ui.com/cli-login';
static API_BASE = 'https://api.revolutionary-ui.com/v1';
/**
* Initialize auth manager and ensure config directory exists
*/
static async init() {
try {
await fs.mkdir(AuthManager.CONFIG_DIR, { recursive: true });
}
catch (error) {
// Directory might already exist
}
}
/**
* Check if user is authenticated
*/
static async isAuthenticated() {
try {
const config = await this.loadConfig();
if (!config.accessToken)
return false;
// Check if token is expired
if (config.expiresAt) {
const expiryDate = new Date(config.expiresAt);
if (expiryDate < new Date()) {
// Try to refresh token
if (config.refreshToken) {
return await this.refreshAuth(config.refreshToken);
}
return false;
}
}
return true;
}
catch {
return false;
}
}
/**
* Get current auth configuration
*/
static async getAuth() {
try {
return await this.loadConfig();
}
catch {
return null;
}
}
/**
* Start login process
*/
static async login() {
await this.init();
console.log(chalk_1.default.cyan('\nπ Opening browser for authentication...'));
console.log(chalk_1.default.gray(`URL: ${this.LOGIN_URL}`));
// Generate a unique session ID for this login attempt
const sessionId = this.generateSessionId();
const loginUrl = `${this.LOGIN_URL}?session=${sessionId}&source=cli`;
// Open browser
await this.openBrowser(loginUrl);
console.log(chalk_1.default.yellow('\nβ³ Waiting for authentication...'));
console.log(chalk_1.default.gray('Please complete the login process in your browser.'));
console.log(chalk_1.default.gray('You can close this terminal if needed - your session will be saved.\n'));
// Poll for authentication completion
const authenticated = await this.pollForAuth(sessionId);
if (authenticated) {
const auth = await this.getAuth();
console.log(chalk_1.default.green('\nβ
Authentication successful!'));
console.log(chalk_1.default.gray(`Logged in as: ${auth?.userEmail}`));
console.log(chalk_1.default.gray(`Subscription: ${auth?.subscriptionPlan?.toUpperCase() || 'FREE'}`));
// Show available features
if (auth?.features) {
console.log(chalk_1.default.cyan('\n⨠Available Features:'));
const features = this.getEnabledFeatures(auth.features);
features.forEach(feature => {
console.log(chalk_1.default.gray(` β’ ${feature}`));
});
}
return true;
}
else {
console.log(chalk_1.default.red('\nβ Authentication failed or timed out.'));
console.log(chalk_1.default.gray('Please try again or contact support if the issue persists.'));
return false;
}
}
/**
* Logout user
*/
static async logout() {
try {
await fs.unlink(this.AUTH_PATH);
console.log(chalk_1.default.green('\nβ
Successfully logged out!'));
}
catch (error) {
console.log(chalk_1.default.yellow('\nβ οΈ You were not logged in.'));
}
}
/**
* Check if user has access to a specific feature
*/
static async hasFeature(feature) {
const auth = await this.getAuth();
if (!auth || !auth.features)
return false;
return auth.features[feature] || false;
}
/**
* Get user's subscription plan
*/
static async getSubscriptionPlan() {
const auth = await this.getAuth();
return auth?.subscriptionPlan || 'free';
}
/**
* Check if subscription is active
*/
static async isSubscriptionActive() {
const auth = await this.getAuth();
return auth?.subscriptionStatus === 'active' || auth?.subscriptionStatus === 'trialing';
}
/**
* Save authentication config
*/
static async saveConfig(config) {
await fs.writeFile(this.AUTH_PATH, JSON.stringify(config, null, 2), 'utf-8');
// Set restrictive permissions (user read/write only)
await fs.chmod(this.AUTH_PATH, 0o600);
}
/**
* Load authentication config
*/
static async loadConfig() {
const data = await fs.readFile(this.AUTH_PATH, 'utf-8');
return JSON.parse(data);
}
/**
* Generate unique session ID
*/
static generateSessionId() {
return `cli_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
/**
* Open browser with URL
*/
static async openBrowser(url) {
const platform = process.platform;
let command;
let args;
if (platform === 'darwin') {
command = 'open';
args = [url];
}
else if (platform === 'win32') {
command = 'cmd';
args = ['/c', 'start', url];
}
else {
command = 'xdg-open';
args = [url];
}
return new Promise((resolve) => {
const child = (0, child_process_1.spawn)(command, args, { detached: true, stdio: 'ignore' });
child.unref();
resolve();
});
}
/**
* Poll for authentication completion
*/
static async pollForAuth(sessionId, maxAttempts = 60) {
for (let i = 0; i < maxAttempts; i++) {
try {
// Check with API if authentication is complete
const response = await fetch(`${this.API_BASE}/auth/cli-session/${sessionId}`);
if (response.ok) {
const data = await response.json();
if (data.status === 'authenticated') {
// Save authentication data
await this.saveConfig({
accessToken: data.accessToken,
refreshToken: data.refreshToken,
userId: data.userId,
userEmail: data.userEmail,
subscriptionPlan: data.subscriptionPlan,
subscriptionStatus: data.subscriptionStatus,
expiresAt: data.expiresAt,
features: data.features
});
return true;
}
}
}
catch (error) {
// API might not be available, continue polling
}
// Wait 2 seconds before next attempt
await new Promise(resolve => setTimeout(resolve, 2000));
}
return false;
}
/**
* Refresh authentication token
*/
static async refreshAuth(refreshToken) {
try {
const response = await fetch(`${this.API_BASE}/auth/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ refreshToken })
});
if (response.ok) {
const data = await response.json();
const currentConfig = await this.loadConfig();
await this.saveConfig({
...currentConfig,
accessToken: data.accessToken,
expiresAt: data.expiresAt
});
return true;
}
}
catch (error) {
// Refresh failed
}
return false;
}
/**
* Get list of enabled features
*/
static getEnabledFeatures(features) {
const featureNames = {
marketplaceAccess: 'ποΈ Marketplace Components',
aiGenerator: 'π€ AI Component Generator',
customAI: 'π§ Bring Your Own AI',
teamCollaboration: 'π₯ Team Collaboration',
customComponents: 'π¨ Custom Component Library',
advancedAnalytics: 'π Advanced Analytics',
prioritySupport: 'π Priority Support',
cloudSync: 'βοΈ Cloud Sync',
versionControl: 'π Version Control Integration',
privateRegistry: 'π Private Component Registry',
whiteLabel: 'π·οΈ White Label Options',
apiAccess: 'π API Access',
ssoIntegration: 'π SSO Integration',
auditLogs: 'π Audit Logs',
unlimitedProjects: 'βΎοΈ Unlimited Projects'
};
return Object.entries(features)
.filter(([_, enabled]) => enabled)
.map(([key]) => featureNames[key])
.filter(Boolean);
}
/**
* Make authenticated API request
*/
static async apiRequest(endpoint, options = {}) {
const auth = await this.getAuth();
if (!auth?.accessToken) {
throw new Error('Not authenticated. Please run "revolutionary-ui login" first.');
}
const headers = {
...options.headers,
'Authorization': `Bearer ${auth.accessToken}`,
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${this.API_BASE}${endpoint}`, {
...options,
headers
});
if (response.status === 401) {
// Try to refresh token
if (auth.refreshToken && await this.refreshAuth(auth.refreshToken)) {
// Retry with new token
const newAuth = await this.getAuth();
headers['Authorization'] = `Bearer ${newAuth?.accessToken}`;
return await fetch(`${this.API_BASE}${endpoint}`, {
...options,
headers
});
}
throw new Error('Authentication expired. Please login again.');
}
return response;
}
catch (error) {
console.error(chalk_1.default.red(`API request failed: ${error}`));
return null;
}
}
}
exports.AuthManager = AuthManager;
//# sourceMappingURL=auth-manager.js.map