Skip to content

Instantly share code, notes, and snippets.

@jgrossi
Last active August 14, 2021 18:14
Show Gist options
  • Save jgrossi/4b1364e20418eca3ca937e70550c1823 to your computer and use it in GitHub Desktop.
Save jgrossi/4b1364e20418eca3ca937e70550c1823 to your computer and use it in GitHub Desktop.

Revisions

  1. jgrossi revised this gist Sep 20, 2017. 1 changed file with 17 additions and 1 deletion.
    18 changes: 17 additions & 1 deletion AttachJwtToken.php
    Original file line number Diff line number Diff line change
    @@ -7,12 +7,28 @@

    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 = factory(User::class)->create([
    $user = $this->loginUser ?: factory(User::class)->create([
    'company_id' => null,
    ]);

  2. jgrossi created this gist Sep 20, 2017.
    61 changes: 61 additions & 0 deletions AttachJwtToken.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    <?php

    namespace Tests\Concerns;

    use App\Models\User;
    use Tymon\JWTAuth\Facades\JWTAuth;

    trait AttachJwtToken
    {
    /**
    * @return string
    */
    protected function getJwtToken()
    {
    $user = 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(),
    ]));
    }
    }