The Open-Event-Frontend allows the event organiser to create tickets for his or her event. Other uses can buy these tickets in order to attend the event. In order to make the user experience smooth, we redirect the user to their previous route when they successfully login into their account. This blog explains how we have achieved this functionality in the project.
We have two different cases to handle in order to solve this problem:
- The user was in route A and wanted to move to route B. Here route A doesn’t require authorization and route B requires authorization. In this case, we would like to direct the user to the login route and once they are done, redirect them back to route B.
- The user was in route A and directly entered the login route using the login button. In this case we want to direct them back to the route A after successful login.
We use Ember-simple-auth in order to manage authentication in the project. Not only does it make it easy to manage authentication, it also handles the case 1 for us out of the box. So now the simplified problem is to redirect the user back to the previous route if they entered the login route directly using the web address or the login button.
If we can somehow store the previous route visited by a user, then we can easily redirect them back once they are logged in.
We will add a custom property in the session service called previousRouteName which will store the URL of the previous route visited by the user. We will make use of the willTransition hook in the application.js file. This hook is called everytime the user transitions from one route to another which makes it suitable for us to update the previousRouteName.
_mergeParams is a helper function which makes use of merge function of the Lodash library.
Now we’re done with saving the URL of the previous route. All that remains is to trigger the redirect once the user has successfully logged in. We will use the sessionAuthenticated hook which is triggered everytime the user logs in.
If the previous route variable is set, we redirect to it otherwise we can the super method and let Ember-simple-auth handle case 1 mentioned earlier for us.
- Ember-simple-auth: https://github.com/simplabs/ember-simple-auth
- Best way to get the current URL in Ember: https://discuss.emberjs.com/t/what-is-the-best-practice-for-save-the-target-path-to-go-to-it-after-registration/8040/16
- Preventing and retrying transitions: https://guides.emberjs.com/release/routing/preventing-and-retrying-transitions/