From af56ccccde7dae330a115ef73501b683265ad63d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergio=20Go=CC=81mez=20Bachiller?= Date: Thu, 7 Mar 2024 10:26:28 +0100 Subject: [PATCH] feat: add cli command to create admins --- package.json | 3 +- .../user/infrastructure/cli/add-user.cli.ts | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/core/user/infrastructure/cli/add-user.cli.ts diff --git a/package.json b/package.json index e81c5dd..a3edbe3 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,8 @@ "storybook": "storybook dev -p 6006", "build-storybook": "storybook build", "prisma:migrate": "prisma migrate dev", - "prisma:generate": "prisma generate" + "prisma:generate": "prisma generate", + "cli:user:admin": "npx tsx src/core/user/infrastructure/cli/add-user.cli.ts" }, "dependencies": { "@aulasoftwarelibre/next-auth-firewall": "1.2.0", diff --git a/src/core/user/infrastructure/cli/add-user.cli.ts b/src/core/user/infrastructure/cli/add-user.cli.ts new file mode 100644 index 0000000..9de7c9c --- /dev/null +++ b/src/core/user/infrastructure/cli/add-user.cli.ts @@ -0,0 +1,44 @@ +#!/usr/bin/env node +import 'dotenv/config' + +import { ulid } from 'ulid' + +import UserDataMapper from '@/core/user/infrastructure/persistence/user.data-mapper' +import prisma from '@/lib/prisma/prisma' +import gravatar from '@/lib/utils/gravatar' + +async function main() { + console.info('Creating admin...') + + if (process.argv.length !== 4 || !process.argv[2] || !process.argv[3]) { + console.error(`Error: missing parameters.`) + console.error(`Usage: npm cli:user:admin "Full name" "email"`) + + process.exit(1) + } + + const name = process.argv[2] || '' + const email = process.argv[3] || '' + + const user = UserDataMapper.toModel({ + email, + id: ulid().toLowerCase(), + image: gravatar(email), + name, + roles: ['ROLE_USER', 'ROLE_ADMIN'], + version: 0, + }) + + await prisma.user.create({ + data: { + ...UserDataMapper.toPrisma(user), + emailVerified: new Date(), + }, + }) +} + +main() + .then(() => console.info('Done')) + .catch((error) => console.error(error)) + // eslint-disable-next-line unicorn/prefer-top-level-await + .finally(() => prisma.$disconnect())