Skip to content

Commit

Permalink
Show default message for UnauthorizedException (#123)
Browse files Browse the repository at this point in the history
* Add regression test for default unauthorized message

* Pass default message correctly
  • Loading branch information
erikgaal committed Sep 9, 2019
1 parent 2986922 commit 34386ac
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 10 deletions.
6 changes: 4 additions & 2 deletions src/Exceptions/UnauthorizedException.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@

class UnauthorizedException extends UserError
{
public function __construct($message = 'This action is unauthorized.', $code = 0, Throwable $previous = null)
public function __construct($message = null, $code = null, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
parent::__construct($message ?: 'This action is unauthorized.', 0, $previous);

$this->code = $code ?: 0;
}
}
29 changes: 22 additions & 7 deletions tests/Feature/CustomMutationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,32 @@ public function it_validates_a_custom_mutation()
}

/** @test */
public function it_checks_authorization_for_a_custom_mutation()
public function it_checks_authorization()
{
$this->withExceptionHandling();
$this->graphql('mutation($input: InviteUserInput!) { inviteUser(input: $input) }', [
'input' => [
'email' => 'john@example.com',
],
])->assertJsonFragment(['message' => 'You need to be logged in to do this!']);
$this->withExceptionHandling()
->graphql('mutation($input: InviteUserInput!) { inviteUser(input: $input) }', [
'input' => ['email' => 'john@example.com'],
])->assertJsonFragment(['message' => 'This action is unauthorized.']);

$this->assertDatabaseMissing('users', [
'email' => 'invalid-email',
]);
}

/** @test */
public function it_checks_authorization_and_shows_custom_message()
{
$_SERVER['graphql.inviteUser.authorize'] = 'You need to be logged in to do this!';

$this->withExceptionHandling()
->graphql('mutation($input: InviteUserInput!) { inviteUser(input: $input) }', [
'input' => ['email' => 'fail@example.com'],
])->assertJsonFragment(['message' => 'You need to be logged in to do this!']);

$this->assertDatabaseMissing('users', [
'email' => 'invalid-email',
]);

unset($_SERVER['graphql.inviteUser.authorize']);
}
}
2 changes: 1 addition & 1 deletion tests/Fixtures/Mutations/InviteUserMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function attributes()
public function authorize()
{
if (! auth()->user()) {
return $this->deny('You need to be logged in to do this!');
return $this->deny($_SERVER['graphql.inviteUser.authorize'] ?? null);
}

return true;
Expand Down

0 comments on commit 34386ac

Please sign in to comment.