duanhe2027 2017-05-13 01:41
浏览 35
已采纳

用于管理员和用户角色的Laravel 5.4中间件

I created two Middleware called "MustBeAdmin" and "MustBeUser" to make sure depending on the user login I redirect them to the right page and restrict unauthorized content. Currently everything is working fine and redirects work well too. But the Logic I wrote behind the scene seems wrong to me and its weird it still works. If I write the logic that seems right to me atleast, it does not seem to work as expected.

Users table

id (1,2,3,...)
name
role (1,2,3,...)

Roles table

id (1,2,3,...)
role (Student, Admin,...)

MustBeAdmin middleware

public function handle($request, Closure $next)
    {
        if($request->user()->role == 2)
        {
            return $next($request);
        }
        else
        {
            return redirect('/admin/users');
        }

    }

MustBeUser middleware:

public function handle($request, Closure $next)
    { 
        if($request->user()->role == 1)
        {
            return $next($request);
        }
        else
        {
            return redirect('/admin/users');
        }

    }

kernel.php

'admin' => \App\Http\Middleware\MustBeAdmin::class,
'user' => \App\Http\Middleware\MustBeUser::class,

As you can see I have registered middlewares in kernel.

I am getting results exactly what I need but I doubt if the logic in middleware is correct?

1 = Student
2 = Admin

if you see in MustBeAdmin middleware I am comparing if user role is 2 (admin) then do next($request) and in MustBeUser middleware I am comparing if user role is 1 (Student) then do next($request) and I set else to /Admin directory.

I feel its wrong, what do you think?

  • 写回答

2条回答 默认 最新

  • doukui4836 2017-05-13 04:12
    关注

    You are not checking the authenticated users details in your Middleware. The middleware should be something like:

    //for student 
    public function handle($request, Closure $next)
    {
    
        if ( Auth::check() && Auth::user()->role == 1 )
        {
            return $next($request);
        }
    
        return redirect('/admin');
    
    }
    
    
    //for admin 
    public function handle($request, Closure $next)
    {
    
        if ( Auth::check() && Auth::user()->role == 2 )
        {
            return $next($request);
        }
    
        return redirect('/student');
    
    }
    

    You should check my detailed answer on the same topic here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法