login.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const assert = require('assert');
  3. const { ObjectId } = require('mongoose').Types;
  4. const { CrudService } = require('naf-framework-mongoose/lib/service');
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. const jwt = require('jsonwebtoken');
  7. const uuid = require('uuid');
  8. class LoginService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'login');
  11. this.model = this.ctx.model.User;
  12. }
  13. // 用户登录
  14. async login(data) {
  15. const { mobile, password } = data;
  16. // 根据用户输入的手机号查询其他用户表中是否存在相应数据
  17. const user = await this.model.findOne({ mobile }, '+password');
  18. if (!user) {
  19. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  20. }
  21. if (user.password.secret !== password) {
  22. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  23. }
  24. // 取出用户的类型,根据用户类型返回相应信息
  25. const state = uuid();
  26. const key = `free:auth:state:${state}`;
  27. const token = await this.createJwt(user);
  28. await this.app.redis.set(key, token, 'EX', 60 * 60 * 24);
  29. return { key };
  30. }
  31. // 创建登录Token
  32. async createJwt({ id, name, mobile, dept_id, gender, remark }) {
  33. const { secret, expiresIn = '1d' } = this.config.jwt;
  34. const subject = mobile;
  35. const res = { uid: id, name, mobile, dept_id, gender, remark };
  36. const token = await jwt.sign(res, secret, { expiresIn, subject });
  37. return token;
  38. }
  39. // 创建密码
  40. async createJwtPwd(password) {
  41. const { secret } = this.config.jwt;
  42. const token = await jwt.sign(password, secret);
  43. return token;
  44. }
  45. // 取得redis内token信息
  46. async token({ key }) {
  47. assert(key, 'key不能为空');
  48. const token = await this.app.redis.get(key);
  49. if (!token) {
  50. throw new BusinessError(ErrorCode.SERVICE_FAULT, 'token已经过期');
  51. }
  52. return { token };
  53. }
  54. // 删除操作
  55. async destroy({ key }) {
  56. const res = await this.app.redis.del(key);
  57. return res;
  58. }
  59. }
  60. module.exports = LoginService;