Skip to content

Request Filters

Jason Strimpel edited this page Jul 22, 2014 · 3 revisions

LAZO.app.addRequestFilter provides an interface for adding filters. Filters are used to redirect to another location before executing an action associted with a route.

A good use case is if an application requires authentication. A filter would look for the existence of a session cookie. If the cookie existed it would update the time stamp and Lazo would execute the component action for the requested route by returning undefined. If the cookie were invalid then the filter would return the path to the login page.

Filters are applied in the order they were entered for a given regular expression that matches a route. If multiple regular expression keys are matched then the filters are applied in order matched and then in order of addition to the matching regular expression key.

LAZO.app.addRequestFilter('.*', function (path, params, ctx, options) {
    var sessionCookie = ctx.getCookie('session_token');

    // invalid session; user redirected to login route
    if (!sessionCookie && path !== 'login') {
        return options.sucess('/login');
    }

    // valid session
    // updated cookie
    ctx.setCookie('session_token', sessionCookie, {
        ttl: 60 * 60 * 1000,
        path: '/'
    });

    // return undefined; user continues to original route unless another
    // applied filter returns a redirect
    return options.success();
});

If something went really, really wrong in a filter you can call options.error(err). This will trigger a 500 error and render the corresponding error template.