douzhang6176 2017-07-20 10:16
浏览 234

Laravel:ADMIN和USER的安全性

I have a two different login forms for user and admin. What I want is the user should only login in their own form otherwise it should be an error, and just the same for the admin form.

I only have 1 table for both user and admin in my database. They only differ in user_type which is obviously "admin" and "user"

What I am doing is when the user tried to login in admin login form it shows an info that says 'sorry, you are not an admin in this site'. But that means that the user is still logged in.

What I want is when the tries to login in admin form I don't want it to access the system at all.

Here my code so far:

public function validateLoginResort(Request $requests){
 $username = $requests->username;
 $password = $requests->password;

 $attempt = Auth::attempt([
 'email' => $requests->username,
 'password' => $requests->password,
  ]);

  if(Auth::check()){
    if(Auth::user()->type_user == 'admin'){

       return redirect('home');
     }
     else{
       Auth::logout();
       return redirect('login');
      }
   }else{
     return "Invalid input";
  }
}

I tried using Auth::logout if the user is not an admin but I dont think it is safe and right at all.

I think there is still a better way to do this, can you guys give a suggestion on how to implement this correctly? Thank you

  • 写回答

1条回答 默认 最新

  • dqoqnmb163241 2017-07-21 02:05
    关注

    You could check user type first, and then login user if he/she is admin.

    Suppose your user table name is "users" and corresponding eloquent model is "User", then you could do this:

    $user = User::where('email', $request->get('email'))->first();    
    if (!$user || !\Hash::check($request['password'], $user->password)) {
        return 'Invalid user credential';
    }
    
    if ($user->type_user !== 'admin') {
        return 'Only admin allowed';
    }
    
    \Auth::login($user); // This is the key point.
    return redirect('home');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B