'use strict'; const assert = require('assert'); const { ObjectId } = require('mongoose').Types; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const jwt = require('jsonwebtoken'); const uuid = require('uuid'); class LoginService extends CrudService { constructor(ctx) { super(ctx, 'login'); this.model = this.ctx.model.Dock; } // 用户登录 async login(data) { const { room_phone, passwd, role } = data; const phone = room_phone; const room_id = room_phone; // 根据用户输入的手机号查询其他用户表中是否存在相应数据 let user = await this.model.findOne({ phone, role }); const flag = true; if (!user) { user = await this.model.findOne({ room_id, role }); } // 如果用户不存在抛出异常 if (!user) { throw new BusinessError(ErrorCode.USER_NOT_EXIST); } let _user = ''; // 将用户输入的密码进行加密并与查询到的用户数据密码相比对 const pasw = await this.createJwtPwd(passwd); if (flag) { // 手机 _user = await this.model.findOne({ phone, pasw }); } else { // 房间号 _user = await this.model.findOne({ room_id, pasw }); } if (_user === '') { throw new BusinessError(ErrorCode.USER_NOT_EXIST); // throw new BusinessError(ErrorCode.BAD_PASSWORD); } else { if (role === '3') { const operationlogdata = { login_id: user.id, login_name: user.name, login_role: user.role, type: '0', operation_edit: '登录' }; const url = 'http://127.0.0.1:9004/api/market/operationlog/'; const operationlog = await this.ctx.curl(url, { method: 'post', headers: { 'content-type': 'application/json', }, dataType: 'json', data: JSON.stringify(operationlogdata), }); } } // 取出用户的类型,根据用户类型返回相应信息 const state = uuid(); const key = `free:auth:state:${state}`; const token = await this.createJwt(user); await this.app.redis.set(key, token, 'EX', 60 * 60 * 24); return { key }; } // 创建登录Token async createJwtPwd(password) { const { secret } = this.config.jwt; const token = await jwt.sign(password, secret); return token; } // 创建登录Token async createJwt({ id, adminuser, uid, phone, role, remark, deptid, pid, code }) { const { secret, expiresIn = '1d', issuer = role } = this.config.jwt; const subject = phone; const res = { uid: id, userid: uid, adminuser, phone, role, remark, deptid, pid, code }; const token = await jwt.sign(res, secret, { expiresIn, issuer, subject }); return token; } // 取得redis内token信息 async token({ key }) { assert(key, 'key不能为空'); const token = await this.app.redis.get(key); if (!token) { throw new BusinessError(ErrorCode.SERVICE_FAULT, 'token已经过期'); } return { token }; } // 删除操作 async destroy({ key }) { const res = await this.app.redis.del(key); console.log(res); return res; } } module.exports = LoginService;