I have multiple admin system: one is super admin and the other is normal admin, distinguished by is_admin
attribute in users table.
And these two middlewares: SuperAdminMiddleware.php
public function handle($request, Closure $next, $guard = null)
{
if(Auth::check())
{
if($request->user()->is_admin==1)
{
return $next($request);
}
return redirect('/login');
}
else
{
return redirect('/login');
}
}
and, NormalAdminMiddleware.php
public function handle($request, Closure $next, $guard = null)
{
if(Auth::check())
{
if($request->user()->is_admin==2)
{
return $next($request);
}
return redirect('/login');
}
else
{
return redirect('/login');
}
}
and in loginController:
protected function authenticated()
{
if (auth()->user()->is_admin==1) {
return redirect('/super-admin');
}
else if(auth()->user()->is_admin==2){
return redirect('/normal-admin');
}
else {
return redirect('/home');
}
}
Now, Delete and Read should be designed in such a way that super admin can delete and see all users details, while normal admin can only see their city's user.
id name city is_admin
1 Non Maety 1
3 Pom Lorey 2
4 Rom Lorey 0
2 Yer Easter 0
Non should be able to see all. while Pom should see only id 3 and 4.
If i put show and delete routes under SuperAdminMiddleware, Normal Admin couldnot see their city's records.
Route::group(['middleware' => ['App\Http\Middleware\SuperAdminMiddleware']], function () {
Route::get('/show/{id}', 'MyController@show');
Route::post('/delete', 'MyController@delete');
});
And if i put these routes under both SuperAdminMiddleware and NormalAddminMiddleware. NormalAdminMiddleware can also see other city's records.
Route::group(['middleware' => ['App\Http\Middleware\NormalAdminMiddleware']], function () {
Route::get('/show/{id}', 'MyController@show');
Route::post('/delete', 'MyController@delete');
});
How do i overcome this situation?
You can solve it with a policy:
class UserPolicy
{
/**
* Determine if the given user can be viewed by the user.
*
* @param \App\User $user
* @param \App\User $account
* @return bool
*/
public function view(User $user, User $account)
{
switch($user->is_admin) {
case 1:
return true;
case 2:
return $user->city == $account->city;
default:
return 0;
}
}
/**
* Determine if the given user can be updated by the user.
*
* @param \App\User $user
* @param \App\User $account
* @return bool
*/
public function update(User $user, User $account)
{
switch($user->is_admin) {
case 1:
return true;
case 2:
return $user->city == $account->city;
default:
return 0;
}
}
}
User would be the authenticated user model, account would be the user model that should be viewed.
After you registered your policy (https://laravel.com/docs/5.4/authorization#registering-policies) you can call it in the function of your controller like:
public function show(User $user) {
$this->can('view', $user);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With