feat(passenger-api): integrate @tria-plc IAM package (dual-ORM iam schema + package auth guard)

This commit is contained in:
Abubeker Yasin
2026-06-02 09:30:46 +03:00
parent 5059a1fe58
commit 092199f536
18 changed files with 2886 additions and 467 deletions

View File

@@ -0,0 +1,46 @@
/**
* Dev helper: run the @tria-plc/iamapi-common TypeORM migrations against the shared `iam` schema.
*
* The package ships its migration CLI assuming you run it from inside the package repo (it needs
* the package's devDeps). As a consumer we instead drive the shipped (compiled) migrations with the
* passenger app's own installed TypeORM.
*
* Reads the same DATABASE_* env vars as the app's IAM DataSource (see config/iam-database.config.ts).
* Run via: pnpm --filter @edr/passenger-api iam:migrate
* (the npm script loads .env with `node --env-file`).
*
* NOTE: in production the central IAM team owns/runs these migrations — this helper is for local dev.
*/
const path = require('path');
const { DataSource } = require('typeorm');
const iamDist = path
.dirname(require.resolve('@tria-plc/iamapi-common'))
.replace(/\\/g, '/');
const ds = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT || 5432),
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
schema: process.env.DATABASE_SCHEMA || 'iam',
entities: [], // migrations are raw SQL — no entities needed to run them
migrations: [`${iamDist}/db/migrations/*.js`],
migrationsTableName: 'typeorm_migrations',
});
(async () => {
await ds.initialize();
// The IAM migrations rely on uuid_generate_v4() but never CREATE the extension themselves.
await ds.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
const applied = await ds.runMigrations({ transaction: 'each' });
console.log(`[iam-migrations] applied ${applied.length} migration(s)`);
applied.slice(-5).forEach((m) => console.log(' +', m.name));
await ds.destroy();
console.log('[iam-migrations] DONE');
})().catch((e) => {
console.error('[iam-migrations] FAIL:', e.message);
process.exit(1);
});

View File

@@ -0,0 +1,74 @@
/**
* Dev helper: create a dev IAM user + an ACTIVE session, and print a ready-to-use Bearer token.
*
* Why this exists: in prod the central IAM service issues tokens (via password login at
* /v1/auth/login). For local dev of the passenger API (a token *consumer*), this seeds a session
* directly and mints a matching token with the package's own `generateToken`, so you can call
* protected routes immediately (paste the token into Swagger's Authorize box or `curl -H`).
*
* Run: pnpm --filter @edr/passenger-api iam:seed-dev-user
* Reads DATABASE_* + JWT_ACCESS_TOKEN_SECRET/EXPIRES from .env (loaded via `node --env-file`).
*/
const crypto = require('crypto');
const { DataSource } = require('typeorm');
const { generateToken } = require('@tria-plc/api-common/utils/token');
const DEV_EMAIL = process.env.DEV_IAM_EMAIL || 'dev@edr.local';
const ds = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT || 5432),
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
});
(async () => {
await ds.initialize();
// Upsert the dev user (users.email is UNIQUE).
const name = { en: 'Dev User', am: 'የሙከራ ተጠቃሚ' };
const [user] = await ds.query(
`INSERT INTO iam.users (name, username, email, user_type, status, is_active)
VALUES ($1::jsonb, $2, $3, 'individual', 'accepted', true)
ON CONFLICT (email) DO UPDATE SET updated_at = now()
RETURNING id`,
[JSON.stringify(name), 'dev-user', DEV_EMAIL],
);
const userId = user.id;
// Fresh ACTIVE session; userInfo is the denormalized TCurrentUser the guard puts on req.user.
const sessionId = crypto.randomUUID();
const userInfo = {
id: userId,
email: DEV_EMAIL,
name,
username: 'dev-user',
userType: 'individual',
status: 'accepted',
roles: [],
permissions: [],
};
await ds.query(
`INSERT INTO iam.sessions (id, email, device, "userInfo", user_id, status, expiry_time)
VALUES ($1, $2, 'dev-seeder', $3::jsonb, $4, 'ACTIVE', now() + interval '7 days')`,
[sessionId, DEV_EMAIL, JSON.stringify(userInfo), userId],
);
// The package JwtGuard looks up the session by the token's `id` claim.
const token = generateToken({ id: sessionId });
console.log('\n=== IAM dev user seeded ===');
console.log('user id :', userId);
console.log('email :', DEV_EMAIL);
console.log('session id:', sessionId);
console.log('\nBearer token (valid 7 days):\n' + token);
console.log('\nTry it: curl -H "Authorization: Bearer <token>" http://localhost:3002/v1/auth/me');
console.log('(Run again any time for a fresh token/session.)\n');
await ds.destroy();
})().catch((e) => {
console.error('[seed-iam-dev-user] FAIL:', e.message);
process.exit(1);
});