dimanche 4 février 2018

How to authorise action against account that have multiple users in Laravel

The desired outcome would be that users can create account for company becoming first employee for that company having super-admin role. He then can create other employee accounts that have access to company account.

For that I have two models

  1. Team (the company account)
  2. User (the employee account)

and there is one-to-many relationship between team and user.

I have added global scope to User model in order to automatically load associated team so it would be easy to display necessary information in views.

The User model is authenticable.

Users can have different permissions. For example only super-admin is allowed to delete other user from team. I am following the Laravel way to authenticate action by using custom requests

public function destroy(DeleteTeamUserRequest $request, $id)
{
   $this->users->deleteById($id);
   return redirect()->route('dashboard')->withFlashSuccess('Deleted User');
}

class DeleteTeamUserRequest extends FormRequest
{
    public function authorize()
    {
        return $this->user()->isSuperAdmin();
    }
 }

This way I can be sure that user without super-admin role wouldnt delete other user. However theoretically super-admin of company 1 is able to to delete user form company 2. Of course he would never have that url in frontend but if he tempers the code he has the permission to delete all users.

I could always check in controller that given user is within the team but thats just wrong.

I made both Users and Teams authenticable (create another web guard for team), manually log in the team once user logs in (the same on logout) but came upon the same problem - I have to check if user I try to delete is within the same team as user that performs the action.

{
    public function authorize()
    {
        return $this->user()->isSuperAdmin()
            && $this->team()->has($otherUser); // I dont have other user here
    }
 }

The scenario should be quite common but I couldnt find a good explanation on how to properly handle these cases so I would highly appreciate any suggestions and help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire