login.controller.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Body, Config, Controller, Inject, Param, Post, Get } from '@midwayjs/core';
  2. import { ApiTags } from '@midwayjs/swagger';
  3. import { LoginDTO, LoginType, LoginVO, UPwdDTO } from '../interface/login.interface';
  4. import { LoginService } from '../service/login.service';
  5. import { JwtService } from '@midwayjs/jwt';
  6. import { Context } from '@midwayjs/koa';
  7. const assert = require('assert');
  8. import get = require('lodash/get');
  9. import { UtilService } from '../service/util.service';
  10. import { FrameworkErrorEnum, ServiceError } from 'free-midway-component';
  11. @ApiTags(['登录服务'])
  12. @Controller('/login')
  13. export class LoginController {
  14. @Inject()
  15. loginService: LoginService;
  16. @Inject()
  17. jwtService: JwtService;
  18. @Inject()
  19. utilService: UtilService;
  20. @Config('jwt.secret')
  21. jwtSecret;
  22. @Config('jwt.expiresIn')
  23. jwtExpiresIn;
  24. @Inject()
  25. ctx: Context;
  26. /**
  27. * 账密登录
  28. * @param data 用户名和密码
  29. * @param type 用户类型
  30. */
  31. @Post('/:type')
  32. async toLogin(@Body() data: LoginDTO, @Param('type') type: string) {
  33. const user = await this.loginService.loginByAccount(data, LoginType[type]);
  34. if (user) user.role = type;
  35. let vo = new LoginVO(user);
  36. vo = JSON.parse(JSON.stringify(vo));
  37. const token = await this.jwtService.sign(vo, this.jwtSecret, {
  38. expiresIn: this.jwtExpiresIn,
  39. });
  40. return token;
  41. }
  42. /**
  43. * TODO:微信小程序登录
  44. * @param openid 微信小程序openid
  45. */
  46. @Post('/wxapp/:openid')
  47. async wxAppLogin(@Param('openid') openid: string) {
  48. if (!openid) throw new ServiceError('缺少微信凭证!', FrameworkErrorEnum.BAD_PARAMS);
  49. const user = await this.loginService.wxAppLogin(openid);
  50. return user;
  51. }
  52. /**
  53. * 修改密码
  54. * @param data 修改密码所需数据
  55. * @param type 账户类型
  56. */
  57. @Post('/updatePwd/:type')
  58. async updatePwd(@Body() data: UPwdDTO, @Param('type') type: string) {
  59. // 随机密码
  60. data.password = this.utilService.randomStr();
  61. await this.loginService.updatePwd(data, LoginType[type]);
  62. return 'ok';
  63. }
  64. @Post('/resetPwd/:type')
  65. async resetPwd(@Body('_id') _id: string, @Param('type') type: string) {
  66. // 随机密码
  67. const data = new UPwdDTO();
  68. data._id = _id;
  69. data.password = this.utilService.randomStr();
  70. await this.loginService.updatePwd(data, LoginType[type]);
  71. return data.password;
  72. }
  73. @Get('/analysis')
  74. async analysisToken() {
  75. const token = get(this.ctx, 'request.header.token');
  76. assert(token, '缺少token信息');
  77. const result = await this.jwtService.decodeSync(token);
  78. return result;
  79. }
  80. }