Viewed   100 times

I am using Laravel Framework 5.4.10, and I am using the regular authentication that

php artisan make:auth

provides. I want to protect the entire app, and to redirect users to /themes after login.

I have 4 controllers: ForgotPasswordController.php, LoginController.php, RegisterController.php and ResetPasswordController.php. I have edited this line into the last three:

protected $redirectTo = '/themes';

This is the first line in my routes/web.php:

Auth::routes();

I have added this function in my Controller.php:

    public function __construct()
    {
        $this->middleware('auth');

    }

I have edited app/Http/Middleware/RedirectIfAuthenticated.php, so that the handle function looks like this:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/themes');
    }

    return $next($request);
}

It's all fine, except when I click the Login button, I get redirected to "/", not "/themes". If I don't require authentication in the controllers (no __contruct function in Controller.php file), I get redirected OK at login. What am I doing wrong?

 Answers

3

That's what i am currrently working, what a coincidence.

You also need to add the following lines into your LoginController

namespace AppHttpControllersAuth;

use AppHttpControllersController;

use IlluminateFoundationAuthAuthenticatesUsers;

use IlluminateHttpRequest;

class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/

use AuthenticatesUsers;


protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
    return redirect()->route('dashboard');
}

 return redirect('/home');
}
/**
 * Where to redirect users after login.
 *
 * @var string
 */
//protected $redirectTo = '/admin';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}
}
Monday, August 15, 2022
4

You are having these redirection loops because all the methods in HomeController are protected by Guest Middleware.

Since you wish to redirect authenticated users to HomeController@index

Remove $this->middleware('guest'); from HomeController

or

Modify the Guest Middleware to ignore index method

$this->middleware('guest', ['only' => ['tutorials','tutorialsCategory']])

List other methods you wish to protect with Guest Middleware excluding Index method

Sunday, November 6, 2022
 
1

You have to gain access over STDERR and, probably, STDOUT. Use proc_open, e.g.:

$desc = [
  1 => ['pipe', 'w'], // STDOUT
  2 => ['pipe', 'w'], // STDERR
];

$proc = proc_open('ls -l . something', $desc, $pipes);
if (is_resource($proc)) {

  if ($out = stream_get_contents($pipes[1])) {
    echo $out;
  }
  fclose($pipes[1]);


  if ($err = stream_get_contents($pipes[2])) {
    fprintf(STDERR, "Error: %sn", $err);
  }
  fclose($pipes[2]);

  // You can also check the process exit status
  // 0 means success, otherwise error.
  $exit_status = proc_close($proc);
}

Of course, there is no need in STDOUT pipe, if the command redirects it to a file.

And yes, system() won't throw exceptions. Obviously, you can implement your own class which will throw an exception in case if the process exit status is non-zero, or there is something caught in the STDERR pipe:

class MyShellException extends Exception {}

class MyShell {
  public static function execute($command, &$out = null) {
    if (func_num_args() > 1) {
      $desc[1] = ['pipe', 'w'];
    } else {
      $desc[1] = ['file', '/dev/null'];
    }

    $desc[2] = ['pipe', 'w'];

    $proc = proc_open($command, $desc, $pipes);
    if (is_resource($proc)) {
      if (isset($pipes[1])) {
        $out = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
      }

      if ($err = stream_get_contents($pipes[2])) {
        fclose($pipes[2]);
        throw new MyShellException("Command $command failed: $err");
      }

      if ($exit_status = proc_close($proc)) {
        throw new MyShellException("Command $command exited with non-zero status");
      }
    }
  }
}


try {
  MyShell::execute('ls -l . something', $out);
  echo "Output: $outn";
} catch (MyShellException $e) {
  if (!empty($out)) {
    echo "Output: $outn";
  }
  fprintf(STDERR, "MyShell error: " . $e->getMessage());
  exit(1);
}
Monday, December 26, 2022
2

After a couple of hours of investigation, I figured out that the solution is quite simple.

All I had to do is to add the following function to nova LoginController:

protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    $redirectPath = $this->redirectPath();
    redirect()->setIntendedUrl($redirectPath);

    return redirect()->intended($redirectPath);
}

Explanation:

This function is implemented in trait AuthenticatesUsers.

intended function (member of Redirector class) create a redirect response, based on previously intended location, and if not exists - on given url.

If no url.intended is set in session, user will be redirected to url generated by LoginController::redirectPath. However, if there an entry of url.intended does exist in session, we need to delete it in order to force redirecting user to the url we are interested in.

The only problem which I see is that we loose the feature of redirecting user to the same page he was before he was logged out. So it is a simple matter of choice as a developer...

Tuesday, November 1, 2022
 
joly
 
2

Put the URL the user was accessing in the session before redirecting to the login page. The login page can then redirect back to that stored URL after authenticating the user.

On the page that needs logging in:

session_start();
$_SESSION['after_login'] = $_SERVER['REQUEST_URI'];
header("Location: login.php");

On the login page:

session_start();
if (user has entered correct username and password) {
    header("Location: http://example.com" . $_SESSION['after_login']);
}
Friday, November 18, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :