Skip to content

Commit

Permalink
add test for qr generation
Browse files Browse the repository at this point in the history
  • Loading branch information
imorland committed Nov 8, 2023
1 parent 6186d8b commit 9d0428a
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Model/TwoFactor.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ class TwoFactor extends AbstractModel
*/
protected $fillable = ['user_id', 'secret', 'backup_codes', 'is_active']; // Add other fields as necessary

public $casts = [
'is_active' => 'boolean',
];

/**
* Get the user that owns this 2FA entry.
*/
Expand Down
62 changes: 62 additions & 0 deletions tests/integration/api/ShowQrCodeControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace IanM\TwoFactor\Tests\integration\api;

use Carbon\Carbon;
use Flarum\Extend;
use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase;
use IanM\TwoFactor\Model\TwoFactor;

class ShowQrCodeControllerTest extends TestCase
{
use RetrievesAuthorizedUsers;

public function setUp(): void
{
parent::setUp();

$this->extension('ianm-twofactor');

$this->prepareDatabase([
'users' => [
$this->normalUser(),
['id' => 3, 'username' => 'normal2', 'password' => '$2y$10$LO59tiT7uggl6Oe23o/O6.utnF6ipngYjvMvaxo1TciKqBttDNKim', 'email' => '[email protected]', 'is_email_confirmed' => 1,
]
],
'two_factor' => [
['id' => 1, 'user_id' => 2, 'secret' => 'OIZ2R42HL2ZNUJNJU72P4EK26CQSD5JLEC7AVH7BCBJKRCUBUPLHXQ4TCAYVFZPDAGH3QDPHWABLMT36QAKTIFPNL5NKTR2BGVIY3GY', 'backup_codes' => '["$2y$10$8UDXx3Fbx\/K9uKHs.4wq8OIP3\/q.0PghYhX\/v9ckHmvXwY2yUI.IC","$2y$10$KWw6OT18AMWa\/T1NcS1hjOiMfuzq45L1KKsFUBXAIjKTsvXJcUEOW"]', 'is_active' => true, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
]
]);
}

/**
* @test
*/
public function user_can_generate_qr_code()
{
$response = $this->send(
$this->request('GET', '/api/users/3/twofactor/qrcode', [
'authenticatedAs' => 3,
])
);

$this->assertEquals(200, $response->getStatusCode());

$body = (string) $response->getBody();
$this->assertJson($body);

$data = json_decode($body, true);
$this->assertArrayHasKey('svg', $data);
$this->assertArrayHasKey('code', $data);

$this->assertStringContainsString('data:image/png;base64,', $data['svg']);
$this->assertNotEmpty($data['code']);

$twoFactor = TwoFactor::query()->where('user_id', 3)->first();

$this->assertNotNull($twoFactor);
$this->assertEquals($data['code'], $twoFactor->secret);
$this->assertFalse($twoFactor->is_active);
}
}

0 comments on commit 9d0428a

Please sign in to comment.