import { Body, Config, Controller, Inject, Param, Post, Get } from '@midwayjs/core'; import { ApiTags } from '@midwayjs/swagger'; import { LoginDTO, LoginType, LoginVO, UPwdDTO } from '../interface/login.interface'; import { LoginService } from '../service/login.service'; import { JwtService } from '@midwayjs/jwt'; import { Context } from '@midwayjs/koa'; const assert = require('assert'); import get = require('lodash/get'); import { UtilService } from '../service/util.service'; import { FrameworkErrorEnum, ServiceError } from 'free-midway-component'; @ApiTags(['登录服务']) @Controller('/login') export class LoginController { @Inject() loginService: LoginService; @Inject() jwtService: JwtService; @Inject() utilService: UtilService; @Config('jwt.secret') jwtSecret; @Config('jwt.expiresIn') jwtExpiresIn; @Inject() ctx: Context; /** * 账密登录 * @param data 用户名和密码 * @param type 用户类型 */ @Post('/:type') async toLogin(@Body() data: LoginDTO, @Param('type') type: string) { const user = await this.loginService.loginByAccount(data, LoginType[type]); if (user) user.role = type; let vo = new LoginVO(user); vo = JSON.parse(JSON.stringify(vo)); const token = await this.jwtService.sign(vo, this.jwtSecret, { expiresIn: this.jwtExpiresIn, }); return token; } /** * TODO:微信小程序登录 * @param openid 微信小程序openid */ @Post('/wxapp/:openid') async wxAppLogin(@Param('openid') openid: string) { if (!openid) throw new ServiceError('缺少微信凭证!', FrameworkErrorEnum.BAD_PARAMS); const user = await this.loginService.wxAppLogin(openid); return user; } /** * 修改密码 * @param data 修改密码所需数据 * @param type 账户类型 */ @Post('/updatePwd/:type') async updatePwd(@Body() data: UPwdDTO, @Param('type') type: string) { // 随机密码 data.password = this.utilService.randomStr(); await this.loginService.updatePwd(data, LoginType[type]); return 'ok'; } @Post('/resetPwd/:type') async resetPwd(@Body('_id') _id: string, @Param('type') type: string) { // 随机密码 const data = new UPwdDTO(); data._id = _id; data.password = this.utilService.randomStr(); await this.loginService.updatePwd(data, LoginType[type]); return data.password; } @Get('/analysis') async analysisToken() { const token = get(this.ctx, 'request.header.token'); assert(token, '缺少token信息'); const result = await this.jwtService.decodeSync(token); return result; } }