Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 30x 30x 30x 30x 11x 11x 11x 4x 4x 7x 7x 1x 6x 6x 6x 6x 6x | import { logger } from '../../shared/logging/logger';
import { UserRepository } from './user-repository';
import { PasswordHasher } from './password-hasher';
import { TokenService } from './token-service';
import { VerificationCodeService } from './verification-code-service';
import { InvalidVerificationCodeError } from './errors/invalid-verification-code.error';
import { VerifiedSession } from './verify-passwordless-code.use-case';
export interface ResetPasswordInput {
email: string;
code: string;
password: string;
}
/**
* Setting a new password with a mailed code, for someone who cannot log in to change it the normal
* way (UpdateUserProfileUseCase, which requires the current password).
*
* Resetting also ends every other session. A reset is what someone does *after* suspecting their
* account was reached by somebody else, so leaving the intruder's refresh token working would make
* the whole operation cosmetic.
*/
export class ResetPasswordUseCase {
constructor(
private readonly userRepository: UserRepository,
private readonly verificationCodeService: VerificationCodeService,
private readonly passwordHasher: PasswordHasher,
private readonly tokenService: TokenService,
) {}
async execute(input: ResetPasswordInput): Promise<VerifiedSession> {
const email = input.email.trim().toLowerCase();
const check = await this.verificationCodeService.consume('password-reset', email, input.code);
if (check !== 'valid') {
logger.warn({ check, purpose: 'password-reset' }, 'auth.verification_code_rejected');
throw new InvalidVerificationCodeError();
}
const user = await this.userRepository.findByEmail(email);
if (!user) {
throw new InvalidVerificationCodeError();
}
const updated = user.withResetPassword(await this.passwordHasher.hash(input.password));
await this.userRepository.save(updated);
// Minted at the *new* version, so the session this request hands back is the only one that
// survives its own invalidation. Every refresh token still out there carries the old number.
const tokens = this.tokenService.generateTokenPair(user.id, updated.sessionVersion);
logger.info({ userId: user.id }, 'auth.password_reset_succeeded');
return { userId: user.id, ...tokens };
}
}
|