-
-
Save whoisryosuke/537d81e8279ba1c4b13ca71413531ef2 to your computer and use it in GitHub Desktop.
AttachJwtToken.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace Tests\Traits; | |
| use App\User; | |
| 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([ | |
| 'role' => 'customer', | |
| ]); | |
| return $user->createToken('Kushy Test API', [])->accessToken; | |
| } | |
| /** | |
| * @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(), | |
| ])); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment