1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EcodevTests\Felix\Model\Traits; |
6
|
|
|
|
7
|
|
|
use Ecodev\Felix\Model\Traits\HasOtp; |
8
|
|
|
use OTPHP\Factory; |
9
|
|
|
use OTPHP\TOTPInterface; |
10
|
|
|
use PHPUnit\Framework\TestCase; |
11
|
|
|
|
12
|
|
|
final class HasOtpTest extends TestCase |
13
|
|
|
{ |
14
|
|
|
private \Ecodev\Felix\Model\HasOtp $user; |
15
|
|
|
|
16
|
|
|
protected function setUp(): void |
17
|
|
|
{ |
18
|
|
|
$this->user = new class() implements \Ecodev\Felix\Model\HasOtp { |
19
|
|
|
use HasOtp; |
20
|
|
|
|
21
|
|
|
public function getLogin(): ?string |
22
|
|
|
{ |
23
|
|
|
return '[email protected]'; |
24
|
|
|
} |
25
|
|
|
}; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function testCreateOtpSecret(): void |
29
|
|
|
{ |
30
|
|
|
self::assertNull($this->user->getOtpUri(), 'should have no OTP secret at first'); |
31
|
|
|
self::assertFalse($this->user->isOtp(), 'should have OTP disabled at first'); |
32
|
|
|
|
33
|
|
|
self::expectExceptionMessage('Cannot enable OTP without a secret'); |
|
|
|
|
34
|
|
|
$this->user->setOtp(true); |
35
|
|
|
|
36
|
|
|
$this->user->createOtpSecret('felix.lan'); |
37
|
|
|
$otp1 = $this->user->getOtpUri(); |
38
|
|
|
self::assertIsString($otp1); |
39
|
|
|
self::assertStringStartsWith('otpauth://totp/', $otp1, 'TOTP provisionning URI was generated and stored'); |
|
|
|
|
40
|
|
|
|
41
|
|
|
$this->user->createOtpSecret('felix.lan'); |
42
|
|
|
$otp2 = $this->user->getOtpUri(); |
43
|
|
|
self::assertIsString($otp2); |
44
|
|
|
self::assertNotSame($otp1, $otp2, 'TOTP provisionning URI was changed'); |
45
|
|
|
|
46
|
|
|
$this->user->setOtp(true); |
47
|
|
|
self::assertTrue($this->user->isOtp()); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function testRevokeSecret(): void |
51
|
|
|
{ |
52
|
|
|
$this->user->createOtpSecret('felix.lan'); |
53
|
|
|
$this->user->revokeOtpSecret(); |
54
|
|
|
|
55
|
|
|
self::assertFalse($this->user->isOtp()); |
56
|
|
|
self::assertNull($this->user->getOtpUri()); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function testVerifySecret(): void |
60
|
|
|
{ |
61
|
|
|
$this->user->setOtp(false); |
62
|
|
|
self::assertFalse($this->user->verifyOtp('123456'), 'Cannot verify OTP with 2FA disabled'); |
63
|
|
|
|
64
|
|
|
$this->user->createOtpSecret('felix.lan'); |
65
|
|
|
$this->user->setOtp(true); |
66
|
|
|
|
67
|
|
|
self::assertFalse($this->user->verifyOtp('123456'), 'Wrong OTP given'); |
68
|
|
|
|
69
|
|
|
$uri = $this->user->getOtpUri(); |
70
|
|
|
self::assertNotNull($uri); |
71
|
|
|
|
72
|
|
|
$otp = Factory::loadFromProvisioningUri($uri); |
|
|
|
|
73
|
|
|
self::assertInstanceOf(TOTPInterface::class, $otp); |
74
|
|
|
self::assertTrue($this->user->verifyOtp($otp->now()), 'Correct OTP given'); |
|
|
|
|
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|