Skip to content

Commit 136c232

Browse files
committed
Merge remote-tracking branch 'origin/main'
2 parents 96b1612 + 95eef25 commit 136c232

File tree

2 files changed

+181
-2
lines changed

2 files changed

+181
-2
lines changed

Diff for: src/HelpersServiceProvider.php

+8
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Illuminate\Support\Facades\Hash;
99
use Illuminate\Support\Facades\Validator;
1010
use Illuminate\Support\ServiceProvider;
11+
use Javaabu\Helpers\Http\Middleware\JsonOnly;
1112

1213
class HelpersServiceProvider extends ServiceProvider
1314
{
@@ -209,5 +210,12 @@ public function register()
209210
foreach (glob(app_path().'/Helpers/*.php') as $filename) {
210211
require_once($filename);
211212
}
213+
214+
$this->registerMiddlewareAliases();
215+
}
216+
217+
public function registerMiddlewareAliases(): void
218+
{
219+
app('router')->aliasMiddleware('json', JsonOnly::class);
212220
}
213221
}

Diff for: src/Testing/TestCase.php

+173-2
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,18 @@
44

55
use App\Models\User;
66
use Illuminate\Auth\Passwords\PasswordBrokerManager;
7+
use Illuminate\Cookie\CookieValuePrefix;
78
use Illuminate\Database\Eloquent\Factories\Factory;
89
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
910
use Illuminate\Support\Facades\Hash;
1011
use Illuminate\Support\Facades\Mail;
1112
use Illuminate\Support\Facades\Notification;
1213
use Illuminate\Support\Str;
14+
use Illuminate\Testing\TestResponse;
15+
use Laravel\Passport\ApiTokenCookieFactory;
16+
use Laravel\Passport\Client;
17+
use Laravel\Passport\ClientRepository;
18+
use Laravel\Passport\Passport;
1319
use Javaabu\Permissions\Models\Permission;
1420
use Spatie\Permission\PermissionRegistrar;
1521
use Javaabu\Permissions\Models\Role;
@@ -232,8 +238,8 @@ protected function getRole($role_name, $guard = 'web_admin'): Role
232238
{
233239
// find the role
234240
$role = Role::whereName($role_name)
235-
->whereGuardName($guard)
236-
->first();
241+
->whereGuardName($guard)
242+
->first();
237243

238244
// if missing, create
239245
if (! $role) {
@@ -283,4 +289,169 @@ protected function getFactory($class): Factory
283289

284290
return $factory;
285291
}
292+
293+
/**
294+
* Make a json API call
295+
*
296+
* @param $method
297+
* @param $uri
298+
* @param array $data
299+
* @param string $access_cookie
300+
* @param array $headers
301+
* @param array $cookies
302+
* @return TestResponse
303+
*/
304+
public function jsonApi($method, $uri, array $data = [], string $access_cookie = '', array $headers = [], array $cookies = [])
305+
{
306+
$files = $this->extractFilesFromDataArray($data);
307+
308+
$content = json_encode($data);
309+
310+
$headers = array_merge([
311+
'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
312+
'CONTENT_TYPE' => 'application/json',
313+
'Accept' => 'application/json',
314+
'X-CSRF-TOKEN' => session()->token(),
315+
], $headers);
316+
317+
$cookies = array_merge([
318+
Passport::cookie() => $access_cookie,
319+
], $cookies);
320+
321+
return $this->call(
322+
$method,
323+
$uri,
324+
[],
325+
$cookies,
326+
$files,
327+
$this->transformHeadersToServerVars($headers),
328+
$content
329+
);
330+
}
331+
332+
/**
333+
* Acting as a specific API user
334+
* @param mixed $email
335+
* @param array $scopes
336+
*/
337+
protected function actingAsApiUser($email, $scopes = ['read', 'write'])
338+
{
339+
$this->seedDatabase();
340+
341+
//find the user
342+
$user = is_object($email) ? $email : $this->getActiveAdminUser($email);
343+
344+
Passport::actingAs($user, $scopes);
345+
}
346+
347+
/**
348+
* Get an access token
349+
* @param string $grant_type
350+
* @param array $scopes
351+
* @param array $params
352+
* @param Client|null $client
353+
*/
354+
protected function getAccessToken(string $grant_type = 'client_credentials', array $scopes = ['read', 'write'], array $params = [], Client $client = null)
355+
{
356+
if (empty($client)) {
357+
// create a new client
358+
$user = $this->getActiveAdminUser('[email protected]');
359+
$client = (new ClientRepository())->create(
360+
$user->id,
361+
'Test Client',
362+
'http://localhost'
363+
);
364+
}
365+
366+
$request_params = array_merge([
367+
'client_id' => $client->id,
368+
'client_secret' => $client->secret,
369+
'grant_type' => $grant_type,
370+
'scope' => implode(' ', $scopes),
371+
], $params);
372+
373+
// make the request
374+
$response = $this->json('post', '/api/v1/oauth/token', $request_params)
375+
->assertStatus(200)
376+
->assertJsonStructure([
377+
'token_type',
378+
'expires_in',
379+
'access_token',
380+
]);
381+
382+
return ($response->json())['access_token'];
383+
}
384+
385+
/**
386+
* Get client access token
387+
* @param array $scopes
388+
* @return mixed
389+
*/
390+
protected function getClientAccessToken(array $scopes = ['read', 'write']): mixed
391+
{
392+
return $this->getAccessToken('client_credentials', $scopes);
393+
}
394+
395+
/**
396+
* Get client access token
397+
* @param $username
398+
* @param $user_type
399+
* @param string $password
400+
* @param array $scopes
401+
* @return mixed
402+
*/
403+
protected function getPasswordAccessToken($username, $user_type, string $password = 'Jv7528222', array $scopes = ['read', 'write']): mixed
404+
{
405+
// create a new password client
406+
$client = (new ClientRepository())->create(
407+
$this->getActiveAdminUser($username)->id,
408+
'Test Client',
409+
'http://localhost',
410+
false,
411+
true
412+
);
413+
414+
return $this->getAccessToken(
415+
'password',
416+
$scopes,
417+
compact('username', 'user_type', 'password'),
418+
$client
419+
);
420+
}
421+
422+
/**
423+
* Get user access token
424+
*
425+
* @param $email
426+
* @param array $scopes
427+
* @return mixed
428+
*/
429+
protected function getUserAccessToken($email, array $scopes = ['read', 'write']): mixed
430+
{
431+
$user = is_object($email) ? $email : $this->getActiveUser($email);
432+
return $this->getPasswordAccessToken($user->email, 'user', 'Jv7528222', $scopes);
433+
}
434+
435+
/**
436+
* With OAuth Cookie
437+
*
438+
* @param $user
439+
* @return string
440+
*/
441+
protected function getOAuthCookie($user)
442+
{
443+
$cookie_factory = new ApiTokenCookieFactory(app('config'), app('encrypter'));
444+
445+
// initialize the CSRF Token
446+
session()->start();
447+
448+
$identifier = ($user && $user->is_active) ? $user->getPassportCookieIdentifier() : null;
449+
450+
$cookie = $cookie_factory->make($identifier, session()->token());
451+
452+
return app('encrypter')->encrypt(
453+
CookieValuePrefix::create($cookie->getName(), app('encrypter')->getKey()).$cookie->getValue(),
454+
Passport::$unserializesCookies
455+
);
456+
}
286457
}

0 commit comments

Comments
 (0)