Friday, September 23, 2011

Experimenting with #mojolicious experimental groups block

In the course of discussion via IRC in #mojo the groups block was added as an experimental feature to Mojolicious::Lite (originally called routes but shortly after renamed), here is the result of me playing with it in the context of a authentication and authorization:


use Mojolicious::Lite;

under sub { 
  my $self = shift;
  my ($user) = split /:/, $self->req->url->to_abs->userinfo;
  
  unless ($user) {
    $self->res->headers->www_authenticate('Basic realm=test');
    $self->render_text('You must log in', status => 401);
    return;
  } else {
    $self->stash( user => $user );
    return 1;
  }
};

helper greet => sub {
  sprintf(
    "Hello %s would you like to play a game",
    shift->stash('user')
  );
};

get '/' => sub { shift->greet; };

group {
  under '/gtw' => sub { shift->stash('user') eq 'david' };

  get sub {
    shift->render_text('The only way to win is to not play at all');
  };
};

get '/chess' => sub { shift->render_text('checkmate'); };
get '/bye'   => sub { shift->render_text('Bye!', status => 401); };

app->start;


No comments:

Post a Comment