Skip to content
This repository was archived by the owner on Feb 19, 2025. It is now read-only.

Commit

Permalink
Adds ability to set a user to act as for a given set of requests
Browse files Browse the repository at this point in the history
This is very rudimentary right now and only supports the session driver, but more support will come as needed
  • Loading branch information
craigpaul committed Aug 26, 2024
1 parent 310cf8e commit 5651c52
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Exceptions/UnsupportedAuthenticationGuardException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace CraigPaul\Blitz;

use Exception;

class UnsupportedAuthenticationGuardException extends Exception
{
/**
* Create a new exception instance.
*
* @param string $guard
*
* @return void
*/
public function __construct(string $guard)
{
parent::__construct("Unsupported authentication guard: {$guard}");
}
}
32 changes: 32 additions & 0 deletions src/Testing/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@
use function array_map;
use function base64_encode;
use function count;

use CraigPaul\Blitz\UnsupportedAuthenticationGuardException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Cookie\CookieValuePrefix;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Session;
use InvalidArgumentException;

abstract class TestCase
Expand Down Expand Up @@ -227,6 +233,32 @@ public function disableCookieEncryption(): self
return $this;
}

/**
* Set the currently logged in user for the request.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param null|string $guard
*
* @return $this
*
* @throws \CraigPaul\Blitz\UnsupportedAuthenticationGuardException
*/
public function actingAs(Authenticatable $user, ?string $guard = null)
{
$guard = $guard ?: Config::get('auth.defaults.guard');

Auth::guard($guard)->login($user);

Session::save();

match (Config::get('auth.guards.' . $guard . '.driver')) {
'session' => $this->withCookie(Config::get('session.cookie'), Session::getId()),
default => throw new UnsupportedAuthenticationGuardException($guard),
};

return $this;
}

/**
* Include histogram buckets for grouping response times.
*
Expand Down

0 comments on commit 5651c52

Please sign in to comment.