[Dancer-users] best practices: how to require a login for parts of the site...

Daniel Pittman daniel at rimspace.net
Sat May 29 03:28:44 CEST 2010


One of the requirements I am going to hit in the near future is that we will
need to provide some public and some routes inside a single application.

When users hit anything under a specific path, basically, they need to have an
already validated login, or else we need to send 'em off to get one.  The most
basic "implement a login form" style thing pattern, nothing fancy.

What I am curious about is the "best practice" way to achieve that inside the
scope of Dancer, and how to make it a "drop in" part of other projects if I
end up wanting to advocate wider use of Dancer in the company.

My current model is to provide a plugin akin to this:

package Dancer::Plugin::WithAuth;
my $config = plugin_config;
register with_auth (&) {
    my $handler = shift;
    return sub {
        session('user') or redirect $config->{login_path}, 302;
        goto &$handler;

That then gets used with a route like this:

get '/example/:arg' => with_auth {
    # normal handler here

Is this the best approach to take to authentication for parts of the site?

I considered the approach of hooking all requests and performing my own URL
matching to determine if they should require authentication, but that seems to
require that I duplicate an awful lot of code from the Dancer route system.

Alternately, is there some feature of Dancer that I missed which would be
easier to use for this?

Oh.  I did consider this construction, but found it hard to get right,
especially if I wanted to cover '/admin' as well as pages under it.

    get r('/admin/.*') => sub {
        session('user') or redirect '/login', 302;

    get '/admin/example' => sub {
        # ...should only be called *after* the first route calls 'pass'

Is that just my messing up or something?

✣ Daniel Pittman            ✉ daniel at rimspace.net            ☎ +61 401 155 707
               ♽ made with 100 percent post-consumer electrons

More information about the Dancer-users mailing list