mardi 23 août 2016

Redirect user after login in laravel 5.1

I am trying to implement a feature where, after logging in, a user gets redirected to a URL depending on their role. I have the roles part set up, but I'm having trouble testing the user's properties immediately after login.

I followed the instructions here to create a user login page. I have an AuthController that looks like this:

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller {

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    protected $redirectTo = '/test';
    ...
}

My __construct() function validates the user, but I don't know how to access the user object only immediately after login. This is what I presently have:

 public function __construct() {
     $this->middleware('guest', ['except' => 'getLogout']);

     if ( \Auth::check() ) {
         $user = \Auth::user();
         if ( $user->admin() ) {
         // an admin
             $this->redirectTo = '/admin';
         } else {
         // it's a client
             $this->redirectTo = '/client/dashboard';

         }
     }

     $user = \Auth::user();
     if ( is_object($user) ) {
     } else {
         $this->redirectTo = '/auth-not-object';
     }
 }

When I first attempt to log in with an administrator account, I get to the path /auth-not-object, because there isn't any authenticated user object at that point.

After having attempted to log in, but getting a bad redirect, when I revisit the /login url, I get redirected to /home, which I believe is the default $redirectTo in the traits this class uses. So that means we've passed the AuthController __construct() method without having changed the $redirectTo, even though there is an authenticated user.

I've found other questions, such as How to add extra logic on login condition in Laravel 5.2 and laravel redirect to url after login, but I don't understand how to apply those answers. For instance, the accepted answer to the second question shows new methods, getCredentials() and login(), which don't exist in the poster's original class. I am not sure in what class to add them, or where to call them from, in my codebase.

Other similar answers show a radically different way of authenticating users, such as this. It seems that, to use that solution, I would need to re-write my code, and forgo the use of the traits, which include bonus features like login throttling and so on.

Is there a way I can redirect users based on role after login, while still using these built-in traits?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire