Instantly share code, notes, and snippets.

Embed
What would you like to do?
AttachJwtToken.php
<?php
namespace Tests\Concerns;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
trait AttachJwtToken
{
/**
* @var User
*/
protected $loginUser;
/**
* @param User $user
* @return $this
*/
public function loginAs(User $user)
{
$this->loginUser = $user;
return $this;
}
/**
* @return string
*/
protected function getJwtToken()
{
$user = $this->loginUser ?: factory(User::class)->create([
'company_id' => null,
]);
return JWTAuth::fromUser($user);
}
/**
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $cookies
* @param array $files
* @param array $server
* @param string $content
* @return \Illuminate\Http\Response
*/
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
if ($this->requestNeedsToken($method, $uri)) {
$server = $this->attachToken($server);
}
return parent::call($method, $uri, $parameters, $cookies, $files, $server, $content);
}
/**
* @param string $method
* @param string $uri
* @return bool
*/
protected function requestNeedsToken($method, $uri)
{
return !('/auth/login' === $uri && 'POST' === $method);
}
/**
* @param array $server
* @return string
*/
protected function attachToken(array $server)
{
return array_merge($server, $this->transformHeadersToServerVars([
'Authorization' => 'Bearer ' . $this->getJwtToken(),
]));
}
}
@phegman

This comment has been minimized.

phegman commented Oct 22, 2018

Thanks, this is great! I had to make one small change (adding the default value to the $user parameter):

    /**
     * @param User $user
     * @return $this
     */
    public function loginAs(User $user = null)
    {
        $this->loginUser = $user;
        return $this;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment