freshyo/apps/backend/scripts/create-user.ts
2026-10-13 19:10:27 +05:30

174 lines
6.4 KiB
TypeScript

#!/usr/bin/env bun
/**
* create-user — create a Freshyo user (or reset its password).
*
* Writes to the D1 database through `wrangler d1 execute`, so the same script
* works against the local dev DB (default) and the remote DB (--remote).
* Passwords are bcrypt-hashed (12 rounds) exactly like the signup flow.
*
* Run from apps/backend:
*
* bun run create-user -- \
* --mobile 9990001111 --password "secret123" \
* --name "Test User" --email test@freshyo.in
*
* Flags:
* --name <string> display name (optional)
* --email <string> email; at least one of --email/--mobile is required
* --mobile <string> mobile; at least one of --email/--mobile is required
* --password <string> plaintext password (required)
* --update if the user already exists, (re)set its password
* --remote target the remote D1 instead of the local one
* --show-sql print the SQL and exit (no write)
* --help show this help
*
* Env overrides:
* D1_CONFIG wrangler config file (default: wrangler.dev.toml, or
* wrangler.prod.toml when --remote)
* D1_DB_NAME D1 database name (default: freshyo-dev)
*/
import bcrypt from 'bcryptjs'
import { resolve } from 'node:path'
import { existsSync } from 'node:fs'
const USAGE = `create-user — create a Freshyo user (or reset its password)
Usage:
bun run create-user -- --mobile <m> --password <p> [--name <n>] [--email <e>] [--update] [--remote]
Options:
--name display name (optional)
--email email (one of --email/--mobile required)
--mobile mobile (one of --email/--mobile required)
--password plaintext password (required)
--update if the user already exists, (re)set its password
--remote use the remote D1 (default: local)
--show-sql print the SQL instead of running it
--help show this help
`
const argv = process.argv.slice(2)
const flag = (n: string) => argv.includes(`--${n}`)
const opt = (n: string): string | undefined => {
const eq = argv.find((a) => a.startsWith(`--${n}=`))
if (eq) return eq.slice(n.length + 3)
const i = argv.indexOf(`--${n}`)
if (i !== -1 && argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) return argv[i + 1]
return undefined
}
function die(msg: string): never {
console.error(`\n error: ${msg}\n`)
console.error(USAGE)
process.exit(1)
}
if (flag('help') || flag('h') || argv.length === 0) {
console.log(USAGE)
process.exit(0)
}
const name = opt('name')?.trim() ?? null
const email = opt('email')?.trim() ?? null
const mobile = opt('mobile')?.trim() ?? null
const password = opt('password')
const update = flag('update')
const remote = flag('remote')
const showSql = flag('show-sql')
if (!password) die('--password is required')
if (!email && !mobile) die('at least one of --email / --mobile is required')
const BACKEND_DIR = resolve(import.meta.dir, '..')
const config = process.env.D1_CONFIG ?? (remote ? 'wrangler.prod.toml' : 'wrangler.dev.toml')
const dbName = process.env.D1_DB_NAME ?? 'freshyo-dev'
const WRANGLER = resolve(BACKEND_DIR, 'node_modules/.bin/wrangler')
function run(args: string[]): { out: string; err: string; code: number } {
const p = Bun.spawnSync([existsSync(WRANGLER) ? WRANGLER : 'wrangler', ...args], {
cwd: BACKEND_DIR,
stdout: 'pipe',
stderr: 'pipe',
})
return { out: p.stdout.toString(), err: p.stderr.toString(), code: p.exitCode }
}
function parseJson(out: string): any[] | null {
const s = out.indexOf('[')
const e = out.lastIndexOf(']')
if (s === -1 || e === -1) return null
try {
return JSON.parse(out.slice(s, e + 1))
} catch {
return null
}
}
const q = (s: string) => `'${s.replace(/'/g, "''")}'`
const lit = (s: string | null) => (s === null ? 'NULL' : q(s))
// Match clause: find the user by mobile and/or (case-insensitive) email.
const matchParts: string[] = []
if (mobile) matchParts.push(`mobile = ${q(mobile)}`)
if (email) matchParts.push(`lower(email) = lower(${q(email)})`)
const match = matchParts.join(' OR ')
const targetArgs = ['d1', 'execute', dbName, '--config', resolve(BACKEND_DIR, config), remote ? '--remote' : '--local']
const main = async () => {
// 1) Look up an existing user.
const checkSql = `SELECT id, name, email, mobile FROM users WHERE ${match} ORDER BY id LIMIT 1;`
const check = run([...targetArgs, '--json', '--command', checkSql])
if (check.code !== 0) {
die(`lookup failed:\n${check.err || check.out}`)
}
const parsed = parseJson(check.out)
const existing = parsed?.[0]?.results?.[0] as { id: number } | undefined
if (existing && !update) {
die(`a user with that email/mobile already exists (id=${existing.id}). Pass --update to reset its password.`)
}
// 2) Hash the password (bcrypt, same cost as signup).
const hash = await bcrypt.hash(password!, 12)
// 3) Build the write.
let sql: string
if (existing) {
sql = [
`UPDATE users SET name = ${name === null ? 'name' : `COALESCE(${lit(name)}, name)`}, email = ${email === null ? 'email' : `COALESCE(${lit(email)}, email)`}, mobile = ${mobile === null ? 'mobile' : `COALESCE(${lit(mobile)}, mobile)`} WHERE id = ${existing.id};`,
`UPDATE user_creds SET user_password = ${q(hash)} WHERE user_id = ${existing.id};`,
`INSERT INTO user_creds (user_id, user_password) SELECT ${existing.id}, ${q(hash)} WHERE NOT EXISTS (SELECT 1 FROM user_creds WHERE user_id = ${existing.id});`,
].join('\n')
} else {
sql = [
`INSERT INTO users (name, email, mobile) VALUES (${lit(name)}, ${lit(email)}, ${lit(mobile)});`,
`INSERT INTO user_creds (user_id, user_password) VALUES (last_insert_rowid(), ${q(hash)});`,
].join('\n')
}
if (showSql) {
console.log(`-- target: ${dbName} (${remote ? 'remote' : 'local'}) via ${config}\n`)
console.log(sql)
return
}
// 4) Write.
const write = run([...targetArgs, '--command', sql])
if (write.code !== 0) {
die(`write failed:\n${write.err || write.out}`)
}
// 5) Report.
const after = run([...targetArgs, '--json', '--command', checkSql])
const row = parseJson(after.out)?.[0]?.results?.[0]
console.log(
`\n ${existing ? 'Updated password for' : 'Created'} user ${row?.id != null ? `#${row.id}` : ''}` +
`\n name: ${row?.name ?? name ?? '-'}` +
`\n email: ${row?.email ?? email ?? '-'}` +
`\n mobile: ${row?.mobile ?? mobile ?? '-'}` +
`\n target: ${dbName} (${remote ? 'remote' : 'local'})\n`,
)
}
await main()