backend/src/models/actions/create/CreateResetToken.ts
Nicolai Ort 8f0a396dd0
All checks were successful
continuous-integration/drone/pr Build is passing
Bugfix for @lfk/frontend/#43
2021-02-07 13:37:01 +01:00

44 lines
1.7 KiB
TypeScript

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { getConnectionManager } from 'typeorm';
import { ResetAlreadyRequestedError, UserDisabledError, UserNotFoundError } from '../../../errors/AuthError';
import { UserEmailNeededError } from '../../../errors/UserErrors';
import { JwtCreator } from '../../../jwtcreator';
import { User } from '../../entities/User';
/**
* 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.
*/
export class CreateResetToken {
/**
* The email address of the user that wants to reset their password.
*/
@IsNotEmpty()
@IsEmail()
@IsString()
email: string;
/**
* Create a password reset token based on this.
*/
public async toResetToken(): Promise<string> {
if (!this.email) {
throw new UserEmailNeededError();
}
let found_user = await getConnectionManager().get().getRepository(User).findOne({ where: [{ email: this.email }] });
if (!found_user) { throw new UserNotFoundError(); }
if (found_user.enabled == false) { throw new UserDisabledError(); }
if (found_user.resetRequestedTimestamp > (Math.floor(Date.now() / 1000) - 15 * 60)) { throw new ResetAlreadyRequestedError(); }
found_user.refreshTokenCount = found_user.refreshTokenCount + 1;
found_user.resetRequestedTimestamp = Math.floor(Date.now() / 1000);
await getConnectionManager().get().getRepository(User).save(found_user);
//Create the reset token
let reset_token: string = JwtCreator.createReset(found_user);
return reset_token;
}
}