Home  >  Article  >  PHP Framework  >  Let's talk about interceptors (Gates) in Laravel

Let's talk about interceptors (Gates) in Laravel

青灯夜游
青灯夜游forward
2022-09-28 19:59:341672browse

Let's talk about interceptors (Gates) in Laravel

Laravel Gates (interceptors) allow you to authorize users to access certain areas of your application. You can easily define interceptors in your application and then use them to allow or deny access.

Simple example

Suppose in the user table, there is a column named admin, depending on whether the user is an administrator, it can be 1 or 0. We can easily secure a module that is part of the application with a simple check like this:

Route::get('administration', function(){
    if(auth()->check() && auth()->user()->admin){
        echo 'Welcome to the admin section';
    } else {
        echo 'You shall not pass';
    }
});

If a specific user has their admin line set to 1, they will see the following output.

Admin access screenshot

Otherwise, they will see the following:

Admin denied access

This looks great right! We have an easy way to allow or deny access to specific parts of our application. However, the problem is: what if there are a large number of places throughout the application where user access permissions need to be checked and modified. We would have to search the code globally and modify this logic everywhere. Not very efficient.

For this, we can define a Gate (interceptor) and use it throughout the application.

Define the interceptor

To define the interceptor, you can open the App\Providers\AuthServiceProvider.php file and in our boot () Add the following content to the method:

public function boot()
{
    $this->registerPolicies();

    Gate::define('access-admin', function ($user) {
        return $user->admin;
    });
}

We can use this interceptor anywhere in the entire application where we want to authenticate the administrator user. In the next section you'll see how we use this new interceptor.

Using interceptors

To use interceptors, we can call Gate::allows() or Gate::denies( ) method, as shown below:

Route::get('administration', function(){
    if (Gate::allows('access-admin')) {
        echo 'Welcome to the admin section';
    } else {
        echo 'You shall not pass';
    }
});

Please note: Gate::denies() method will do Gate::allows() The benefit of performing a reverse check

interceptor is that we can now change our definition at any time and the authorization logic will be changed synchronously throughout the application.

Another purpose of using interceptors is to check permissions related to data. Taking a blog as an example, we can grant users editing permissions on posts they create.

We can pass data to the interceptor to check if the user has permission to perform an action.

Passing data like an interceptor

Suppose our application has a Post table with a column user_id, It contains the ID of the user who created it. We can define a Gate (interceptor) to determine if a user can edit a specific post like this:

Gate::define('edit-post', function ($user, $post) {
    return $user->id === $post->user_id;
});

Two parameters are passed to our interceptor definition. The first is the $user object, which contains the authenticated user, and the second parameter is our $post object.

Tips: If there is no authenticated user, the interceptor will return false.

The interceptor will allow access if the authenticated user is the original author; otherwise it will deny access.

Here's a quick example of how we can use the new edit-post interceptor.

Route::get('edit/{id}', function($id){

    $post = \App\Model\Post::find($id);

    if( Gate::allows('edit-post', $post) ){
        echo 'You can edit this post';
    } else {
        echo 'You shall not pass';
    }

});

Above, we used Route Closures in the example, but we may want to map this route to a controller. This will also let us use the new Authorize function.

Authorize Authorization Helper Function

In addition to efficiency, another reason to use interceptors is the helper function.

Assume we map the route to the controller:

Route::get('edit/{id}', 'PostController@edit');

We can use the authorize() helper to check if the authenticated user has permission to edit the post:

<?php namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function edit($id){

        $post = Post::find($id);
        $this->authorize('edit-post', $post);

    }
}

If the controller inherits from the App\Http\Controllers\Controller base class, you can use the function just like the Gate::allow() function authorize() Helper function.

Finally, what if we want to check authorization in the view? We can do this using the @can Blade function helper.

Authentication at the view layer

Assume that the Blade view is as follows:

nbsp;html>


    <meta>
    <meta>
    <title>{{ $post->title }}</title>


    <h1>{{ $post->title }}</h1>
    <p>{!! $post->body !!}</p>

We can use the Blade helper function@can Check if the current user is allowed to edit this post:

nbsp;html>


    <meta>
    <meta>
    <title>{{ $post->title }}</title>


    <h1>{{ $post->title }}</h1>
    <p>{!! $post->body !!}</p>

    @can('edit-post', $post)
        id }}">Edit Post
    @endcan


If the authenticated user is the original author of the post, they will see an Edit Post button.

Using the @can helper function can make our code easier to read and manage. You can also use @cannot to reverse the operation.

Summary

This is the basics of using Gates (interceptors) in Laravel applications. Interceptors allow us to easily authorize specific users to access areas of our application. This may also be called an Access Control List (ACL), a list of permissions associated with an object.

But we shouldn't overcomplicate things... In the simplest scenario, Interceptors are used to allow or deny access. Users can either be allowed authorization or be denied authorization.

Since this tutorial is about getting the user through and not through... it makes sense to send you out with this image of Gandalf from Lord of the Rings (manual dog head).

Lets talk about interceptors (Gates) in Laravel

To learn more about Laravel Gates (interceptors), be sure to visit the Larav authorization documentation.

English original address: https://devdojo.com/tnylea/laravel-gates

Translation address: https://learnku.com/laravel/t/67585

[Related recommendations: laravel video tutorial]

The above is the detailed content of Let's talk about interceptors (Gates) in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete