import { HttpException, HttpStatus, Injectable, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { UsersService } from 'kkk-lib/auth/users/users.service'; import { AuthModule } from 'kkk-lib/auth/auth.module'; import md5 = require('md5'); import { AuthCreateUserDto } from './auth/auth-create-user.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { PGroup } from 'kkk-lib/auth/entity/p-group'; import { Repository } from 'typeorm'; import { GroupService } from 'kkk-lib/auth/users/group.service'; import { PUser } from 'kkk-lib/auth/entity/p-user.entity'; import { AuthUpdateUserDto } from 'kkk-lib/auth/auth/auth-update-user.dto'; import { AuthUserPassUpdateDto } from './auth/auth-user-pass-update.dto'; import { v4 as uuidv4 } from 'uuid'; import { PUserPasswordRelEntity } from 'kkk-lib/auth/entity/p-user-password-rel.entity'; import { EmailService } from 'kkk-lib/auth/email.service'; @Injectable() export class AuthService { constructor( private readonly usersService: UsersService, private readonly jwtService: JwtService, @InjectRepository(PGroup) private readonly pGroupRepository: Repository, @InjectRepository(PUser) private readonly pUserRepository: Repository, private groupService: GroupService, @InjectRepository(PUserPasswordRelEntity) private readonly pUserPasswordRelEntityRepository: Repository, private readonly emailService: EmailService, ) {} async validateUser(username: string, pass: string): Promise { if (AuthModule.subSys) { //子系统的情况下,登录只能通过单点登录部分,不验证用户名密码 return null; } const user = await this.usersService.findOne(username); const midpass = pass + AuthModule.secretOrKey; const md5pass = md5(midpass); if (user && user.password === md5pass) { const { password, ...result } = user; return result; } return null; } async login(user: any) { let level = 0; if (user.userType && user.userType.level) { level = user.userType.level; } const profile = await this.usersService.getProfile(user.id); // console.log(profile); const payload = { username: user.username, sub: user.id, level: level, profile: profile, }; return { access_token: this.jwtService.sign(payload), }; } async createUser(createDto: AuthCreateUserDto, req: any) { if (!req.user.userId) { throw new UnauthorizedException(); } if ( !createDto.username || !createDto.password || !createDto.realName || !createDto.userTypeId ) { throw new HttpException( '必填项不能为空', HttpStatus.INTERNAL_SERVER_ERROR, ); } if (createDto.password.trim().length < 6) { throw new HttpException( '密码长度必须>=6', HttpStatus.INTERNAL_SERVER_ERROR, ); } let createFlag = false; const data = await this.usersService.findOneById(req.user.userId); if (data.userType.name == AuthModule.manageName) { createFlag = true; } if (createFlag) { // 添加用户 createDto['password'] = md5(createDto.password + AuthModule.secretOrKey); const user = { username: createDto.username, password: createDto.password, realName: createDto.realName, userType: { id: createDto.userTypeId }, }; if (createDto.deptId && createDto.deptId != 0) { user['depart'] = { id: createDto.deptId }; } console.log(user); await this.pUserRepository.save(user); return { code: 200, message: '添加成功', }; } else { throw new HttpException( '创建失败,没有该权限', HttpStatus.INTERNAL_SERVER_ERROR, ); } } async resetPassword(req: any, updateDto: AuthUpdateUserDto) { if (!req.user.userId) { throw new UnauthorizedException(); } if (!updateDto.userId) { throw new HttpException( 'userId不能为空', HttpStatus.INTERNAL_SERVER_ERROR, ); } if (req.user.profile.userType.name !== '管理员') { throw new HttpException( '权限不足,不能操作', HttpStatus.INTERNAL_SERVER_ERROR, ); } if (!updateDto.password) { updateDto.password = 'password'; } else if (updateDto.password && updateDto.password.trim().length < 6) { throw new HttpException( '密码长度必须>=6', HttpStatus.INTERNAL_SERVER_ERROR, ); } const newPassword = md5(updateDto.password + AuthModule.secretOrKey); await this.usersService .updateInfo(updateDto.userId, { password: newPassword, }) .catch((error) => { console.log(error); throw new HttpException( '重置密码失败', HttpStatus.INTERNAL_SERVER_ERROR, ); }); return { code: 200, message: '重置成功', }; } async forgetPassword(email: string) { if (!email) { throw new HttpException( '邮箱不能为空!', HttpStatus.INTERNAL_SERVER_ERROR, ); } const user = await this.pUserRepository.findOne({ where: { email, }, order: { createdTime: 'DESC', }, }); if (user) { const reset_password_token = uuidv4(); // 发送邮箱 await this.emailService.sendEMail( { username: user.username, query: { reset_password_token, }, }, email, ); await this.pUserPasswordRelEntityRepository.save({ userId: user.id, status: 0, reset_password_token, }); return { code: 200, message: '请求成功', }; } throw new HttpException( '找不到该用户,请确保邮箱是否输入正确!', HttpStatus.INTERNAL_SERVER_ERROR, ); } async updatePassword(updateDto: AuthUserPassUpdateDto) { if ( !updateDto.reset_password_token || !updateDto.password || updateDto.password.length < 6 ) { throw new HttpException( '参数不能为空或密码长度必须 >= 6', HttpStatus.INTERNAL_SERVER_ERROR, ); } const p:any = { reset_password_token: updateDto.reset_password_token, status: 0, } const data = await this.pUserPasswordRelEntityRepository.findOne(p); if (data) { // 修改密码 await this.pUserRepository .update(data.userId, { password: md5(updateDto.password + AuthModule.secretOrKey), }) .catch((err) => { console.log('修改密码失败:' + err); }); // 修改关系表 await this.pUserPasswordRelEntityRepository .update(data.id, { status: 1, }) .catch((err) => { console.log('修改关系表失败:' + err); }); return { code: 200, message: '修改成功', }; } throw new HttpException( 'token不存在或已失效', HttpStatus.INTERNAL_SERVER_ERROR, ); } }