feat: Add authentication and session management with NextAuth.js and Prisma [broken]

- Implemented API session retrieval in `lib/api-auth.ts` to manage user sessions.
- Created authentication options in `lib/auth-options.ts` using NextAuth.js with credentials provider.
- Added migration scripts to create necessary tables for authentication in `migrations/0002_create_auth_tables.sql` and `prisma/migrations/20250601033219_add_nextauth_tables/migration.sql`.
- Configured ESLint with Next.js and TypeScript support in `eslint.config.mjs`.
- Updated Next.js configuration in `next.config.ts` for Cloudflare compatibility.
- Defined Cloudflare Worker configuration in `open-next.config.ts` and `wrangler.jsonc`.
- Enhanced type definitions for authentication in `types/auth.d.ts`.
- Created a Cloudflare Worker entry point in `src/index.ts.backup` to handle API requests and responses.
This commit is contained in:
2025-06-01 16:34:54 +02:00
parent 71c8aff125
commit bde0b44ea0
53 changed files with 20841 additions and 6435 deletions

View File

@ -1,7 +1,7 @@
#!/usr/bin/env node
/**
* Comprehensive D1 Database Management Script
*
*
* Usage Examples:
* node scripts/d1-manager.js tables
* node scripts/d1-manager.js schema Company
@ -11,27 +11,27 @@
* node scripts/d1-manager.js --remote query "SELECT COUNT(*) FROM Session"
*/
import { execSync } from 'child_process';
import { writeFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { execSync } from "child_process";
import { writeFileSync, mkdirSync } from "fs";
import { join } from "path";
const DB_NAME = 'd1-notso-livedash';
const DB_NAME = "d1-notso-livedash";
const args = process.argv.slice(2);
// Parse flags
const isRemote = args.includes('--remote');
const filteredArgs = args.filter(arg => !arg.startsWith('--'));
const isRemote = args.includes("--remote");
const filteredArgs = args.filter((arg) => !arg.startsWith("--"));
if (filteredArgs.length === 0) {
showHelp();
process.exit(1);
showHelp();
process.exit(1);
}
const command = filteredArgs[ 0 ];
const command = filteredArgs[0];
const params = filteredArgs.slice(1);
function showHelp() {
console.log(`
console.log(`
🗄️ D1 Database Manager for ${DB_NAME}
Usage: node scripts/d1-manager.js [--remote] <command> [params...]
@ -60,125 +60,134 @@ Examples:
}
function execute(sql, silent = false) {
const remoteFlag = isRemote ? '--remote' : '';
const cmd = `npx wrangler d1 execute ${DB_NAME} ${remoteFlag} --command "${sql}"`;
const remoteFlag = isRemote ? "--remote" : "";
const cmd = `npx wrangler d1 execute ${DB_NAME} ${remoteFlag} --command "${sql}"`;
if (!silent) {
console.log(`🔍 Executing${isRemote ? ' (remote)' : ' (local)'}: ${sql}\\n`);
}
if (!silent) {
console.log(
`🔍 Executing${isRemote ? " (remote)" : " (local)"}: ${sql}\\n`
);
}
try {
return execSync(cmd, { encoding: 'utf8' });
} catch (error) {
console.error('❌ Query failed:', error.message);
process.exit(1);
}
try {
return execSync(cmd, { encoding: "utf8" });
} catch (error) {
console.error("❌ Query failed:", error.message);
process.exit(1);
}
}
function wranglerCommand(subcommand, silent = false) {
const remoteFlag = isRemote ? '--remote' : '';
const cmd = `npx wrangler d1 ${subcommand} ${DB_NAME} ${remoteFlag}`;
const remoteFlag = isRemote ? "--remote" : "";
const cmd = `npx wrangler d1 ${subcommand} ${DB_NAME} ${remoteFlag}`;
if (!silent) {
console.log(`📊 Running: ${cmd}\\n`);
}
if (!silent) {
console.log(`📊 Running: ${cmd}\\n`);
}
try {
return execSync(cmd, { stdio: 'inherit' });
} catch (error) {
console.error('❌ Command failed:', error.message);
process.exit(1);
}
try {
return execSync(cmd, { stdio: "inherit" });
} catch (error) {
console.error("❌ Command failed:", error.message);
process.exit(1);
}
}
switch (command) {
case 'info':
wranglerCommand('info');
break;
case "info":
wranglerCommand("info");
break;
case 'tables':
console.log('📋 Listing all tables:\\n');
execute("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name;");
break;
case "tables":
console.log("📋 Listing all tables:\\n");
execute(
"SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name;"
);
break;
case 'schema':
if (!params[ 0 ]) {
console.error('❌ Please specify a table name');
console.log('Usage: node scripts/d1-manager.js schema <table_name>');
process.exit(1);
}
console.log(`🏗️ Schema for table '${params[ 0 ]}':\\n`);
execute(`PRAGMA table_info(${params[ 0 ]});`);
break;
case "schema":
if (!params[0]) {
console.error("❌ Please specify a table name");
console.log("Usage: node scripts/d1-manager.js schema <table_name>");
process.exit(1);
}
console.log(`🏗️ Schema for table '${params[0]}':\\n`);
execute(`PRAGMA table_info(${params[0]});`);
break;
case 'count':
if (!params[ 0 ]) {
console.error('❌ Please specify a table name');
console.log('Usage: node scripts/d1-manager.js count <table_name>');
process.exit(1);
}
console.log(`🔢 Row count for table '${params[ 0 ]}':\\n`);
execute(`SELECT COUNT(*) as row_count FROM ${params[ 0 ]};`);
break;
case "count":
if (!params[0]) {
console.error("❌ Please specify a table name");
console.log("Usage: node scripts/d1-manager.js count <table_name>");
process.exit(1);
}
console.log(`🔢 Row count for table '${params[0]}':\\n`);
execute(`SELECT COUNT(*) as row_count FROM ${params[0]};`);
break;
case 'query':
if (!params[ 0 ]) {
console.error('❌ Please specify a SQL query');
console.log('Usage: node scripts/d1-manager.js query "SELECT * FROM table"');
process.exit(1);
}
execute(params[ 0 ]);
break;
case "query":
if (!params[0]) {
console.error("❌ Please specify a SQL query");
console.log(
'Usage: node scripts/d1-manager.js query "SELECT * FROM table"'
);
process.exit(1);
}
execute(params[0]);
break;
case 'backup':
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const filename = params[ 0 ] || `backup_${timestamp}.sql`;
case "backup":
const timestamp = new Date()
.toISOString()
.replace(/[:.]/g, "-")
.slice(0, 19);
const filename = params[0] || `backup_${timestamp}.sql`;
try {
mkdirSync('backups', { recursive: true });
} catch (e) {
// Directory might already exist
}
try {
mkdirSync("backups", { recursive: true });
} catch (e) {
// Directory might already exist
}
const backupPath = join('backups', filename);
console.log(`💾 Creating backup: ${backupPath}\\n`);
wranglerCommand(`export --output ${backupPath}`);
console.log(`\\n✅ Backup created successfully: ${backupPath}`);
break;
const backupPath = join("backups", filename);
console.log(`💾 Creating backup: ${backupPath}\\n`);
wranglerCommand(`export --output ${backupPath}`);
console.log(`\\n✅ Backup created successfully: ${backupPath}`);
break;
case 'backup-schema':
try {
mkdirSync('backups', { recursive: true });
} catch (e) {
// Directory might already exist
}
case "backup-schema":
try {
mkdirSync("backups", { recursive: true });
} catch (e) {
// Directory might already exist
}
console.log('📜 Exporting schema only...\\n');
wranglerCommand('export --no-data --output backups/schema.sql');
console.log('\\n✅ Schema exported to backups/schema.sql');
break;
console.log("📜 Exporting schema only...\\n");
wranglerCommand("export --no-data --output backups/schema.sql");
console.log("\\n✅ Schema exported to backups/schema.sql");
break;
case 'recent-logs':
console.log('📊 Recent database activity:\\n');
try {
wranglerCommand('insights');
} catch (error) {
console.log(' Insights not available for this database');
}
break;
case "recent-logs":
console.log("📊 Recent database activity:\\n");
try {
wranglerCommand("insights");
} catch (error) {
console.log(" Insights not available for this database");
}
break;
case 'all-tables-info':
console.log('📊 Information about all tables:\\n');
const tables = [ 'Company', 'User', 'Session' ];
for (const table of tables) {
console.log(`\\n🏷 Table: ${table}`);
console.log('─'.repeat(50));
execute(`SELECT COUNT(*) as row_count FROM ${table};`);
}
break;
case "all-tables-info":
console.log("📊 Information about all tables:\\n");
const tables = ["Company", "User", "Session"];
for (const table of tables) {
console.log(`\\n🏷 Table: ${table}`);
console.log("─".repeat(50));
execute(`SELECT COUNT(*) as row_count FROM ${table};`);
}
break;
default:
console.error(`❌ Unknown command: ${command}`);
showHelp();
process.exit(1);
default:
console.error(`❌ Unknown command: ${command}`);
showHelp();
process.exit(1);
}