Vuejs Router guard works unexpected









up vote
0
down vote

favorite












I have router which work with errors and can't understand how to fix it.



This global router which should check jwt token expiration and handle routing. Everything worked fine before adding some functionality like isActivated account. So now I need to check if User has token and if User account is activated.



1) If user has token it should make next() otherwise next("/login") (redirect)



2) If user has token but his account is not activated yet (first time login), it should redirect on Setup page next("/setup") until he submits some information.



So this is my guard



router.beforeEach((to, from, next) => 
const token = localStorage.getItem("token");
const tokenExp = parseInt(localStorage.getItem("tokenExp"))
const isActivated = localStorage.getItem("isActivated")
const now = new Date().getTime() + 129600000

const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

console.log("first")

if (requiresAuth && !token)
next('/login');
else if (requiresAuth && token)

if (now > tokenExp)
axios.post("/user/t/r", token)
.then(e =>
const token = e.headers['authorization'].replace("Bearer ", "");

localStorage.setItem("token", token);
localStorage.setItem("tokenExp", (new Date().getTime() + 172800000).toString())

if (isActivated === 'true')
next()
else
next("/setup")

)
.catch(e =>
localStorage.removeItem("token")
localStorage.removeItem("tokenExp")
localStorage.removeItem("fullName")
localStorage.removeItem("role")
next('/login')
)
else
console.log("second")
if (isActivated === 'true')
console.log("third")
next();
else
console.log("fourth")
next("/setup")



else
next();

)


And this is my console.log with error when I login:



enter image description here










share|improve this question

















  • 2




    Yes, the reason behind this is router.beforeEach runs whenever you redirect to any route. And in the else condition where you are redirecting to a step /setup, the above beforeEach runs again and hence the never ending loop
    – Mohit Tilwani
    yesterday














up vote
0
down vote

favorite












I have router which work with errors and can't understand how to fix it.



This global router which should check jwt token expiration and handle routing. Everything worked fine before adding some functionality like isActivated account. So now I need to check if User has token and if User account is activated.



1) If user has token it should make next() otherwise next("/login") (redirect)



2) If user has token but his account is not activated yet (first time login), it should redirect on Setup page next("/setup") until he submits some information.



So this is my guard



router.beforeEach((to, from, next) => 
const token = localStorage.getItem("token");
const tokenExp = parseInt(localStorage.getItem("tokenExp"))
const isActivated = localStorage.getItem("isActivated")
const now = new Date().getTime() + 129600000

const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

console.log("first")

if (requiresAuth && !token)
next('/login');
else if (requiresAuth && token)

if (now > tokenExp)
axios.post("/user/t/r", token)
.then(e =>
const token = e.headers['authorization'].replace("Bearer ", "");

localStorage.setItem("token", token);
localStorage.setItem("tokenExp", (new Date().getTime() + 172800000).toString())

if (isActivated === 'true')
next()
else
next("/setup")

)
.catch(e =>
localStorage.removeItem("token")
localStorage.removeItem("tokenExp")
localStorage.removeItem("fullName")
localStorage.removeItem("role")
next('/login')
)
else
console.log("second")
if (isActivated === 'true')
console.log("third")
next();
else
console.log("fourth")
next("/setup")



else
next();

)


And this is my console.log with error when I login:



enter image description here










share|improve this question

















  • 2




    Yes, the reason behind this is router.beforeEach runs whenever you redirect to any route. And in the else condition where you are redirecting to a step /setup, the above beforeEach runs again and hence the never ending loop
    – Mohit Tilwani
    yesterday












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have router which work with errors and can't understand how to fix it.



This global router which should check jwt token expiration and handle routing. Everything worked fine before adding some functionality like isActivated account. So now I need to check if User has token and if User account is activated.



1) If user has token it should make next() otherwise next("/login") (redirect)



2) If user has token but his account is not activated yet (first time login), it should redirect on Setup page next("/setup") until he submits some information.



So this is my guard



router.beforeEach((to, from, next) => 
const token = localStorage.getItem("token");
const tokenExp = parseInt(localStorage.getItem("tokenExp"))
const isActivated = localStorage.getItem("isActivated")
const now = new Date().getTime() + 129600000

const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

console.log("first")

if (requiresAuth && !token)
next('/login');
else if (requiresAuth && token)

if (now > tokenExp)
axios.post("/user/t/r", token)
.then(e =>
const token = e.headers['authorization'].replace("Bearer ", "");

localStorage.setItem("token", token);
localStorage.setItem("tokenExp", (new Date().getTime() + 172800000).toString())

if (isActivated === 'true')
next()
else
next("/setup")

)
.catch(e =>
localStorage.removeItem("token")
localStorage.removeItem("tokenExp")
localStorage.removeItem("fullName")
localStorage.removeItem("role")
next('/login')
)
else
console.log("second")
if (isActivated === 'true')
console.log("third")
next();
else
console.log("fourth")
next("/setup")



else
next();

)


