Skip to content
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

[8.x] Adds on-demand authorization check #39778

Closed
wants to merge 11 commits into from
Closed

[8.x] Adds on-demand authorization check #39778

wants to merge 11 commits into from

Conversation

DarkGhostHunter
Copy link
Contributor

@DarkGhostHunter DarkGhostHunter commented Nov 25, 2021

What

Allows the developer to throw an AuthotizationException using a condition, bypassing before/after callbacks or registering a gate or policy that's only used once.

Before:

if (auth()->user()->comments()->count() > 3) {
    throw new AuthorizationException();
}

After:

Gate::authorizeUnless(auth()->user()->comments()->count() > 3);

It also supports callbacks, which allows to use the authenticated user as parameter, and a message with a code.

Gate::authorizeIf(function ($user) {
    return $user->comments()->count() < 2;
}, "You have allocated all of your comments", 406);

And supports using the Response itself as a callback result. When doing so, it can override the false/truthy result, giving more control on the callback.

Gate::authorizeUnless(function ($user) {
    if ($user->notPremium()) {
        return Response::deny('You have to activate your account before commenting');
    }

    return $user->comments()->count() > 3;
}, "You have allocated all of your comments", 406);

Includes authorizeIf() and authorizeUnless() to do the opposite.

BC?

None, only additive.

@DarkGhostHunter
Copy link
Contributor Author

If you're asking why I made so much commits, it's because I used VSCode Web on a tablet.

@taylorotwell
Copy link
Member

Doesn't read right to me? If sounds like the user will be authorized if the condition is truthy, but they will actually be denied.

@taylorotwell taylorotwell marked this pull request as draft November 26, 2021 15:29
@DarkGhostHunter
Copy link
Contributor Author

Fucked up the example. Now is understandable.

@DarkGhostHunter
Copy link
Contributor Author

Gonna scrap this and add this functionality to authorize() itself, because you can do something similar with throw_if() and throw_unless().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants