const express = require('express'); const router = express.Router(); const crypto = require('crypto'); const events = require('events'); const db = require('../common/mysqlConnection'); router.post('/', (req, res, next) => { if (!req.body) { res.status(200).send({ status: 'error', info: '参数错误' }); } else { let captchaCode = req.body.captcha; if (req.session.captcha !== captchaCode) { res.status(200).send({ status: 'error', info: '验证码错误' }); } else { let emitter = new events.EventEmitter(), userId = req.body.userId, password = req.body.password; emitter.on('ok', () => { res.status(200).send({ status: 'successed', info: '注册成功', url: '#/signin' }); }); emitter.on('err', (err, errInfo) => { res.status(200).send({ status: 'error', info: errInfo, error: err }); }); //检测UserId是否存在 emitter.on('selectUserIdFromUserTable', () => { //定义SQL语句查询UserID是否存在 let pool = db.pool.adminDatabasePool; sqlString = 'SELECT userId FROM CloudSqlAdmin_Users WHERE userId = ?', value = [userId]; db.queryArgs(pool, sqlString, value, (err, results, fields) => { if (err) { emitter.emit('err', err.err, err.errInfo); } else { if (results.length !== 0) { emitter.emit('err', null, '邮箱或用户名已存在'); } else { emitter.emit('createSalt'); } } }); }) //生成salt emitter.on('createSalt', () => { crypto.randomBytes(128, (err, salt) => { if (err) { throw err; } salt = salt.toString('hex'); emitter.emit('createPassword', salt); }); }); //生成密码 emitter.on('createPassword', (salt) => { crypto.pbkdf2(password, salt, 4096, 256, 'SHA256', (err, hash) => { if (err) { emitter.emit('err', err, '后端逻辑出错,请联系管理员修复该问题'); throw err; } hash = hash.toString('hex'); //生成密文 emitter.emit('insertUserInfoToUserTable', hash, salt); }) }); //向User表插入数据 emitter.on('insertUserInfoToUserTable', (hash, salt) => { //定义向Users表插入用户账户信息的SQL语句 let pool = db.pool.adminDatabasePool; sqlString = 'INSERT INTO CloudSqlAdmin_Users (uid, userId, password, salt, createTime, lastUpdateTime) VALUES (uuid(), ?, ?, ?, NOW(), NOW())', value = [userId, hash, salt]; db.queryArgs(pool, sqlString, value, (err, results, fields) => { if (err) { emitter.emit('err', err.err, err.errInfo); } else { emitter.emit('insertUserInfoToUserProfileTable'); } }); }); //向UserProfile表插入数据 emitter.on('insertUserInfoToUserProfileTable', () => { //定义向UsersProfile表插入用户账户信息的SQL语句 let pool = db.pool.adminDatabasePool; sqlString = 'INSERT INTO CloudSqlAdmin_UsersProfile (uid, userId, inviteCode, userStatus, createTime, lastUpdateTime) VALUES (uuid(), ?, ?, 1, NOW(), NOW())', value = [userId, '$$$TempPassCode']; db.queryArgs(pool, sqlString, value, (err, results, fields) => { if (err) { emitter.emit('err', err.err, err.errInfo); } else { emitter.emit('ok'); } }); }); emitter.emit('selectUserIdFromUserTable'); } } }); module.exports = router;