93 lines
3.3 KiB
JavaScript
93 lines
3.3 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const bcrypt = require('bcryptjs');
|
||
|
||
/** bcrypt 成本因子,改这里等于改全站强度(与 scripts/set-password.js 保持一致) */
|
||
const BCRYPT_ROUNDS = 10;
|
||
|
||
/** 账号不存在时也做一次比较,避免通过响应时间探测账号是否存在 */
|
||
const DUMMY_HASH = bcrypt.hashSync('pack-service-dummy-password', BCRYPT_ROUNDS);
|
||
|
||
class AuthService extends Service {
|
||
/** 生成密码哈希(存库用) */
|
||
async hashPassword(plain) {
|
||
return bcrypt.hash(String(plain), BCRYPT_ROUNDS);
|
||
}
|
||
|
||
/**
|
||
* 账号密码登录:account 支持用户名或手机号
|
||
* @param {string} account 用户名 / 手机号
|
||
* @param {string} password 明文密码
|
||
* @return {Promise<object|null>} 成功返回脱敏用户信息,失败返回 null
|
||
*/
|
||
async login(account, password) {
|
||
if (!account || !password) return null;
|
||
|
||
const user = await this.ctx.service.user.findByAccount(account);
|
||
const hash = user && user.passwordHash ? user.passwordHash : DUMMY_HASH;
|
||
const matched = await bcrypt.compare(String(password), hash);
|
||
|
||
if (!user || !matched) {
|
||
this.ctx.logger.warn('[auth] 登录失败: %s', account);
|
||
return null;
|
||
}
|
||
if (Number(user.status) !== 1) {
|
||
this.ctx.logger.warn('[auth] 账号已被禁用: %s', account);
|
||
return null;
|
||
}
|
||
|
||
await user.update({ lastLoginAt: new Date() });
|
||
return this.ctx.service.user.toSafeUser(user);
|
||
}
|
||
|
||
/**
|
||
* 自助注册:建用户 + 写入密码哈希
|
||
* 用户名/手机号唯一性由 user service 的 assertUnique 保证(冲突抛 409)
|
||
* @return {Promise<object>} 脱敏用户信息(不含密码哈希)
|
||
*/
|
||
async register({ username, password, nickname, phone, email }) {
|
||
const user = await this.ctx.service.user.create({
|
||
username,
|
||
nickname: nickname || username,
|
||
phone: phone || null,
|
||
email: email || null,
|
||
});
|
||
await this.ctx.service.user.setPassword(user.id, await this.hashPassword(password));
|
||
this.ctx.logger.info('[auth] 新用户注册: %s (id=%s)', username, user.id);
|
||
return user;
|
||
}
|
||
|
||
/**
|
||
* 设置/重置密码(脚本或后续的改密接口用)
|
||
* @return {Promise<boolean>} 用户不存在返回 false
|
||
*/
|
||
async setPassword(userId, plain) {
|
||
const hash = await this.hashPassword(plain);
|
||
return this.ctx.service.user.setPassword(userId, hash);
|
||
}
|
||
|
||
/**
|
||
* 修改密码:先校验原密码,再写入新哈希
|
||
* @return {Promise<boolean>} 原密码不对或用户不存在返回 false
|
||
*/
|
||
async changePassword(userId, oldPassword, newPassword) {
|
||
const user = await this.ctx.service.user.findByIdWithPassword(userId);
|
||
if (!user || !user.passwordHash) return false;
|
||
|
||
const matched = await bcrypt.compare(String(oldPassword), user.passwordHash);
|
||
if (!matched) {
|
||
this.ctx.logger.warn('[auth] 修改密码失败:原密码不正确, userId=%s', userId);
|
||
return false;
|
||
}
|
||
|
||
await user.update({ passwordHash: await this.hashPassword(newPassword), passwordChangedAt: new Date() });
|
||
// 该用户详情有缓存(/api/users/:id),顺手失效
|
||
await this.ctx.service.cache.del(`user:${userId}`).catch(() => {});
|
||
this.ctx.logger.info('[auth] 密码已修改, userId=%s(旧令牌立即失效)', userId);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
module.exports = AuthService;
|