Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions adminforth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import jwt from 'jsonwebtoken';
import crypto from 'crypto';
import AdminForth from './index.js';
import { IAdminForthAuth } from './types/Back.js';
import { afLogger } from './modules/logger.js';

// Function to generate a password hash using PBKDF2
function calcPasswordHash(password, salt, iterations = 100000, keyLength = 64, digest = 'sha512') {
Expand Down Expand Up @@ -105,7 +106,7 @@ class AdminForthAuth implements IAdminForthAuth {
if (expirySeconds !== undefined) {
expiryMs = expirySeconds * 1000;
} else if (expiry !== undefined) {
console.warn('setCustomCookie: expiry(in ms) is deprecated, use expirySeconds instead (seconds), traceback:', new Error().stack);
afLogger.warn(`setCustomCookie: expiry(in ms) is deprecated, use expirySeconds instead (seconds), traceback: ${new Error().stack}`);
expiryMs = expiry;
}

Expand Down Expand Up @@ -145,23 +146,23 @@ class AdminForthAuth implements IAdminForthAuth {
decoded = jwt.verify(jwtToken, secret);
} catch (err) {
if (err.name === 'TokenExpiredError') {
console.error('Token expired:', err.message);
afLogger.error(`Token expired: ${err.message}`);
} else if (err.name === 'JsonWebTokenError') {
console.error('Token error:', err.message);
afLogger.error(`Token error: ${err.message}`);
} else {
console.error('Failed to verify JWT token', err);
afLogger.error(`Failed to verify JWT token: ${err}`);
}
return null;
}
const { pk, t } = decoded;
if (t !== mustHaveType) {
console.error(`Invalid token type during verification: ${t}, must be ${mustHaveType}`);
afLogger.error(`Invalid token type during verification: ${t}, must be ${mustHaveType}`);
return null;
}
if (decodeUser !== false) {
const dbUser = await this.adminforth.getUserByPk(pk);
if (!dbUser) {
console.error(`User with pk ${pk} not found in database`);
afLogger.error(`User with pk ${pk} not found in database`);
// will logout user which was deleted
return null;
}
Expand Down
6 changes: 4 additions & 2 deletions adminforth/basePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import fs from 'fs';

import crypto from 'crypto';

import { afLogger } from './modules/logger.js';


export default class AdminForthPlugin implements IAdminForthPlugin {

Expand All @@ -24,7 +26,7 @@ export default class AdminForthPlugin implements IAdminForthPlugin {
this.pluginDir = currentFileDir(metaUrl);
this.customFolderPath = path.join(this.pluginDir, this.customFolderName);
this.pluginOptions = pluginOptions;
process.env.HEAVY_DEBUG && console.log(`🪲 🪲 AdminForthPlugin.constructor`, this.constructor.name);
afLogger.trace(`🪲 🪲 AdminForthPlugin.constructor ${this.constructor.name}`);
this.className = this.constructor.name;
}

Expand All @@ -42,7 +44,7 @@ export default class AdminForthPlugin implements IAdminForthPlugin {

const seed = `af_pl_${this.constructor.name}_${resourceConfig.resourceId}_${uniqueness}`;
this.pluginInstanceId = md5hash(seed);
process.env.HEAVY_DEBUG && console.log(`🪲 AdminForthPlugin.modifyResourceConfig`, seed, 'id', this.pluginInstanceId);
afLogger.trace(`🪲 AdminForthPlugin.modifyResourceConfig, ${seed}, 'id', ${this.pluginInstanceId}`);
this.adminforth = adminforth;
}

Expand Down
5 changes: 3 additions & 2 deletions adminforth/commands/bundle.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { callTsProxy, findAdminInstance } from "./callTsProxy.js";
import { afLogger } from '../modules/logger.js';


async function bundle() {
console.log("Bundling admin SPA...");
afLogger.info("Bundling admin SPA...");
const instance = await findAdminInstance();


Expand All @@ -16,7 +17,7 @@ async function bundle() {
`);

} catch (e) {
console.log(`Running budndle failed`, e);
afLogger.error(`Running bundle failed`, e);
}
}

Expand Down
19 changes: 10 additions & 9 deletions adminforth/commands/callTsProxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from "path";
import fs from "fs";
import chalk from "chalk";
import dotenv from "dotenv";
import { afLogger } from './modules/logger.js';
Comment thread
yaroslav8765 marked this conversation as resolved.
Outdated

const currentFilePath = import.meta.url;
const currentFileFolder = path.dirname(currentFilePath).replace("file:", "");
Expand All @@ -20,7 +21,7 @@ export function callTsProxy(tsCode, silent=false) {
dotenv.config({ path: envPath, override: true });
}

process.env.HEAVY_DEBUG && console.log("🌐 Calling tsproxy with code:", path.join(currentFileFolder, "proxy.ts"));
afLogger.trace("🌐 Calling tsproxy with code:", path.join(currentFileFolder, "proxy.ts"));
return new Promise((resolve, reject) => {
const child = spawn("tsx", [path.join(currentFileFolder, "proxy.ts")], {
env: process.env,
Expand All @@ -42,7 +43,7 @@ export function callTsProxy(tsCode, silent=false) {
const parsed = JSON.parse(stdout);
if (!silent) {
parsed.capturedLogs.forEach((log) => {
console.log(...log);
afLogger.info(...log);
});
}

Expand All @@ -54,19 +55,19 @@ export function callTsProxy(tsCode, silent=false) {
reject(new Error("Invalid JSON from tsproxy: " + stdout));
}
} else {
console.error(`tsproxy exited with non-0, this should never happen, stdout: ${stdout}, stderr: ${stderr}`);
afLogger.error(`tsproxy exited with non-0, this should never happen, stdout: ${stdout}, stderr: ${stderr}`);
reject(new Error(stderr));
}
});

process.env.HEAVY_DEBUG && console.log("🪲 Writing to tsproxy stdin...\n'''", tsCode, "'''");
afLogger.trace("🪲 Writing to tsproxy stdin...\n'''", tsCode, "'''");
child.stdin.write(tsCode);
child.stdin.end();
});
}

export async function findAdminInstance() {
process.env.HEAVY_DEBUG && console.log("🌐 Finding admin instance...");
afLogger.trace("🌐 Finding admin instance...");
const currentDirectory = process.cwd();

let files = fs.readdirSync(currentDirectory);
Expand All @@ -83,7 +84,7 @@ export async function findAdminInstance() {
for (const file of files) {
if (file.endsWith(".ts")) {
const fileNoTs = file.replace(/\.ts$/, "");
process.env.HEAVY_DEBUG && console.log(`🪲 Trying bundleing ${file}...`);
afLogger.trace(`🪲 Trying bundleing ${file}...`);
try {
const res = await callTsProxy(`
import { admin } from './${fileNoTs}.js';
Expand All @@ -101,10 +102,10 @@ export async function findAdminInstance() {
// and show the error so user can fix it
const fileContent = fs.readFileSync(file, "utf-8");
if (fileContent.includes("export const admin")) {
console.error(chalk.red(`Error running ${file}:`, e));
afLogger.error(`Error running ${file}: ${e}`);
process.exit(1);
}
process.env.HEAVY_DEBUG && console.log(`🪲 File ${file} failed`, e);
afLogger.trace(`🪲 File ${file} failed`, e);
}
}
}
Expand All @@ -130,4 +131,4 @@ export async function findAdminInstance() {
// function exec() {
// return admin.doX();
// }
// `).then(console.log).catch(console.error);
// `).then(afLogger.info).catch(afLogger.error);
3 changes: 2 additions & 1 deletion adminforth/commands/createApp/templates/adminuser.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import AdminForth, { AdminForthDataTypes } from 'adminforth';
import type { AdminForthResourceInput, AdminForthResource, AdminUser } from 'adminforth';
import { logger } from 'adminforth';
import { randomUUID } from 'crypto';

async function allowedForSuperAdmin({ adminUser }: { adminUser: AdminUser }): Promise<boolean> {
Expand Down Expand Up @@ -94,7 +95,7 @@ export default {
},
edit: {
beforeSave: async ({ oldRecord, updates, adminUser, resource }: { oldRecord: any, updates: any, adminUser: AdminUser, resource: AdminForthResource }) => {
console.log('Updating user', updates);
logger.info('Updating user', updates);
if (oldRecord.id === adminUser.dbUser.id && updates.role) {
return { ok: false, error: 'You cannot change your own role' };
}
Expand Down
6 changes: 3 additions & 3 deletions adminforth/commands/createApp/templates/index.ts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import AdminForth from 'adminforth';
import usersResource from "./resources/adminuser.js";
import { fileURLToPath } from 'url';
import path from 'path';
import { Filters } from 'adminforth';
import { Filters, logger } from 'adminforth';
import { initApi } from './api.js';

const ADMIN_BASE_URL = '';
Expand Down Expand Up @@ -75,7 +75,7 @@ if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
const port = 3500;

admin.bundleNow({ hotReload: process.env.NODE_ENV === 'development' }).then(() => {
console.log('Bundling AdminForth SPA done.');
logger.info('Bundling AdminForth SPA done.');
});

admin.express.serve(app);
Expand All @@ -91,6 +91,6 @@ if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
});

admin.express.listen(port, () => {
console.log(`\n⚡ AdminForth is available at http://localhost:${port}${ADMIN_BASE_URL}\n`);
logger.info(`\n⚡ AdminForth is available at http://localhost:${port}${ADMIN_BASE_URL}\n`);
});
}
8 changes: 4 additions & 4 deletions adminforth/commands/createApp/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { exec } from 'child_process';
import Handlebars from 'handlebars';
import { promisify } from 'util';
import { getVersion } from '../cli.js';
import { afLogger } from '../modules/logger.js';
Comment thread
yaroslav8765 marked this conversation as resolved.
Outdated

const execAsync = promisify(exec);

Expand Down Expand Up @@ -335,7 +336,6 @@ async function installDependencies(ctx, cwd) {
await execAsync(`${nodeBinary} ${npmPath} install`, { cwd: customDir, env: { PATH: process.env.PATH } }),
]);
}
// console.log(chalk.dim(`Dependencies installed in ${cwd} and ${customDir}: \n${res[0].stdout}${res[1].stdout}`));
}

function generateFinalInstructions(skipPrismaSetup, options) {
Expand Down Expand Up @@ -390,9 +390,9 @@ export function prepareWorkflow(options) {
{
title: '📝 Preparing final instructions...',
task: (ctx) => {
console.log(chalk.green(`✅ Successfully created your new Adminforth project in ${ctx.projectDir}!\n`));
console.log(generateFinalInstructions(ctx.skipPrismaSetup, options));
console.log('\n\n');
afLogger.info(chalk.green(`✅ Successfully created your new Adminforth project in ${ctx.projectDir}!\n`));
afLogger.info(generateFinalInstructions(ctx.skipPrismaSetup, options));
afLogger.info('\n\n');
}
}
],
Expand Down
7 changes: 4 additions & 3 deletions adminforth/commands/createCustomComponent/configLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'path';
import chalk from 'chalk';
import jiti from 'jiti';
import dotenv, { config } from "dotenv";
import { afLogger } from '../modules/logger.js';
Comment thread
yaroslav8765 marked this conversation as resolved.
Outdated

dotenv.config({ path: '.env.local', override: true });
dotenv.config({ path: '.env', override: true });
Expand Down Expand Up @@ -59,12 +60,12 @@ export async function loadAdminForthConfig() {
}


console.log(chalk.dim(`Loaded configuration from ${configPath}`));
afLogger.info(chalk.dim(`Loaded configuration from ${configPath}`));
return config;

} catch (error) {
console.error(chalk.red(`\nError loading or parsing configuration file: ${configPath}, error: ${error}`));
console.error(error);
afLogger.error(chalk.red(`\nError loading or parsing configuration file: ${configPath}, error: ${error}`));
afLogger.error(error);
process.exit(1);
}
}
Loading
Loading