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条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容