Skip to content

Authorization

Introduction

OTAS has two types of authorization currently, one provided by a plugin called Keerill.Users and it used on more the 95% of the system for managing permissions. the second way is used for more complex logic via Auth Policies.

OTAS Method

The normal method for Authorization you'll see on most of the pages is using if statements and filtering user permissions like:

$user_permissions = $this->user->permissions;
if(!in_array('some_permission',array_keys($user_permissions))){
if(in_array('r',array_keys($user_permissions))){
return Redirect::to('dashboard');
}else{
return Redirect::to('/');
}
}

r letter means read/view permission. and c, u, d are for create, update, delete respectively.

Better Method

A better method of this is using the can and cannot methods on the User model. which is the instance you get when you sign in or in $this->user object. so the above code will shortened to:

if ($this->user->cannot('some_permission', 'view')) { // $this->user->can('some_permission', 'view') opposite
return Redirect::to('dashboard');
}

and the second argument is optional here, because the default value is view already, but you can change to (create, update, or delete).

Auth Policies

Policies are classes that just encapsulate the authorization logic behind methods and make it easier to check them in pages and models. to make a policy you need to create a class that extends Support\Policies\Policy abstract class and then define the methods corresponding to the permission name containing the appropriate logic, then you can pass any payload in the resources array, e.g:

use Support\Policies\Policy;
 
class PostPolicy extends Policy
{
public function edit()
{
return $this->user->isAdmin() || $this->user->id === $this->resources['post']->author_id;
}
 
public function publish()
{
return $this->user->isAdmin() && !$this->resources['post']->is_private;
}
}

then when you need to use it:

use TheNamespace\PostPolicy;
 
function onEdit()
{
$post = /* find post by id */;
// Both resources & user are optional, if there is resources needed
// or if you want to change the user to check from the default logged in
$editPolicy = new PostPolicy(action: 'edit', resources: ['post' => $post], user: $this->user);
$publishPolicy = new PostPolicy(action: 'publish', resources: ['post' => $post]);
 
if ($editPolicy->allows()) {
//...
}
 
if ($publishPolicy->denies()) { // As the opposite check
//...
}
}