You are here

public function TfaRecoveryCodeTest::testReadyCodesValidate in Two-factor Authentication (TFA) 8

@covers ::ready @covers ::getCodes @covers ::validate

File

tests/src/Unit/Plugin/TfaValidation/TfaRecoveryCodeTest.php, line 122

Class

TfaRecoveryCodeTest
@coversDefaultClass \Drupal\tfa\Plugin\TfaValidation\TfaRecoveryCode

Namespace

Drupal\Tests\tfa\Unit\Plugin\TfaValidation

Code

public function testReadyCodesValidate() {

  // No codes, means it isn't ready.
  $fixture = $this
    ->getFixture();
  $this
    ->assertFalse($fixture
    ->ready());

  // Fake some codes for user 3.
  $this->userData
    ->get('tfa', 3, 'tfa_recovery_code')
    ->willReturn([
    'foo',
    'bar',
  ]);
  $this->encryptionService
    ->decrypt('foo', $this->encryptionProfile
    ->reveal())
    ->willReturn('foo_decrypted');
  $this->encryptionService
    ->decrypt('bar', $this->encryptionProfile
    ->reveal())
    ->willReturn('bar_decrypted');
  $this->tfaSettings
    ->get('validation_plugin_settings.tfa_recovery_code.recovery_codes_amount')
    ->willReturn(10);
  $this->tfaSettings
    ->get('encryption')
    ->willReturn('foo');
  $this->tfaSettings
    ->get('default_validation_plugin')
    ->willReturn('bar');
  $this->encryptionProfileManager
    ->getEncryptionProfile('foo')
    ->willReturn($this->encryptionProfile
    ->reveal());
  $fixture = $this
    ->getFixture();
  $this
    ->assertTrue($fixture
    ->ready());
  $this
    ->assertEquals([
    'foo_decrypted',
    'bar_decrypted',
  ], $fixture
    ->getCodes());

  // Validate with a bad code. Prophecy doesn't support reference returns.
  $this->userData
    ->delete('tfa', 3, 'tfa_recovery_code')
    ->shouldBeCalled();
  $fixture = $this
    ->getFixture();
  $form_state = new FormState();
  $form_state
    ->setValues([
    'code' => 'bad_code',
  ]);
  $this
    ->assertFalse($fixture
    ->validateForm([], $form_state));
  $this
    ->assertCount(1, $fixture
    ->getErrorMessages());

  // Validate with a good code. This will remove the code and re-encrypt the
  // remaining code 'bar_decrypted'.
  $this->encryptionService
    ->encrypt('bar_decrypted', $this->encryptionProfile
    ->reveal())
    ->willReturn('bar');
  $this->userData
    ->set('tfa', 3, 'tfa_recovery_code', [
    1 => 'bar',
  ])
    ->shouldBeCalled();
  $fixture = $this
    ->getFixture();
  $form_state
    ->setValues([
    'code' => 'foo_decrypted',
  ]);
  $this
    ->assertTrue($fixture
    ->validateForm([], $form_state));
  $this
    ->assertEmpty($fixture
    ->getErrorMessages());
}