public static function changePasswordByCode($email, $code, $newPassword, $login = true)
    {
        if (empty($email)) {
            throw new BadRequestException("Missing required email for password reset confirmation.");
        }

        if (empty($newPassword)) {
            throw new BadRequestException("Missing new password for reset.");
        }

        if (empty($code) || 'y' == $code) {
            throw new BadRequestException("Invalid confirmation code.");
        }

        /** @var User $user */
        $user = User::whereEmail($email)->whereConfirmCode($code)->first();

        if (null === $user) {
            // bad code
            throw new NotFoundException("The supplied email and/or confirmation code were not found in the system.");
        } elseif ($user->isConfirmationExpired()) {
            throw new BadRequestException("Confirmation code expired.");
        }

        static::isAllowed($user);

        try {
            $user->confirm_code = 'y';
            $user->password = $newPassword;
            $user->save();
        } catch (\Exception $ex) {
            throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
        }

        if ($login) {
            static::userLogin($email, $newPassword);

            return ['success' => true, 'session_token' => Session::getSessionToken()];
        }

        return ['success' => true];
    }