65 lines
2.2 KiB
JavaScript
65 lines
2.2 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 创建用户 / 重置登录密码(本机没装 mysql 客户端也能用)
|
||
*
|
||
* 用法:
|
||
* npm run user:pass -- <账号> <密码> [昵称]
|
||
* node scripts/set-password.js admin 123456 管理员
|
||
*
|
||
* 账号不存在时自动创建(username = 账号,status = 1);
|
||
* 账号存在时只重置密码。密码经 bcrypt 哈希后写入 users.password_hash。
|
||
*/
|
||
|
||
const mysql = require('mysql2/promise');
|
||
const bcrypt = require('bcryptjs');
|
||
const resolveDbConfig = require('./db-config');
|
||
|
||
/** 与 app/service/auth.js 的 BCRYPT_ROUNDS 保持一致 */
|
||
const BCRYPT_ROUNDS = 10;
|
||
|
||
function usage() {
|
||
console.log('用法: npm run user:pass -- <账号> <密码> [昵称]');
|
||
console.log('示例: npm run user:pass -- admin 123456 管理员');
|
||
}
|
||
|
||
async function main() {
|
||
const [ account, password, nickname ] = process.argv.slice(2);
|
||
if (!account || !password) {
|
||
usage();
|
||
process.exit(1);
|
||
}
|
||
|
||
const hash = await bcrypt.hash(String(password), BCRYPT_ROUNDS);
|
||
const config = resolveDbConfig();
|
||
const conn = await mysql.createConnection(config);
|
||
|
||
try {
|
||
const [rows] = await conn.query(
|
||
'select id, username, phone, email from users where (username = ? or phone = ? or email = ?) and deleted_at is null limit 1',
|
||
[ account, account, account ],
|
||
);
|
||
|
||
if (rows.length) {
|
||
const user = rows[0];
|
||
await conn.query('update users set password_hash = ?, updated_at = now() where id = ?', [ hash, user.id ]);
|
||
console.log(`[user:pass] 已重置密码: ${user.username || user.phone || user.email} (id=${user.id})`);
|
||
} else {
|
||
const [result] = await conn.query(
|
||
'insert into users (username, nickname, password_hash, password_changed_at, status) values (?, ?, ?, now(), 1)',
|
||
[ account, nickname || account, hash ],
|
||
);
|
||
console.log(`[user:pass] 已创建用户: ${account} (id=${result.insertId}),昵称: ${nickname || account}`);
|
||
}
|
||
|
||
console.log(`[user:pass] 连接: ${config.host}:${config.port}/${config.database} as ${config.user}`);
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
}
|
||
|
||
main().catch((err) => {
|
||
console.error(`[user:pass] 失败: ${err.code || ''} ${err.message}`);
|
||
process.exit(1);
|
||
});
|