Currently, I have a system in with I have two completely separate entities Users
and Admins
each with their own table.
Within the admins
table, there is a field for access_level
as the admins can themselves have different access levels in terms of what they can see and manage. For instance, only admins with an access level of admin can create new admins.
Middleware seemed the best bet for this.
In my Admin Model I have the following methods:
/**
* Check whether this admin has full admin status
*
* @return void
*/
public function getIsAdminAttribute()
{
return $this->access_level == 'admin' ? true : false;
}
/**
* Check whether this user has Partial status
*
* @return void
*/
public function getIsFullAttribute()
{
return $this->access_level == 'full' ? true : false;
}
/**
* Check whether this user has Partial status
*
* @return void
*/
public function getIsPartialAttribute()
{
return $this->access_level == 'partial' ? true : false;
}
/**
* Check whether this admin has a particular role
*
* @param [type] $role
* @return void
*/
public function getHasRoleAttribute($role)
{
if($this->access_level == $role){
return true;
}
return false;
}
So now I have access to the accessors is_admin, is_partial, is_full
to check the currently logged in admin's permission. I also have a method to check if an admin has a given role.
My Middleware, which I have called Role
looks like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class Role
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $roles)
{
if (Auth::guard('admin')->user()) {
$user = Auth::guard('admin')->user();
if ($user->is_admin) {
return $next($request);
foreach($roles as $role){
// Check whether user has a given role
if($user->has_role($role)){
return $next($request);
}
}
}
}
return response('You do not have permission to perform this action', 401);
}
}
In routes/web.php
I then use it like this:
Route::get('/vacancies', 'JobPostController@index')->name('vacancies.index')->middleware('role:partial');
But when I assign myself partial, I get a 401 error was visiting the route.
The roles are within the admin table as there will only ever be 3 roles and they'll always be tied to admins.