feat: Admin-Seed automatisch beim Deploy ausfuehren
Backend Image / build-and-push (push) Successful in 2m35s
Frontend Image / build-and-push (push) Successful in 2m46s

Bisher wurde nirgends automatisch ein erster Admin-User angelegt -
prisma/seed.ts existierte, war aber weder im Dockerfile-CMD noch sonst
irgendwo verdrahtet. Auf einer frischen Datenbank haette also niemand
sich einloggen koennen.

- Dockerfile-CMD: migrate:deploy && seed && node dist/main.js
- ts-node/typescript von devDependencies zu dependencies verschoben
  (seed.ts laeuft als rohes TypeScript zur Laufzeit, kein
  Kompilierschritt), tsconfig.json zusaetzlich ins Runtime-Image kopiert
- seed.ts gegen Unique-Constraint-Race bei mehreren gleichzeitig
  startenden Pod-Replicas gehaertet (P2002 abgefangen statt Absturz)
- Login-Banner im Log nur beim tatsaechlichen Erst-Anlegen (URL aus
  FRONTEND_ORIGIN, Benutzername, Passwort) - bewusst nicht bei jedem
  Neustart, sonst wuerden veraltete/geaenderte Zugangsdaten weiter
  geloggt und Credentials landen unnoetig dauerhaft in den Logs

Seed ist bereits idempotent per E-Mail-Check (auch bei deaktivierten
Usern), UsersService.assertNotLastSystemRoleUser verhindert ohnehin
das Deaktivieren des letzten aktiven Admins - kein Aenderungsbedarf
dort, siehe Konversation.

Verifiziert: tsc/eslint clean, 297/297 Tests, Build clean. Migration
und Schema live gegen die lokale DB bestaetigt (ueber WSL direkt, da
Windows->WSL-Portweiterleitung weiterhin kaputt ist); der eigentliche
Seed-Lauf selbst konnte nicht End-to-End gegen die DB verifiziert
werden (gleiches Verbindungsproblem), Banner-Ausgabe isoliert
smoke-getestet.
This commit is contained in:
Nick Szaunig committed 2026-08-27 06:38:23 +02:00
1 parent 62004483cf
commit 05876838b0
6 files changed
+128 -43

No files matched your search

+42 -10
View File
@@ -1,12 +1,27 @@
import 'dotenv/config';
import * as bcrypt from 'bcryptjs';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../generated/prisma';
import { Prisma, PrismaClient } from '../generated/prisma';
const BCRYPT_SALT_ROUNDS = 12;
const DEFAULT_ADMIN_EMAIL = '[email protected]';
const DEFAULT_ADMIN_PASSWORD = 'ChangeMe123!';
// Only printed the moment the account is actually created (first deploy on
// an empty database), never on later restarts: by then the real admin may
// have changed the password via /profile, so repeating it would just be
// stale and would leak credentials into logs indefinitely for no reason.
function printLoginBanner(email: string, password: string): void {
const url = process.env.FRONTEND_ORIGIN ?? 'http://localhost:3000';
const line = '='.repeat(60);
console.log(line);
console.log('Seed: Admin-Zugang eingerichtet.');
console.log(` URL: ${url}`);
console.log(` Benutzer: ${email}`);
console.log(` Passwort: ${password}`);
console.log(line);
}
async function main(): Promise<void> {
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
@@ -25,15 +40,32 @@ async function main(): Promise<void> {
const adminRole = await prisma.role.findUniqueOrThrow({
where: { key: 'ADMIN' },
});
await prisma.user.create({
data: {
email,
passwordHash,
name: 'Administrator',
roleId: adminRole.id,
},
});
console.log(`Seed: created admin user ${email}.`);
try {
await prisma.user.create({
data: {
email,
passwordHash,
name: 'Administrator',
roleId: adminRole.id,
},
});
printLoginBanner(email, password);
} catch (error: unknown) {
// P2002 = unique constraint violation on email: another replica's
// startup won this race between the existence check above and this
// create() call. The user now exists either way, so this is a no-op,
// not a failure - container startup must not crash on it.
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2002'
) {
console.log(
`Seed: admin user ${email} was created concurrently, skipping.`,
);
} else {
throw error;
}
}
await prisma.$disconnect();
}