0
votes

I am using Durandal in an asp.net application which is all working well. What I would like to achieve is to put something into the routing of it so if required I can stop the current route and redirect.

The reason for this is I want to permission base some routes where the permissions are stored in a database. So during the routing I want to check the route, use web api accordingly to check if they have access to that route and redirect if so OR use a method on the viewmodel to check this and redirect accordingly. I do use the activate function on the viewmodel, I wondered if the route can be redirected here perhaps?

Has anyone done this before?

EDIT: Following the great answer below the following is the code I eventually used on a test route to get this working. The web api function HasAccessToRoute part returns a bool:

define(['durandal/http', 'plugins/router', 'knockout', 'durandal/app'], function (http, router, ko, app) {

function viewModel() {
    var self = this;

    self.canActivate = function () {
        return http.ajaxRequest("get", "/api/route/hasaccesstoroute?route=test")
            .done(function (result) {
                if (!result) {
                    app.showMessage("Test area cannot be accessed");
                }
            });            
    };
}

var model = new viewModel();
return model;
});
1

1 Answers

1
votes

Yes, it is possible. Take a look at canActivate here. You can return a promise in your canActivate handler and fetch your authorization profiles asynchronously. Once you have the authorization profile, you can then resolve your canActivate with either true or false, accordingly. This is what we do.

Also, the routes in Durandal are client-side, not server-side. Or are you doing server-side rendering with, say, Razor? If not, then the only time you would be going out to the server, essentially, is to obtain data, usually through a RESTful Web API (although you can do this with action-based routes as well).

This is an important point since canActivate is a client-side handler.