And this is my console.log with error when I login:



enter image description here










share|improve this question













I have router which work with errors and can't understand how to fix it.



This global router which should check jwt token expiration and handle routing. Everything worked fine before adding some functionality like isActivated account. So now I need to check if User has token and if User account is activated.



1) If user has token it should make next() otherwise next("/login") (redirect)



2) If user has token but his account is not activated yet (first time login), it should redirect on Setup page next("/setup") until he submits some information.



So this is my guard



router.beforeEach((to, from, next) => 
const token = localStorage.getItem("token");
const tokenExp = parseInt(localStorage.getItem("tokenExp"))
const isActivated = localStorage.getItem("isActivated")
const now = new Date().getTime() + 129600000

const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

console.log("first")

if (requiresAuth && !token)
next('/login');
else if (requiresAuth && token)

if (now > tokenExp)
axios.post("/user/t/r", token)
.then(e =>
const token = e.headers['authorization'].replace("Bearer ", "");

localStorage.setItem("token", token);
localStorage.setItem("tokenExp", (new Date().getTime() + 172800000).toString())

if (isActivated === 'true')
next()
else
next("/setup")

)
.catch(e =>
localStorage.removeItem("token")
localStorage.removeItem("tokenExp")
localStorage.removeItem("fullName")
localStorage.removeItem("role")
next('/login')
)
else
console.log("second")
if (isActivated === 'true')
console.log("third")
next();
else
console.log("fourth")
next("/setup")



else
next();

)


And this is my console.log with error when I login:



enter image description here







vue.js vuejs2 vue-router






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked yesterday









Dave

97110




97110







  • 2




    Yes, the reason behind this is router.beforeEach runs whenever you redirect to any route. And in the else condition where you are redirecting to a step /setup, the above beforeEach runs again and hence the never ending loop
    – Mohit Tilwani
    yesterday












  • 2




    Yes, the reason behind this is router.beforeEach runs whenever you redirect to any route. And in the else condition where you are redirecting to a step /setup, the above beforeEach runs again and hence the never ending loop
    – Mohit Tilwani
    yesterday







2




2




Yes, the reason behind this is router.beforeEach runs whenever you redirect to any route. And in the else condition where you are redirecting to a step /setup, the above beforeEach runs again and hence the never ending loop
– Mohit Tilwani
yesterday




Yes, the reason behind this is router.beforeEach runs whenever you redirect to any route. And in the else condition where you are redirecting to a step /setup, the above beforeEach runs again and hence the never ending loop
– Mohit Tilwani
yesterday












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










You are infinitely redirecting to /setup, You code on first run hits "fourth" then sends the user to /setup where that before call is run again and your infinite loop starts.



You need to stop calling next('/setup') or next('/login') if the user is already on that page.



You need to make use of router.currentRoute in order to check you are not going to redirect to page they are already on.



https://router.vuejs.org/api/#router-currentroute






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237823%2fvuejs-router-guard-works-unexpected%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    You are infinitely redirecting to /setup, You code on first run hits "fourth" then sends the user to /setup where that before call is run again and your infinite loop starts.



    You need to stop calling next('/setup') or next('/login') if the user is already on that page.



    You need to make use of router.currentRoute in order to check you are not going to redirect to page they are already on.



    https://router.vuejs.org/api/#router-currentroute






    share|improve this answer
























      up vote
      1
      down vote



      accepted










      You are infinitely redirecting to /setup, You code on first run hits "fourth" then sends the user to /setup where that before call is run again and your infinite loop starts.



      You need to stop calling next('/setup') or next('/login') if the user is already on that page.



      You need to make use of router.currentRoute in order to check you are not going to redirect to page they are already on.



      https://router.vuejs.org/api/#router-currentroute






      share|improve this answer






















        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        You are infinitely redirecting to /setup, You code on first run hits "fourth" then sends the user to /setup where that before call is run again and your infinite loop starts.



        You need to stop calling next('/setup') or next('/login') if the user is already on that page.



        You need to make use of router.currentRoute in order to check you are not going to redirect to page they are already on.



        https://router.vuejs.org/api/#router-currentroute






        share|improve this answer












        You are infinitely redirecting to /setup, You code on first run hits "fourth" then sends the user to /setup where that before call is run again and your infinite loop starts.



        You need to stop calling next('/setup') or next('/login') if the user is already on that page.



        You need to make use of router.currentRoute in order to check you are not going to redirect to page they are already on.



        https://router.vuejs.org/api/#router-currentroute







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Marc Newton

        1,5251317




        1,5251317



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237823%2fvuejs-router-guard-works-unexpected%23new-answer', 'question_page');

            );

            Post as a guest














































































            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            ReactJS Fetched API data displays live - need Data displayed static

            Evgeni Malkin