Skip to content

[12.x] Introducing authorizeAfterValidation #55798

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 12.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/Illuminate/Validation/ValidatesWhenResolvedTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ public function validateResolved()
{
$this->prepareForValidation();

if (! $this->passesAuthorization()) {
$authorizeAfterValidation = $this->authorizeAfterValidation();

if (! $authorizeAfterValidation && ! $this->passesAuthorization()) {
$this->failedAuthorization();
}

Expand All @@ -32,6 +34,10 @@ public function validateResolved()
$this->failedValidation($instance);
}

if ($authorizeAfterValidation && ! $this->passesAuthorization()) {
$this->failedAuthorization();
}

$this->passedValidation();
}

Expand Down Expand Up @@ -105,4 +111,14 @@ protected function failedAuthorization()
{
throw new UnauthorizedException;
}

/**
* Determine if the request should verify the authorization only after validation.
*
* @return bool
*/
protected function authorizeAfterValidation()
{
return false;
}
}
28 changes: 28 additions & 0 deletions tests/Foundation/FoundationFormRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ public function testValidateThrowsExceptionFromAuthorizationResponse()
$this->createRequest([], FoundationTestFormRequestForbiddenWithResponseStub::class)->validateResolved();
}

public function testValidateThrowsNoAuthorizationExceptionIfValidationFails()
{
$this->expectException(ValidationException::class);
$this->expectExceptionMessage('error');

$request = $this->createRequest([], FoundationTestFormRequestAuthorizeAfterValidation::class);

$request->validateResolved();
}

public function testValidateDoesntThrowExceptionFromResponseAllowed()
{
$this->createRequest([], FoundationTestFormRequestPassesWithResponseStub::class)->validateResolved();
Expand Down Expand Up @@ -437,6 +447,24 @@ public function passedValidation()
}
}

class FoundationTestFormRequestAuthorizeAfterValidation extends FormRequest
{
public function authorize()
{
return Response::deny('foo');
}

public function rules()
{
return ['name' => 'required'];
}

protected function authorizeAfterValidation()
{
return true;
}
}

class FoundationTestFormRequestForbiddenWithResponseStub extends FormRequest
{
public function authorize()
Expand Down