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!
Much easier with this library and login function is
This will help you @Schwesi .
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:
The login submit action
Hope it helps.
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 linenext({ name: 'Login', query: { from: loginpath } });
I pass as a query in the redirect.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.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.