Commit ee2efb84 authored by Lorenzo Trujillo Rojas's avatar Lorenzo Trujillo Rojas
Browse files

Se agrgó el método para obtener códigos de reseteo

parent 9ae7809c
Loading
Loading
Loading
Loading
+36 −0
Original line number Diff line number Diff line
@@ -10,10 +10,16 @@ import { LoginUserDto } from './dto/login-user.dto';
import { ALL_ROLES } from 'src/shared/enum/admin-role.enum';
import { PayloadJwtDto } from 'src/shared/dto/payload-jwt.dto';
import { UpdatePwdDto } from './dto/update-pwd.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UserResetCode } from './entities/user-reset-code.entity';
import { Repository } from 'typeorm';
import { randomInt } from 'crypto';
import { UserResetPasswordDto } from './dto/user-reset-password.dto';

@Injectable()
export class AuthUserService {
  constructor(
    @InjectRepository(UserResetCode) private userResetCodeRepository: Repository<UserResetCode>,
    private userService: UserService,
    private jwtService: JwtService,
    private encryptionService: EncryptionService,
@@ -75,4 +81,34 @@ export class AuthUserService {
    const newPwdHashed = await this.encryptionService.hashPassword(updatePwdDto.newPassword);
    await this.userService.updatePassword(email, newPwdHashed);
  }

  async getResetPasswordCode(email: string) {
    const user: User = await this.userService.findOne(email);
    if (!user) throw new UnauthorizedException('Invalid email');
    const resetCode = randomInt(100000, 999999).toString();
    const expirationDate = new Date();
    expirationDate.setHours(expirationDate.getHours() + 1);
    const existUserCode = await this.userResetCodeRepository.findBy({ user, code: resetCode });
    console.log(existUserCode);
    
    if (existUserCode.length > 0) {
      await this.userResetCodeRepository.delete(existUserCode[0].id);
    }
    await this.userResetCodeRepository.save({ user, code: resetCode, expirationDate });
    return resetCode;
  }

  async resetPassword({ email, resetCode, newPassword }: UserResetPasswordDto) {
    const user: User = await this.userService.findOne(email);
    if (!user) throw new UnauthorizedException('Invalid email');
    
    const userResetCode: UserResetCode[] = await this.userResetCodeRepository.findBy({ user, code: resetCode });

    if (userResetCode.length === 0) throw new UnauthorizedException('Invalid code');
    if (userResetCode[0].expirationDate < new Date()) throw new UnauthorizedException('Code expired');

    const newPwdHashed = await this.encryptionService.hashPassword(newPassword);
    await this.userService.updatePassword(email, newPwdHashed);
    await this.userResetCodeRepository.delete(userResetCode[0].id);
  }
}