Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
59 lines
2.2 KiB
TypeScript
59 lines
2.2 KiB
TypeScript
/**
|
|
* Bootstraps an organization and its first owner. Run once per environment:
|
|
* pnpm --filter @photoreport/api create-owner -- --org-slug photoreport --org-name "PhotoReport" \
|
|
* --email [email protected] --name "Your Name"
|
|
* The password is read from the PHOTOREPORT_OWNER_PASSWORD environment variable, never from argv.
|
|
*/
|
|
import { parseArgs } from "node:util";
|
|
import { hashPassword, MIN_PASSWORD_LENGTH } from "../src/auth/passwords.js";
|
|
import { loadConfig } from "../src/config.js";
|
|
import { createDb } from "../src/db.js";
|
|
|
|
const { values } = parseArgs({
|
|
options: {
|
|
"org-slug": { type: "string" },
|
|
"org-name": { type: "string" },
|
|
"org-mode": { type: "string", default: "AGENCY" },
|
|
email: { type: "string" },
|
|
name: { type: "string" },
|
|
},
|
|
});
|
|
|
|
const password = process.env.PHOTOREPORT_OWNER_PASSWORD ?? "";
|
|
const slug = values["org-slug"];
|
|
const orgName = values["org-name"];
|
|
const email = values.email?.trim().toLowerCase();
|
|
const name = values.name;
|
|
const mode = values["org-mode"] === "INDEPENDENT" ? "INDEPENDENT" : "AGENCY";
|
|
|
|
if (!slug || !orgName || !email || !name) {
|
|
console.error("Missing --org-slug, --org-name, --email or --name");
|
|
process.exit(1);
|
|
}
|
|
if (password.length < MIN_PASSWORD_LENGTH) {
|
|
console.error(`Set PHOTOREPORT_OWNER_PASSWORD (at least ${MIN_PASSWORD_LENGTH} characters)`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const db = createDb(loadConfig().DATABASE_URL);
|
|
try {
|
|
const passwordHash = await hashPassword(password);
|
|
const result = await db.$transaction(async (tx) => {
|
|
const user =
|
|
(await tx.user.findUnique({ where: { email } })) ??
|
|
(await tx.user.create({ data: { email, name, passwordHash, preferences: { create: {} } } }));
|
|
const org =
|
|
(await tx.organization.findUnique({ where: { slug } })) ??
|
|
(await tx.organization.create({ data: { slug, name: orgName, mode } }));
|
|
await tx.membership.upsert({
|
|
where: { userId_organizationId: { userId: user.id, organizationId: org.id } },
|
|
create: { userId: user.id, organizationId: org.id, role: "OWNER" },
|
|
update: { role: "OWNER" },
|
|
});
|
|
return { userId: user.id, organizationId: org.id };
|
|
});
|
|
console.log(JSON.stringify(result));
|
|
} finally {
|
|
await db.$disconnect();
|
|
}
|