4

I have a certain notification popup I want to trigger if the Security denies access for ROLE_USER to use the path Admin_Only , I successfully configured this , which works perfectly, on my :

security.yml

 access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/Admin_Only, role: ROLE_ADMIN }

access_denied_url: /home

and I have a JQuery Function on my Twig file to which I am rendering my /home Action let's call it accessDeniedJQ. The question is How do I check and where ( Action in the Controller or on twig ) that a redirection has happened and the access was denied , in other words how do I check if this exception was raised so the JQ function starts.

Khaled Ouertani
  • 316
  • 2
  • 13
  • have you tried `console.log()` at the different points of the application? In php, I believe you can do a `console.log('')" ?>` as your die. – Malcolm Salvador Aug 22 '17 at 08:17
  • In native php i know it's possible but using the twig templating i lack the syntax to catch the exception , a code example would help alot – Khaled Ouertani Aug 22 '17 at 08:36
  • 1
    Can't you change the url to /home?redirected=true and directly look for that in your jQuery? – Salketer Aug 22 '17 at 08:51
  • @KhaledOuertani how about `try catch`? https://stackoverflow.com/questions/23731604/how-to-try-catch-in-symfony – Malcolm Salvador Aug 22 '17 at 09:01
  • @Salketer Thanks alot , I did pass some parameters along with the path , I checked for them on the twig and depending on its existance I was able to trigger the function , please elaborate more with some code example so this question has a right answer. – Khaled Ouertani Aug 22 '17 at 09:14

1 Answers1

1

When your framework does an internal redirect (or you just can't know if there was an HTTP redirect) your best bet is to use an URL with a query string to let your code be aware of it.

Here my suggestion is to append something similar to redirected=true in the url so it would become /home?redirected=true

Using the function taken from the answer at jquery get querystring from URL

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

I can easily detect that my page was redirected and act accordingly:

if(getUrlVars().redirected){
    alert('You are not allowed there, got redirected!');
}
Salketer
  • 14,263
  • 2
  • 30
  • 58