Using this-> authorize () policy, check in laravel controller inside store () method

So, I read about using laravel policies to grant permissions in the resources of my application, but there seems to be a problem there, although I followed the tutorial.

I have a user model that cannot be created via HTTP requests, except for other users who have the Entrust role for "Admin" or "Broker". What I understood and managed to get him to work on other activities, such as indexing users, was as follows:

  • Inside, AuthServiceProvider.phpinside a private array, $policiesI registered this user class with a class UserPolicylike this

    class AuthServiceProvider extends ServiceProvider {

             protected $policies = [
    
                 'App\Model' => 'App\Policies\ModelPolicy',
                  User::class => UserPolicy::class,
                  Insured::class => InsuredPolicy::class
            ];
    
            public function boot(GateContract $gate)
            {
                 $this->registerPolicies($gate);
            }
    

    }

  • UserPolicy

    UserPolicy {

    use HandlesAuthorization;
    
    protected $user;
    
    public function __construct(User $user) {
        $this->user = $user;
    }
    
    public function index(User $user) {
        $is_authorized = $user->hasRole('Admin');
        return $is_authorized;
    }
    
    public function show(User $user, User $user_res) {
    
        $is_authorized = ($user->id == $user_res->id);
        return $is_authorized;    
    }
    
    public function store() {
        $is_authorized = $user->hasRole('Admin');
        return $is_authorized;
    }
    

    }

  • UserController this->authorize(),

    UserController {

    public function index()
    {
        //temporary authentication here
        $users = User::all();
        $this->authorize('index', User::class);
        return $users;
    }
    
    public function show($id)
    {
        $user = User::find($id);
        $this->authorize('show', $user);
        return $user;
    }
    
    public function store(Request $request) {
    
    
        $user = new User;
        $user->name = $request->get('name');
        $user->email = $request->get('email');
        $user->password = \Hash::make($request->get('password'));
    
        $this->authorize('store', User::class);
    
        $user->save();
    
        return $user;
    
    }
    

    }

, $this->authorize() : .

authorize()

+4
1

store() UserPolicy::class :

public function store(User $user) {
   $is_authorized = $user->hasRole('Admin');
   return true;
}

User $user.

, .

+1

Source: https://habr.com/ru/post/1659258/


All Articles