Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/SGRD-4_add-usage-test-case-functions-to-generate-jwt-trait #3

Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Test

on:
push:
branches:
- main

tags:
- v*

pull_request:

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- uses: "shivammathur/setup-php@v2"
with:
php-version: "8.1"
- uses: "ramsey/composer-install@v2"

- name: Run PHPCS
run: |
composer run-script lint

- name: Run tests
run: |
composer run-script test
53 changes: 52 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- [Add new custom guard](#add-new-custom-guard)
- [Usage example](#usage-example)
- [Testing](#testing)
- [HTTP testing](#http-testing)

## Installation

Expand Down Expand Up @@ -73,7 +74,7 @@ class CustomTest extends TestCase

public function testThatIAmActingAsUser(): void
{
$user = User::create();
$user = User::factory()->create();

$this->withAccessTokenFor($user);

Expand All @@ -82,3 +83,53 @@ class CustomTest extends TestCase
}
}
```

### HTTP testing

`withAccessTokenFor` method is adding the `Bearer` token to `headers` which are sent by http tests. But you need to specify the server url somewhere on your tests. eg. `tests/CreatesApplication`:

```php
<?php
use Supaapps\Guard\Tests\Concerns\GenerateJwtToken;

trait CreatesApplication
{
use GenerateJwtToken;

public function createApplication(): Application
{
...

$this->setAuthServerUrl();
return $app;
}
}
```

Next run your http tests, for example:

```php
<?php

namespace Tests\Feature;

use Tests\TestCase;

class CustomTest extends TestCase
{
public function itReturnsTheAuthUser(): void
{
$user = User::factory()->create();

$this->withAccessTokenFor($user);

// assume you have /user endpoint that
// - uses auth:jwt middleware
// - and returns auth user
$response = $this->getJson('/user');

$response->assertOk()
->assertJson($user->toArray());
}
}
```
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@
},
"require-dev": {
"orchestra/testbench": "^8.21",
"nunomaduro/collision": "^7.8"
"nunomaduro/collision": "^7.8",
"squizlabs/php_codesniffer": "^3.8"
},
"autoload-dev": {
"psr-4": {
Expand All @@ -57,7 +58,7 @@
"@php vendor/bin/testbench serve"
],
"lint": [
"@php vendor/bin/phpstan analyse"
"@php vendor/bin/phpcs src tests config -v"
],
"test": [
"@php vendor/bin/testbench package:test"
Expand Down
82 changes: 81 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions config/sguard.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

/*
* supaapps/supaapps-guard package
*/
Expand Down
13 changes: 4 additions & 9 deletions src/Auth/JwtAuthDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
use Illuminate\Support\Facades\Cache;
use stdClass;

/**
*
*/
class JwtAuthDriver implements Guard
{
use GuardHelpers;
Expand Down Expand Up @@ -101,7 +98,7 @@ public function user()
*/
public function fetchPublicKey()
{
$url = rtrim(config('sguard.auth_server_url'),'/') . '/keys/public_key';
$url = rtrim(config('sguard.auth_server_url'), '/') . '/keys/public_key';
return file_get_contents($url);
}

Expand All @@ -110,7 +107,7 @@ public function fetchPublicKey()
*/
public function fetchAlgo()
{
$url = rtrim(config('sguard.auth_server_url'),'/') . '/keys/algo';
$url = rtrim(config('sguard.auth_server_url'), '/') . '/keys/algo';
return file_get_contents($url);
}

Expand All @@ -135,25 +132,23 @@ public function validate(array $credentials = [])
return $this->fetchAlgo();
});
$this->jwtPayload = JWT::decode($bearerToken, new Key(trim($publicKey), trim($algorithm)));
if ( config('sguard.realm_name') !== $this->jwtPayload->aud) {
if (config('sguard.realm_name') !== $this->jwtPayload->aud) {
throw new AuthenticationException('Auth error - realm mismatch');
}
$this->firstName = $this->jwtPayload->first_name;
$this->lastName = $this->jwtPayload->last_name;
$this->email = $this->jwtPayload->email;
$this->scopesArray = explode(' ', $this->jwtPayload->scopes);
$this->scopes = $this->jwtPayload->scopes;
if (strpos($this->scopes, '/' . config('sguard.realm_name') .'/*') !== false) {
if (strpos($this->scopes, '/' . config('sguard.realm_name') . '/*') !== false) {
$this->admin = true;
} else {
$this->admin = false;
}

} catch (\Throwable $ex) {
throw new AuthenticationException('Auth error - ' . $ex->getMessage());
}


return true;
}

Expand Down
2 changes: 0 additions & 2 deletions src/GuardServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,4 @@ public function register(): void
{
$this->mergeConfigFrom(__DIR__ . '/../config/sguard.php', 'sguard');
}


}
11 changes: 11 additions & 0 deletions src/Tests/Concerns/GenerateJwtToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@

use Firebase\JWT\JWT;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;

trait GenerateJwtToken
{
use MakesHttpRequests;

public function withAccessTokenFor(Authenticatable $user, array $payload = []): string
{
$accessToken = $this->generateTestingJwtToken($payload + [
Expand All @@ -18,6 +22,8 @@ public function withAccessTokenFor(Authenticatable $user, array $payload = []):
'Authorization' => "Bearer {$accessToken}"
]);

$this->withToken($accessToken);

return $accessToken;
}

Expand All @@ -42,4 +48,9 @@ public function generateTestingJwtToken(array $payload = []): string
File::get(__DIR__ . '/../../../tests/keys/algo')
);
}

public function setAuthServerUrl()
{
Config::set('sguard.auth_server_url', __DIR__ . '/../../../tests');
}
}
6 changes: 4 additions & 2 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@

class TestCase extends BaseTestCase
{
use RefreshDatabase, GenerateJwtToken;
use RefreshDatabase;
use GenerateJwtToken;

protected function getPackageProviders($app)
{
Expand All @@ -27,7 +28,8 @@ protected function getEnvironmentSetUp($app)
'driver' => 'supaapps-guard',
'provider' => 'users',
]);
$app['config']->set('sguard.auth_server_url', __DIR__);

$this->setAuthServerUrl();

$app->afterResolving('migrator', static function ($migrator) {
$migrator->path(laravel_migration_path());
Expand Down
Loading