简体   繁体   中英

how to use user authorize in laravel based on query select eloquent

So, to put it simply, suppose I have a members table with columns

[
  'id', 'name', 'phone', 'province'
]

Users table

[
  'id', 'email', 'password', 'role_id'
]

Operator access table

[
  'user_id', 'province'
]

Roles table

[
  'id', 'role'
]

For available roles (admin, operator)

Role admin can access all member data, while Role operators can access only one province

How to create an authorize checker if the user operator is not allowed to access / update / delete / store the members table apart from the province itself

Do I have to use Gate authorize? How to do it?

You could try this through the use of middleware: If the user has already been authenticated and within the middleware function, (pre-middleware action)

$user_role = Role::find(Auth::user()->role_id)->role;
if ($user_role == 'operator') {
    return response()->json([
        'message' => 'You do not have the permission to visit this resource'
    ], 401);
} else {
    // Move on to the request
}

You could modify this function as needed

You can check permission in middleware. if the page has permission is accessable to user or not

public function handle($request, Closure $next)
    {
        $user = Auth::guard('admin')->user();
           
        if ($user->role == 0) {   //Allow all for Admin
            return $next($request);
        }

        $role = Role::where('_id', $user->role)->first();
        $a = $request->segment(2); 
        if (isset($role->permissions[$a])) {
            return $next($request);
        }

        return redirect('admin');
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM