login.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const moment = require('moment');
  5. const { ObjectId } = require('mongoose').Types;
  6. const { CrudService } = require('naf-framework-mongoose/lib/service');
  7. const { BusinessError, ErrorCode } = require('naf-core').Error;
  8. const jwt = require('jsonwebtoken');
  9. const uuid = require('uuid');
  10. class LoginService extends CrudService {
  11. constructor(ctx) {
  12. super(ctx, 'login');
  13. this.model = this.ctx.model.User;
  14. }
  15. async login({ login_id, password }) {
  16. assert(login_id, '请输入登录用户名');
  17. assert(password, '请输入密码');
  18. const user = await this.checkUser(login_id, password);
  19. const jwt_user = await this.createJwt(user);
  20. const state = uuid();
  21. const key = `free:auth:state:${state}`;
  22. await this.app.redis.set(key, jwt_user, 'EX', 60 * 60 * 24);
  23. return { key };
  24. }
  25. async checkUser(login_id, password) {
  26. const user = await this.model.findOne({ login_id }, '+password');
  27. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '用户不存在');
  28. if (user.password.secret !== password) {
  29. throw new BusinessError(ErrorCode.BAD_PASSWORD, '用户密码错误');
  30. }
  31. return JSON.parse(JSON.stringify(user));
  32. }
  33. // 创建登录Token
  34. async createJwt({ id, login_id, ...info }) {
  35. info = _.omit(info, [ '_v', 'meta' ]);
  36. const { secret, expiresIn = '1d' } = this.config.jwt;
  37. const subject = login_id;
  38. const res = { id, login_id, ...info };
  39. const token = await jwt.sign(res, secret, { expiresIn, subject });
  40. return token;
  41. }
  42. // 取得redis内token信息
  43. async token({ key }) {
  44. assert(key, 'key不能为空');
  45. const token = await this.app.redis.get(key);
  46. if (!token) {
  47. throw new BusinessError(ErrorCode.SERVICE_FAULT, 'token已经过期');
  48. }
  49. // 转换成用户信息,给过去
  50. let res = jwt.decode(token);
  51. res = _.pick(res, [ 'login_id', '_tenant', 'id', 'name', 'role', 'status' ]);
  52. return res;
  53. }
  54. // 删除操作
  55. async destroy({ key }) {
  56. const res = await this.app.redis.del(key);
  57. return res;
  58. }
  59. }
  60. module.exports = LoginService;