import SQL from 'sql-template-strings'; import { ulid } from 'ulid'; import './dotenv.ts'; import dbConnection from './db.ts'; import { env } from './env.ts'; import jwt from './jwt.ts'; // This module creates a test user in the database with the username "admin" // that has the "*" role. It also creates an authentication token for the user, // and returns the token. This token can be used to authenticate as the admin // user in tests. // This module should never be used in production code. It is only for testing // purposes. const __dirname = new URL('.', import.meta.url).pathname; if (env !== 'development') { throw new Error('This script should only be run in development mode'); } /** * Runs the migrations in the migrations directory. */ async function migrate(): Promise { const db = await dbConnection(); await db.migrate({ migrationsPath: `${__dirname}/../migrations` }); await db.close(); } /** * Creates a test database with a test user named "admin" with the role "*". * Creates an authentication token and prints it to stdout. */ async function initTestDatabase(): Promise { const db = await dbConnection(); await db.get(SQL` INSERT OR IGNORE INTO users (id, username, usernameNorm, email, roles, avatarSource, lastActive) VALUES ( ${ulid()}, 'admin', 'admin', 'admin@example.com', '*', null, strftime('%s','now')*1000 ) `); const adminId = (await db.get(SQL` SELECT id FROM users WHERE username = 'admin' `))?.id; if (typeof adminId !== 'string') { throw new Error('Admin user not created'); } const adminUser = { id: adminId, username: 'admin', email: 'admin@example.com', roles: '*', authenticated: true, }; const token = await jwt.sign('_', adminUser, '3650d', process.env.NUXT_PUBLIC_DOMAIN_BASE ?? ''); await db.close(); return token; } await migrate(); const token = await initTestDatabase(); console.log(token);