jeudi 14 juillet 2016

Validate Authorization in Laravel 5.2

My roles are dynamic and their User's permission are also dynamic. I have two approaches to validate if the user is authorized to access the particular page.

Approach 1

class BaseController extends Controller
{
    public function __construct() {
        if(!\Auth::user()->IsPredefined) {
            $result = $this->ValidateAuthorization();
            if(!$result) {
                \Auth::logout();
                return redirect()->route("login");
            }
        }
    }

    private function ValidateAuthorization() {
        $ActionName = \Route::getCurrentRoute()->getPath();
        switch ($ActionName) {
            case "ChangePassword":
                $ModuleID = ModuleEnum::AccountManagemenet;
                $ActionID = AccountActionEnum::ChangePassword;
                return CheckUsePermissions($ModuleID, $ActionID);            
        }
    }

    private function CheckUsePermissions($ModuleID, $ActionID) {
        $User = MySession::UserPermissions();
        foreach($User->UserRolePermissions as $UserRolePermission) {
            $CurrentActionID = $UserRolePermission->RolePermission->Permission->ActionID;
            $CurrentModuleID = $UserRolePermission->RolePermission->Permission->ModuleID;
            if($CurrentActionID == $ActionID && $CurrentModuleID == $ModuleID && 
                    $UserRolePermission->IsActive == true) {
                return true;
            }
        }
        return false;
    }
}

Approach 2

Use Authorize method in Request class

public function authorize()
{
    return true;
}

Confusion

  1. If Approach 2 is good, should I create Request class for each Get, Put, Delete and POST?
  2. Is there any better approach to validate authorization?


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire