May 8, 2016
0
Level 4
Authorization with Roles in config file
Hi y'all,
I was looking for some lightweight Authorization package, where permissions are stored in config file rather than database and I couldn't find anything.
I tried it by myself and I now have this: config/permissions.php
<?php
return [
// ROLE: OWNER
'owner' => [
// /admin/artist
'admin.artist.create',
'admin.artist.read',
'admin.artist.update',
'admin.artist.delete',
// /admin/song
'admin.song.create',
'admin.song.read',
'admin.song.update',
'admin.song.delete',
// /admin/
],
// ROLE: ADMIN
'admin' => [
],
// ROLE: USER
'user' => [
]
];
AuthServiceProvider.php:
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
foreach ($this->getPermissions() as $permission => $role) {
$gate->define($permission, function ($user) use ($permission, $role) {
return $user->hasRole($role);
});
}
}
protected function getPermissions()
{
$configPermissions = Config::get('permissions');
$returnPermissions = [];
foreach ($configPermissions as $role => $permissions) {
foreach($permissions as $permission) {
$returnPermissions[$permission]['roles'][] = $role;
}
}
return $returnPermissions;
}
User.php model:
public function hasRole($role)
{
if (is_string($role)) {
return $this->roles->contains('name', $role);
}
foreach ($role as $r) {
if($this->hasRole($r)) {
return true;
}
}
}
I would love to enable wildcards in both ways (to be able declare * for owner and to be able to check if user can access ANY action on route). Also there is probably better way to do it, maybe collections instead of arrays, etc.
Also I would prefer structure like below, but I am unable to flatten it to dot notation :/ :
<?php
return [
// ROLE: OWNER
'owner' => [
'admin' => [
'artist' => [
'create',
'read',
'update',
'delete',
],
],
]
]
Please or to participate in this conversation.