1

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

JaneTho
  • 321
  • 1
  • 2
  • 13
  • 2
    you should write your user role checking code inside middleware – RAUSHAN KUMAR Jul 20 '17 at 10:19
  • can you give me an example? – JaneTho Jul 20 '17 at 10:24
  • You can use [middlewares](https://laravel.com/docs/5.4/middleware#introduction) or just find the user by email first before `Auth::attempt` and then check if the type is "admin" if it's the case use `attempt` and then `check` else redirect the user – Maraboc Jul 20 '17 at 10:30

2 Answers2

0

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');
yixiang
  • 890
  • 8
  • 12
0

You're struggling in creating custom code in laravel how the thing works. I suggest you use the laravel package located here: https://github.com/spatie/laravel-permission it allows you to manage user permissions and roles in a database

Thanks,

Al Francis
  • 333
  • 1
  • 12