|
@@ -1,67 +0,0 @@
|
|
-'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.User;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 用户登录
|
|
|
|
- async login(data) {
|
|
|
|
- const { mobile, password } = data;
|
|
|
|
- // 根据用户输入的手机号查询其他用户表中是否存在相应数据
|
|
|
|
- const user = await this.model.findOne({ mobile }, '+password');
|
|
|
|
- if (!user) {
|
|
|
|
- throw new BusinessError(ErrorCode.USER_NOT_EXIST);
|
|
|
|
- }
|
|
|
|
- if (user.password.secret !== password) {
|
|
|
|
- throw new BusinessError(ErrorCode.USER_NOT_EXIST);
|
|
|
|
- }
|
|
|
|
- // 取出用户的类型,根据用户类型返回相应信息
|
|
|
|
- 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 createJwt({ id, name, mobile, dept_id, gender, remark }) {
|
|
|
|
- const { secret, expiresIn = '1d' } = this.config.jwt;
|
|
|
|
- const subject = mobile;
|
|
|
|
- const res = { uid: id, name, mobile, dept_id, gender, remark };
|
|
|
|
- const token = await jwt.sign(res, secret, { expiresIn, subject });
|
|
|
|
- return token;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 创建密码
|
|
|
|
- async createJwtPwd(password) {
|
|
|
|
- const { secret } = this.config.jwt;
|
|
|
|
- const token = await jwt.sign(password, secret);
|
|
|
|
- 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);
|
|
|
|
- return res;
|
|
|
|
- }
|
|
|
|
-}
|
|
|
|
-module.exports = LoginService;
|
|
|