// reset-password.js — emergency portal password reset (username-based, no email needed) // // USAGE (run from project root): // node reset-password.js → list all portal users // node reset-password.js → reset that user's password + reactivate // // Examples: // node reset-password.js // node reset-password.js admin NewPass@123 // require('dotenv').config(); const bcrypt = require('bcryptjs'); const { getPool, query } = require('./services/sqlPool'); const TABLE = '[dbo].[ZCUST_USERS]'; (async () => { const [, , username, newPassword] = process.argv; try { await getPool(); // fail fast if DB unreachable // No args → just list users so you know the exact usernames if (!username) { const rows = await query( `SELECT ID, USERNAME, FULL_NAME, EMAIL, ROLE, ACTIVE, LAST_LOGIN FROM ${TABLE} ORDER BY ROLE, USERNAME` ); if (!rows.length) { console.log('\n⚠ No users found in ZCUST_USERS. Restart the server once to seed the default admin (admin / Admin@123).\n'); } else { console.log('\n── Portal users (login with USERNAME, not email) ─────────────'); rows.forEach(r => console.log( ` #${r.ID} ${String(r.USERNAME).padEnd(14)} ${String(r.ROLE).padEnd(12)} ` + `active=${r.ACTIVE} ${r.FULL_NAME || ''}` ) ); console.log('\nTo reset one: node reset-password.js \n'); } process.exit(0); } if (!newPassword) { console.error('\n❌ Missing new password.\n Usage: node reset-password.js \n'); process.exit(1); } const uname = username.toLowerCase(); const existing = await query(`SELECT ID FROM ${TABLE} WHERE LOWER(USERNAME) = ?`, [uname]); if (!existing.length) { console.error(`\n❌ No user with username "${uname}". Run without args to list valid usernames.\n`); process.exit(1); } const hash = await bcrypt.hash(newPassword, 10); // Also set ACTIVE=1 — login only matches active users (auth.js / findByUsername) await query(`UPDATE ${TABLE} SET PASSWORD = ?, ACTIVE = 1 WHERE LOWER(USERNAME) = ?`, [hash, uname]); console.log(`\n✅ Password reset for "${uname}" and account reactivated.`); console.log(` Log in with username: ${uname} password: ${newPassword}\n`); process.exit(0); } catch (err) { console.error('\n❌ Reset failed:', err.message); console.error(' Check that the SQL Server in .env is reachable from this machine.\n'); process.exit(1); } })();