manicanldes-backend/src/identity/bootstrap.service.ts

61 lines
1.9 KiB
TypeScript

import { AppError } from '../common/errors/app-error';
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { PasswordService } from './password.service';
import { PERMISSIONS } from './permissions';
import { recordAudit } from './audit';
import type { CreateUserInput } from './identity.schemas';
@Injectable()
export class BootstrapService {
constructor(
private readonly db: DatabaseService,
private readonly passwords: PasswordService,
) {}
async createOwner(organizationName: string, input: CreateUserInput) {
const passwordHash = await this.passwords.hash(input.password);
return this.db.$transaction(async (tx) => {
// One-time installation bootstrap, serialized across processes.
await tx.$queryRaw`SELECT pg_advisory_xact_lock(74192001)::text`;
if (await tx.user.count({ where: { isOwner: true } }))
throw new AppError('OWNER_EXISTS');
const organization = await tx.organization.create({
data: { name: organizationName },
});
const role = await tx.role.create({
data: {
organizationId: organization.id,
name: 'Owner',
isSystem: true,
permissions: [...PERMISSIONS],
},
});
const user = await tx.user.create({
data: {
organizationId: organization.id,
email: input.email,
name: input.name,
passwordHash,
isOwner: true,
status: 'ACTIVE',
},
});
await tx.userRole.create({
data: {
userId: user.id,
roleId: role.id,
organizationId: organization.id,
},
});
await recordAudit(
tx,
organization.id,
user.id,
'installation.bootstrapped',
user.id,
);
return { organizationId: organization.id, userId: user.id };
});
}
}