Redirect to requested page after login using vue-r

2020-02-17 02:50发布

In my application some routes are just accessible for authenticated users.
When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redirected to the login component.

If the user logs in successfully, I would like to redirect him to the URL he requested before he had to log in. However, there also should be a default route, in case the user did not request another URL before he logged in.

How can I achieve this using vue-router?


My code without redirect after login

router.beforeEach(
    (to, from, next) => {
        if(to.matched.some(record => record.meta.forVisitors)) {
            next()
        } else if(to.matched.some(record => record.meta.forAuth)) {
            if(!Vue.auth.isAuthenticated()) {
                next({
                    path: '/login'
                    // Redirect to original path if specified
                })
            } else {
                next()
            }
        } else {
            next()
        }
    }        
)



My login function in my login component

login() {
    var data = {
        client_id: 2,
        client_secret: '**************',
        grant_type: 'password',
        username: this.email,
        password: this.password
    }
    // send data
    this.$http.post('oauth/token', data)
         .then(response => {
             // authenticate the user
             this.$auth.setToken(response.body.access_token,
             response.body.expires_in + Date.now())
             // redirect to route after successful login
             this.$router.push('/')
          })



I would be very thankful for any kind of help!

4条回答
时光不老,我们不散
2楼-- · 2020-02-17 03:28

Much easier with this library and login function is

let redirect = this.$auth.redirect();
this.$auth
  .login({
    data: this.model,
    rememberMe: true,
    redirect: { name: redirect ? redirect.from.name : "homepage",  query: redirect.from.query },
    fetchUser: true
  })
查看更多
Root(大扎)
3楼-- · 2020-02-17 03:31

This will help you @Schwesi .

Router.beforeEach(
    (to, from, next) => {
        if (to.matched.some(record => record.meta.forVisitors)) {
            if (Vue.auth.isAuthenticated()) {
                next({
                    path: '/feed'
                })
            } else
                next()
        }
        else if (to.matched.some(record => record.meta.forAuth)) {
            if (!Vue.auth.isAuthenticated()) {
                next({
                    path: '/login'
                })
            } else
                next()
        } else
            next()
    }
);
查看更多
三岁会撩人
4楼-- · 2020-02-17 03:42

In a bit different way this can be achieved by adding a query param in your route when you want to redirect and then checking when you login if the param is set; If is set you use it or otherwise you fallback on root.

In code should look something like this:

Put an action to your link for example:

onLinkClicked() {
  if(!isAuthenticated) {
    // If not authenticated, add a path where to redirect after login.
    this.$router.push({ name: 'login', query: { redirect: '/path' } });
  }
}

The login submit action

submitForm() {
  AuthService.login(this.credentials)
    .then(() => this.$router.push(this.$route.query.redirect || '/'))
    .catch(error => { /*handle errors*/ })
}

Hope it helps.

查看更多
时光不老,我们不散
5楼-- · 2020-02-17 03:49

I know this is old but it's the first result in google and for those of you that just want it given to you this is what you add to your two files. In my case I am using firebase for auth.

Router

The key line here is const loginpath = window.location.pathname; where I get the relative path of their first visit and then the next line next({ name: 'Login', query: { from: loginpath } }); I pass as a query in the redirect.

router.beforeEach((to, from, next) => {
  const currentUser = firebase.auth().currentUser;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (requiresAuth && !currentUser) {
    const loginpath = window.location.pathname;
    next({ name: 'Login', query: { from: loginpath } });
  } else if (!requiresAuth && currentUser) next('menu');
  else next();
});

Login Page

No magic here you'll just notice my action upon the user being authenticated this.$router.replace(this.$route.query.from); it sends them to the query url we generated earlier.

signIn() {
      firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
        (user) => {
          this.$router.replace(this.$route.query.from);
        },
        (err) => {
          this.loginerr = err.message;
        },
      );
    },

I am going to be fleshing out this logic in more detail but it works as is. I hope this helps those that come across this page.

查看更多
登录 后发表回答