Vuejs Router guard works unexpected










0














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
    Nov 10 '18 at 14:13















0














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
    Nov 10 '18 at 14:13













0












0








0







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 Nov 10 '18 at 9:57









Dave

104110




104110







  • 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
    Nov 10 '18 at 14:13












  • 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
    Nov 10 '18 at 14:13







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
Nov 10 '18 at 14:13




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
Nov 10 '18 at 14:13












1 Answer
1






active

oldest

votes


















1














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',
    autoActivateHeartbeat: false,
    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















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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

























      1














      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























        1












        1








        1






        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 Nov 10 '18 at 14:16









        Marc Newton

        1,8581320




        1,8581320



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            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















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

            Edmonton

            Crossroads (UK TV series)