Search code examples
sapui5

How to override the routing and redirect to another view in UI5?


Given the simplified sample app based on Shop Administration Tool. When navigating with the sidebar between the views, I just show different views, e.g. View #1, View #2, etc. These views are standalone views, each of them has its own XML-template and JS-controller.

Now, I want to add a permission check for each view and if a user has no permission, then he should be redirected to the main view instead of the desired view.

I've implemented a pre-navigation check:

router.attachRoutePatternMatched(async (event) => {

    const targetView = event.getParameters().view.getProperty("viewName");

    const isPermitttedToSeeView = await this.checkUserPermission(targetView);

    if (!isPermitttedToSeeView) {

        MessageToast.show("Sorry, you don't have permissions.");

        router.navTo("mainView");

    }

}, this);

This code works but the problem is that in case of no permissions user firstly sees a MessageToast message (OK), then is redirected to the forbidden view (bad), and then immediately redirected to the mainView view (OK).

I've tried to use attachBeforeRouteMatched instead, hoping that in this case the routing is not performed yet and I can redirect a user if needed and user will not see the forbidden view. But not, I still see the forbidden view for a second and then I'm redirected to the mainView.

How can I prevent a redirection to the forbidden view and send the user directly to the mainView view? In other words, how can I alter a routing navigation pipeline?


Solution

  • The possible workaround is to use a «hard» redirect instead of routing:

    mLibrary.URLHelper.redirect("%desiredURL%", false);
    

    Where mLibrary is defined in sap.ui.define via "sap/m/library".

    This will drop any ongoing routing and will force (in terms of UX, not in terms of security) user to be redirected to the desired URL.

    Perhaps, it's not the optimal solution from the performance point of view, since it might lead to unwanted rendering but that's the only way I found to prevent user from being routed to undesired view.