When you try to access a protected resource and get forwarded to the login page, the url in the browser doesn’t change. This means that with the default behaviour of [[!Login]]
you kind of already get redirected back to the protected resource after a successful login. However, this doesn’t work when you enter wrong credentials and the login form is reloaded.
Maybe I’m missing something simple and obvious, but here are some ideas that may or may not work:
Version 1: Request-parameter 'redirectBack’
Template:
[[!Login? &loginTpl=`myLoginTpl`]]
Chunk “myLoginTpl”: Add a hidden field with name “redirectBack” (important!) to the login form.
<input type="hidden" name="redirectBack" value="[[!getReferrerId]]" />
Snippet “getReferrerId”: Change the values of $fallback_id
and $resource_id_login
.
<?php
if (isset($_POST['redirectBack'])){
//login form reload -> don't change value
return (int)$_POST['redirectBack'];
} else {
$fallback_id = 20; //default loginResourceId, if it can't be determined from the request parameter
$resource_id_login = 10; //resource id of the login page
//try to determine original resource id from the request parameter (for friendly urls)
if (isset($_REQUEST['q'])){
$req_uri = $_REQUEST['q'];
$resource_id = $modx->findResource($req_uri);
if ($resource_id && $resource_id != $resource_id_login){
return $resource_id;
}
}
return $fallback_id;
}
Version 2: Redirect in PostHook
Template:
[[!Login? &loginTpl=`myLoginTpl` &postHooks=`myLoginRedirectPostHook`]]
Chunk “myLoginTpl”: Add a hidden field with name “referrer” to the login form.
<input type="hidden" name="referrer" value="[[!getReferrer]]" />
Snippet “getReferrer”:
<?php
if (isset($_POST['referrer'])){
//form reload, don't change value
return $_POST['referrer'];
} else {
$referrer = $_SERVER['REQUEST_URI'];
//maybe do some checks here
return $referrer;
}
Snippet “myLoginRedirectPostHook”:
<?php
$modx = $hook->modx;
if (isset($_POST['referrer']) && !empty($_POST['referrer'])){
$url = $_POST['referrer'];
//maybe do some checks here to prevent shenanigans
$modx->sendRedirect($url);
}
return true;
It is probably not a good idea to call sendRedirect()
in a posthook, because I think it prevents the rest of the code from being executed. But it would allow to use the request uri directly without the need to convert it into a resource-id.