2

In my HotTowel based project, I'm using Durandal 1.1.1 for routing.

I have a login route, which I want to activate if the user is not logged in.

my route config is like:

var routes = [ {
    url: 'login',
    moduleId: 'viewmodels/login',
    name: 'Login',
    visible: true,
    caption: 'Login'
    },{
    url: 'moduledetail/:id',
    moduleId: 'viewmodels/moduledetail',
    name: 'ModuleDetail',
    visible: true,
    caption: 'ModuleDetail'
    }

I want if user want to go #/moduledetail/1 and is not authenticated yet, the browser navigate to route #/login/moduledetail/1 so after successful login route back to the #/moduledetail/1.

A possible solution is to put a navigateTo in canActivate of moduledetail like:

function canActivate()
{
    if (!loggedIn)
        router.navigateTo(`#/login/moduledetail/1`)
    return false;
}

But navigating to another page during canActivate seems so foolish.

Is there any method to tell Durandal that while routing, on this condition use this route?

mehrandvd
  • 8,806
  • 12
  • 64
  • 111

1 Answers1

6

In Durandal 2.0, this is achieved using router.guardRoute:

auth = require('auth');
router.guardRoute = function(model, route) {
    return auth.loggedIn() || '#/login';
};

From what I've read, though undocumented the behavior works the same in Durandal 1.x. Guard route is a function called after the viewModel is loaded but before activate is called on the view model. If true, routing proceeds. If a string, the router tries to navigate to the route associated with that string.

Matthew James Davis
  • 12,134
  • 7
  • 61
  • 90
  • Thanks for your answer. I didn't know that `guardRoute` is added to durandal 2.0. But my problem still remains as it's not working in durandal 1.x and currently I can't upgrade to 2.0 due to the project checkpoints. – mehrandvd Oct 02 '13 at 06:21
  • "From what I've read, though undocumented the behavior works the same in Durandal 1.x." – Matthew James Davis Oct 02 '13 at 17:02
  • But I didn't found any function named `guradRoute` in Duranda 1.x!? – mehrandvd Oct 02 '13 at 20:01
  • 2
    Reason you can't find it in 1.1.1 as it was added in 1.2. https://github.com/BlueSpire/Durandal/blob/master/Changes.txt. Time to upgrade? – RainerAtSpirit Oct 02 '13 at 21:27
  • It is undocumented, which is why I said "though undocumented." From what I've read, it should be in there. But I haven't personally used it. Please try testing to see if router.guardRoute is defined. – Matthew James Davis Oct 02 '13 at 21:27
  • 1
    @RainerAtSpirit Currently I cant upgrade the project due some time constraints, I'll update it in 2 weeks. But yes, it's at 1.2, thanks. – mehrandvd Oct 05 '13 at 08:40