Skip to content

Instantly share code, notes, and snippets.

@salipro4ever
Last active March 21, 2018 07:54
Show Gist options
  • Save salipro4ever/bfd76ffc37043b39f1428228e4536249 to your computer and use it in GitHub Desktop.
Save salipro4ever/bfd76ffc37043b39f1428228e4536249 to your computer and use it in GitHub Desktop.
Understanding about authorization laravel 5.5

Concepts

Laravel's authorization is built around 2 main concepts:

  1. A Gate class The gate is the official authority on who has what ability (i.e. who can do what). You use the gate to register a user's abilities, and later check the gate if the user can perform a given action.
  2. Policy classes Policies are responsible for checking abilities on a single model type. For each model class in your system you want to authorize against, you'll have a matching policy class.

Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource.

Usage

To start testing for this, we need login method first (just run php artisan make:auth)

Official

ref https://laravel.com/docs/5.5/authorization#writing-gates

Note

Gate thường dùng để ngăn chặn từ đầu, k phải để giới hạn Không cần nhất thiết phải map với model, chỉ cần call đúng name Có thể truyền nhiều params vào Gate

Gate::define('xxx', function ($user, $a, $b) { ... });
Gate::allows('xxx', [$a , $b]);

Khi trùng tên với một Policy, Gate sẽ không được chạy Nếu đã map một Model đên Policy in AuthServiceProvider.php, param đầu tiên sẽ chỉ định Policy thực thi (like Policy)

protected $policies = [
    Post::class => PostPolicy::class
];
// using
#method xxx in PostPolicy sẽ được thực thi, mặc cho Gate::define có dc định nghĩa hay không.
$post = \App\Post;
Gate::allows('xxx', [$post , $b]);

Có thể dùng @can in blade, middleware in route, $this->authorize() in controller, $user->can() Gate::allows co thể dùng check Policy luôn nhá

@salipro4ever
Copy link
Author

salipro4ever commented Mar 21, 2018

role + permission vs Gates from db

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


        foreach($this->getPermissions() as $permission) {
            $gate->define($permission->name, function($user) {
                $user->hasRole($permission->roles);
            });
        }
}

protected function getPermissions() {
        return Permission::with('roles')->get();
}

@salipro4ever
Copy link
Author

salipro4ever commented Mar 21, 2018

Handle exception authorization, in app/Exceptions/Handler.php

use Illuminate\Auth\Access\AuthorizationException;
if($exception instanceof AuthorizationException) {
      return redirect('/xxx');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment