Password reset now enforces email

ref #118
This commit is contained in:
Nicolai Ort 2021-01-26 18:07:56 +01:00
parent c43334bf96
commit 979d36ea91

View File

@ -1,39 +1,33 @@
import { IsEmail, IsOptional, IsString } from 'class-validator'; import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { getConnectionManager } from 'typeorm'; import { getConnectionManager } from 'typeorm';
import { ResetAlreadyRequestedError, UserDisabledError, UserNotFoundError } from '../../../errors/AuthError'; import { ResetAlreadyRequestedError, UserDisabledError, UserNotFoundError } from '../../../errors/AuthError';
import { UsernameOrEmailNeededError } from '../../../errors/UserErrors'; import { UserEmailNeededError } from '../../../errors/UserErrors';
import { JwtCreator } from '../../../jwtcreator'; import { JwtCreator } from '../../../jwtcreator';
import { User } from '../../entities/User'; import { User } from '../../entities/User';
/** /**
* This calss is used to create password reset tokens for users. * This class is used to create password reset tokens for users.
* These password reset token can be used to set a new password for the user for the next 15mins. * These password reset token can be used to set a new password for the user for the next 15mins.
*/ */
export class CreateResetToken { export class CreateResetToken {
/**
* The username of the user that wants to reset their password.
*/
@IsOptional()
@IsString()
username?: string;
/** /**
* The email address of the user that wants to reset their password. * The email address of the user that wants to reset their password.
*/ */
@IsOptional() @IsNotEmpty()
@IsEmail() @IsEmail()
@IsString() @IsString()
email?: string; email: string;
/** /**
* Create a password reset token based on this. * Create a password reset token based on this.
*/ */
public async toResetToken(): Promise<any> { public async toResetToken(): Promise<any> {
if (this.email === undefined && this.username === undefined) { if (!this.email) {
throw new UsernameOrEmailNeededError(); throw new UserEmailNeededError();
} }
let found_user = await getConnectionManager().get().getRepository(User).findOne({ where: [{ username: this.username }, { email: this.email }] }); let found_user = await getConnectionManager().get().getRepository(User).findOne({ where: [{ email: this.email }] });
if (!found_user) { throw new UserNotFoundError(); } if (!found_user) { throw new UserNotFoundError(); }
if (found_user.enabled == false) { throw new UserDisabledError(); } if (found_user.enabled == false) { throw new UserDisabledError(); }
if (found_user.resetRequestedTimestamp > (Math.floor(Date.now() / 1000) - 15 * 60)) { throw new ResetAlreadyRequestedError(); } if (found_user.resetRequestedTimestamp > (Math.floor(Date.now() / 1000) - 15 * 60)) { throw new ResetAlreadyRequestedError(); }