Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - login redirect loses the url hash

When I want to share a page url from my site like mysite.com/page1#foo=bar, or want to visit this page when I am logged out, I am redirected to the login form as page1 route is in the auth middleware.

My problem is that after I log in successfully, I am redirected to mysite.com/page1 and I lose the hash value.

(the hash value is also not kept on the /login)

Is there any easy way provided by Laravel to keep the hash ? As the hash is not sent to server, I kind of doubt it, but maybe there is something I missed somewhere !

Otherwise I would need to overwrite the login, maybe read the hash with JS and somehow re-inject it in the redirect after login, but would quite like to avoid doing that if there is an easy way :)

like image 280
mokk Avatar asked Nov 17 '16 12:11

mokk


2 Answers

Thanks to Mruf direction, I managed to get to the bottom of this. Not sure it is the best implementation, but it seems to be working.

Basically, I insert the hash value in the form as Mruf suggested, and then extended the handleUserWasAuthenticated function in AuthController

login.blade.php

<script type="text/javascript" >
  $( document ).ready(function() {
    $('.urlHash').val(window.location.hash);
  });
</script>

<form id="login-form" role="form" method="POST" action="{{ url('/login') }}">
  <input type="hidden" class="form-control urlHash" name="urlHash" value="">
  ....
</form>

AuthController.php

protected function handleUserWasAuthenticated(Request $request, $throttles)
{
    if ($throttles) {
        $this->clearLoginAttempts($request);
    }

    if (method_exists($this, 'authenticated')) {
        return $this->authenticated($request, Auth::guard($this->getGuard())->user());
    }

    // old code: return redirect()->intended($this->redirectPath());

    $newRequest = redirect()->intended($this->redirectPath());
    $newRequest->setTargetUrl($newRequest->getTargetUrl() . $request->urlHash);

    return $newRequest;
}
like image 125
mokk Avatar answered Oct 18 '22 09:10

mokk


A simple JavaScript would do the trick:

$("#login-form").submit(function(){
    e.preventDefault();
    $(this).append("<input type='hidden' name='hash' value='"+window.location.hash+"'");

    $(this).submit();
});

Now you can access the hash within your request object

function controllerAction(Request $request){
    $hash = $request->get("hash");
    // Parse Hash
    ....
    // Redirect to somewhere
    ....
}
like image 26
Mruf Avatar answered Oct 18 '22 11:10

Mruf