User Permissions
Snipe-IT uses Policies to determine whether a user should be able to view, edit, delete, etc a resource.
The policies are location in app/Policies
, and extend from app/Policies/SnipePermissionsPolicy.php
, which does the more complex work of determining whether or not a user should be able to perform a specific action.
To utilize these policies in a controller method, you would use something like:
public function audit() {
$this->authorize('audit', Asset::class);
// Do authorized stuff here
}
If the authorization fails, it will return a forbidden error.
When editing blades, you can use the @can
and @cannot
short syntax.
For example, to determine whether or not to display the option to a logged in user, you would write:
...
@can('view', \App\Models\Asset::class)
<li>
<a href="{{ route('assets.index') }}">
<span>Assets</span>
</a>
</li>
@endcan
...
Creating New Permissions
If you're creating a new model or permission set, there are a few steps you have to take before all of these pieces work together.
SnipePermissionsPolicy
provides methods for handling the granular permissions used throughout Snipe-IT.
Each "area" of a permission (which is usually a model, like Assets, Departments, etc), has a setting in config/permissions.php
like view
/create
/edit
/delete
(and sometimes some extra stuff like checkout
/checkin
, etc.)
A Policy should exist for each of these models, however if they only use the standard view
/create
/edit
/delete
, the policy can be pretty simple, for example with just one method setting the column name. Let's say we're creating a new permission mask for a new model named Florb
.
We'll need to create a new Policy in app/Policies
, named FlorbPolicy
:
<?php
namespace App\Policies;
use App\Policies\SnipePermissionsPolicy;
class FlorbPolicy extends SnipePermissionsPolicy
{
protected function columnName()
{
return 'florbs';
}
}
We'll also need to tell the AuthServiceProvider to take that new policy into consideration. In app/Providers/AuthServiceProvider.php
, we'll need to make sure we add use App\Models\Florb
and App\Policies\FlorbPolicy
- and then add the new policy into the protected $policies
array:
<?php
namespace App\Providers;
use App\Models\Florb;
use App\Policies\FlorbPolicy;
...
/**
* The policy mappings for the application.
*
* See SnipePermissionsPolicy for additional information.
*
* @var array
*/
protected $policies = [
...
Florb::class => FlorbPolicy::class,
...
];
...
Permissions Considerations
While handling permissions is usually pretty straightforward, there are some areas where it can get a little complicated, not from a programming perspective, but from a logic perspective. For example, if a user can checkout assets, they inherently have to be able to view a list of users, locations and other assets, so that they can select them in the checkout interface.
Be sure to think though the implications of any permission policies you implement.
Updated over 5 years ago