In Galileo I have an auth_fail
helper which does something like this. While I work out an example, see that code (and the if_author
and if_admin
under
s).
Ok here is an example, the trick turned out to be (at least for this mechanism) before you can redirect to your failure handler, you need to flash
the format, which make it available to the next handler.
#!/usr/bin/env perl
use Mojolicious::Lite;
any '/fail' => sub {
my $self = shift;
$self->respond_to(
json => {
json => { error => 'Invalid authentication token.' },
status => 401
},
text => {
text => 'Unauthorized.',
status => 401
}
);
};
under sub {
my $self = shift;
# Authenticated
my $token = $self->param('token') || '';
return 1 if $token eq '123456';
# Not authenticated
$self->flash( format => $self->param('format') );
$self->redirect_to('fail');
return undef;
};
any '/private' => sub {
my $self = shift;
$self->respond_to(
json => {
json => { launch_codes => '9999999' },
},
text => {
text => 'Launch Code: 9999999',
}
);
};
app->start;