Anyone new to RBAC I highly suggest using laravel's or Spatie https://github.com/spatie/laravel-permission
However being familiar with RBAC I use built in authentication but have custom authorization.
I use static helper classes, but instance will also work. And these are just simple examples of making sure a required role of a method matches with one of the logged in users role.
I have a role field in users table like:
role
-------------
admin
bkeep // for bookkeeper
admin,bkeep // both roles
user
Make whatever helper or service class you desire.
In a helper class I have:
public static function chkRole($role = null)
{
$userrole = Auth::user()->role;
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return true;
}
return false;
}
Usage at method level:
public function indexAdmin()
{
if (!ChkAuth::chkRole('admin')) {
return redirect('indexbl'); // whereever you redirect
}
// rest of method if role matches.
Example in an edit method
$petid = $request->input('petid');
$pet = Pet::find($petid);
ChkAuth::chkUserId($pet->owner_id);
// owner_id is FK
And helper method that verifies this:
public static function chkUserId($userid)
{
if ($userid === Auth::user()->id || self::chkRole('admin') === true) {
return;
} else {
die(redirect('/login')); // where ever you redirect to
}
return false;
}
Note above die should never be called unless a user tries to enter another id in the url which can happen.
Notice this line:
if ($userid === Auth::user()->id || self::chkRole('admin') === true) {
It's for a situation where user can handle their own data, but an admin can see and edit all. For that a scope is handy:
Scope example:
public function scopegetPets($query, $petsearch = '')
{
$petsearch = $petsearch . "%";
$query->where('petname', 'like', $petsearch);
if (ChkAuth::chkRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
$results = $query->orderBy('petname', 'asc')->paginate(5);
return $results;
}
if (ChkAuth::chkRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid); //whatever fk used
}
Is user if a regular user, but not part of query if admin, since admin can see or edit all.
These are just a few ways to use out of box authentication with some custom authorization.
This is not a class to use, just examples. If you use custom RBAC add more custom methods as needed in your custom class.
Also a true false can be used to verify the correct user is viewing or editing:
Or if checking user only, leave out the admin part:
Called via:
Of course a combination of custom authorization and middleware can be used. Again just examples here.