'use strict'; module.exports = app => { const { BIGINT, STRING, DATE, TINYINT, fn } = app.Sequelize; const Account = app.model.define('account', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false, comment: '账号ID', }, username: { type: STRING(50), allowNull: false, unique: 'idx_username', validate: { notEmpty: { msg: '用户名不能为空', }, len: { args: [ 3, 50 ], msg: '用户名长度应在3-50个字符之间', }, is: { args: /^[a-zA-Z0-9_]+$/, msg: '用户名只能包含字母、数字和下划线', }, }, comment: '用户名', }, email: { type: STRING(100), allowNull: false, validate: { notEmpty: { msg: '邮箱不能为空', }, isEmail: { msg: '请输入有效的邮箱地址', }, }, comment: '邮箱', }, password_hash: { type: STRING(255), allowNull: false, comment: '密码哈希', }, real_name: { type: STRING(50), allowNull: false, validate: { notEmpty: { msg: '真实姓名不能为空', }, len: { args: [ 2, 50 ], msg: '真实姓名长度应在2-50个字符之间', }, }, comment: '真实姓名', }, status: { type: TINYINT(1), allowNull: false, defaultValue: 1, validate: { isIn: { args: [[ 0, 1 ]], msg: '状态值不合法,0-封号,1-启用', }, }, comment: '状态:0-封号,1-启用', }, last_login_at: { type: DATE, allowNull: true, comment: '最后登录时间', }, created_at: { type: DATE, allowNull: false, defaultValue: fn('NOW'), comment: '创建时间', }, updated_at: { type: DATE, allowNull: false, defaultValue: fn('NOW'), comment: '更新时间', }, salt: { type: STRING(20), allowNull: true, comment: '密码盐', }, last_login_ip: { type: STRING(15), allowNull: true, comment: '最后登录ip', }, }, { tableName: 'wms_account', freezeTableName: true, underscored: true, timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', comment: '平台账号表', indexes: [ { name: 'idx_username', fields: [ 'username' ], unique: true, }, { name: 'idx_phone', fields: [ 'phone' ], }, { name: 'idx_email', fields: [ 'email' ], }, { name: 'idx_status', fields: [ 'status' ], }, ], }); // 关联关系 Account.associate = function() { const { AccountStoreEmployee, AccountPlatformActive } = app.model; Account.hasMany(AccountStoreEmployee, { foreignKey: 'account_id', as: 'accountStoreEmployees', }); Account.hasMany(AccountPlatformActive, { foreignKey: 'account_id', as: 'platformActives', }); }; // 实例方法 Account.prototype.toJSON = function() { const values = { ...this.get() }; // 只有在需要返回给客户端时才删除敏感字段 if (this._hideSensitive !== false) { delete values.password_hash; delete values.salt; } return values; }; // 验证密码 Account.prototype.verifyPassword = async function(password) { const crypto = require('crypto'); // 检查 password_hash 是否存在 if (!this.password_hash) { console.error('password_hash is undefined for user:', this.id); return false; } // 检查 salt 是否存在 if (!this.salt) { console.error('salt is undefined for user:', this.id); return false; } const hash = crypto .createHash('sha256') .update(password + (this.salt || '')) .digest('hex'); console.log(`计算后的hash: ${hash}`); console.log(`数据库中的password_hash: ${this.password_hash}`); console.log(`是否匹配: ${hash === this.password_hash}`); return hash === this.password_hash; }; return Account; };