Files
PAGIVA/scripts/create-user.mjs
chaloemphong 9d32552457 Initial commit: page-manager Next.js app with Coolify deploy support
Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents
for deployment to Coolify: in-container cron scheduler
(scripts/cron-runner.mjs) and disk-based upload storage served via
/api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health
for container health checks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-22 11:52:17 +07:00

123 lines
4.4 KiB
JavaScript

// Bootstrap and manage login accounts from the command line.
//
// npm run user:create -- --email you@company.com --name "ชื่อ" --role SUPERADMIN
// npm run user:create -- --email you@company.com --password "..." --role MEMBER
// npm run user:list
//
// The password hash format must stay identical to src/lib/auth/password.ts
// ("scrypt:<saltHex>:<hashHex>") — the login route verifies with that module.
import "dotenv/config";
import crypto from "node:crypto";
import { promisify } from "node:util";
import readline from "node:readline/promises";
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const scrypt = promisify(crypto.scrypt);
const KEY_LENGTH = 64;
const MIN_PASSWORD_LENGTH = 10;
const ROLES = ["SUPERADMIN", "MEMBER"]; // GlobalRole — page roles are set in the /users UI
async function hashPassword(password) {
const salt = crypto.randomBytes(16);
const derived = await scrypt(password, salt, KEY_LENGTH);
return `scrypt:${salt.toString("hex")}:${derived.toString("hex")}`;
}
function parseArgs(argv) {
const args = {};
for (let i = 0; i < argv.length; i++) {
if (!argv[i].startsWith("--")) continue;
const key = argv[i].slice(2);
const value = argv[i + 1]?.startsWith("--") ? "true" : argv[++i];
args[key] = value ?? "true";
}
return args;
}
async function prompt(question, { silent = false } = {}) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
if (silent) {
// Suppress echo so the password does not end up on screen or in a scrollback.
rl.output.write(question);
rl._writeToOutput = () => {};
const answer = await new Promise((resolve) => rl.question("", resolve));
rl.output.write("\n");
rl.close();
return answer;
}
const answer = await rl.question(question);
rl.close();
return answer;
}
async function main() {
const [command = "create", ...rest] = process.argv.slice(2);
const args = parseArgs(rest);
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});
try {
if (command === "list") {
const users = await prisma.user.findMany({ orderBy: { createdAt: "asc" } });
if (users.length === 0) {
console.log("ยังไม่มีผู้ใช้ — สร้างแอดมินคนแรกด้วย npm run user:create");
return;
}
for (const u of users) {
console.log(
`${u.isActive ? "●" : "○"} ${u.email.padEnd(32)} ${u.globalRole.padEnd(9)} ${u.name}`
);
}
return;
}
if (command !== "create") {
console.error(`unknown command "${command}" — use "create" or "list"`);
process.exitCode = 1;
return;
}
const email = (args.email ?? (await prompt("อีเมล: "))).trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
throw new Error(`อีเมลไม่ถูกต้อง: ${email}`);
}
const name = (args.name ?? (await prompt("ชื่อที่จะแสดง: "))).trim();
if (!name) throw new Error("ต้องระบุชื่อ");
const role = (args.role ?? (await prompt(`สิทธิ์ (${ROLES.join("/")}): `))).trim().toUpperCase();
if (!ROLES.includes(role)) throw new Error(`role ต้องเป็น ${ROLES.join(", ")}`);
const password = args.password ?? (await prompt("รหัสผ่าน: ", { silent: true }));
if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH) {
throw new Error(`รหัสผ่านต้องยาวอย่างน้อย ${MIN_PASSWORD_LENGTH} ตัวอักษร`);
}
const existing = await prisma.user.findUnique({ where: { email } });
const passwordHash = await hashPassword(password);
if (existing) {
await prisma.user.update({
where: { email },
data: { name, globalRole: role, passwordHash, isActive: true, mustChangePassword: true },
});
console.log(`อัปเดตผู้ใช้ ${email} (${role}) แล้ว`);
} else {
await prisma.user.create({
data: { email, name, globalRole: role, passwordHash, mustChangePassword: true },
});
console.log(`สร้างผู้ใช้ ${email} (${role}) แล้ว`);
}
} finally {
await prisma.$disconnect();
}
}
main().catch((e) => {
console.error(e.message ?? e);
process.exitCode = 1;
});