Search code examples
phpsymfonyhttp-redirecturl-parameterssymfony-2.8

Redirecting to login page and keeping URL GET parameters in Symfony 2.8


I am creating a URL to be sent in an email like this:

    $url = $this->getContainerInterface()->get('router')->generate(
    'crmpiccobundle_view_subdomain_modify', [
       'subdomain' => $site->getSubdomain(),
       'subdomain_username' => $site->getSubdomain(),
    ], UrlGeneratorInterface::ABSOLUTE_URL),

That URL is handled by the following method in my controller:

/**
 * @Route(
 *     "/view/{subdomain}/modify",
 *     name="crmpiccobundle_view_subdomain_modify"
 * )
 *
 * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
 * @Template("CRMPiccoBundle:Admin/View/Modify:index.html.twig")
 *
 * @param Request $request
 * @param string  $subdomain
 *
 * @return array
 */
public function subdomainModifyViewAction(Request $request, string $subdomain)
{

So, the route /view/{subdomain}/modify requires authentication meaning if the user is not logged in then they will be kicked to the login screen. What I am trying to achieve is to pass the 'subdomain' or the 'subdomain_username' (I realise there is duplication here) through to the login page either in the URL (e.g. /login?subdomain_username=crmpicco) or by other means.

I don't think setting a session variable is suitable because the script is run by a cron and not the user in the browser.

Can I go from /view/crmpicco/modify?subdomain_username=crmpicco to /login?subdomain_username=crmpicco ?

security.yml:

access_control:
    - {path: /, roles: IS_AUTHENTICATED_ANONYMOUSLY}
    - {path: /admin, roles: ROLE_USER}
    - {path: /admin/view, roles: ROLE_USER}

Solution

  • The way I ended up implementing this was to pull the destination URL, which will be redirect to upon successful login, out of the session (_security.default.target_path) and then parse it to pull the URL parameter out (?username=crmpicco).

    // pull the target URL out of the session and parse it to get the ?username=crmpicco part     
    
    parse_str(parse_url($request->getSession()->get('_security.default.target_path'), PHP_URL_QUERY), $usernameArray);
    
    $prefilledUsername = isset($usernameArray['username']) ? $usernameArray['username'] : '';
    
    // ... then pass through $prefilledUsername to my Login view