I am using Mojolicious::Plugin::Authentication to handle authentication in my app. I am trying to set up a route for slash '/' that will have one controller/action if authenticated, and another if not (i.e., you go to a different page depending on whether you're authenticated.) I'm not sure how to go about achieving this. Here are some of the things I've tried:
$r->any('/')->to(cb => sub {
my $self = shift;
if ( $self->is_user_authenticated ) {
$self->redirect_to('member#index');
}
else {
$self->redirect_to('guest#index');
}
});
And...
my $logged_in = $r->under (sub {
my $self = shift;
if (!$self->session("username")) {
return undef;
}
else {
return 1;
}
});
if ( $logged_in ) {
$logged_in->get('/')-to(controller => 'Member', action => 'index');
}
else {
$r->get('/')->to(controller => 'Guest', action => 'index');
}
I don't have to use Mojolicious::Plugin::Authentication. I could easily set a session token and check for it myself. Either way, the problem remains: how do I create a dynamic action for a given route?
Addendum
Forgot to add, I also tried this:
my $auth = $r->under('/' => sub {
my $self = shift;
# Authenticated
return 1 if $self->is_user_authenticated;
# Not authenticated
return undef;
});
$auth->get('/')->to('member#index');
# Routes related to non-members
$r->get('/')->to('guest#index');
Adding Another Detail
I just wanted to add, I can render or redirect_to something different based on state, e.g.,
$r->any('/')->to(cb => sub {
my $self = shift;
if ( $self->is_user_authenticated ) {
$self->render('member/index');
}
else {
$self->render('guest/login');
}
});
And that does work pretty well. However, I am still curious if it's possible to have different controllers/actions for a given route based on the state.
Mojo hooks are what you are looking for, a very powerful feature, particularly useful for authentication:
http://mojolicio.us/perldoc/Mojolicious#HOOKS
You probably need to look at before_dispatch()
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With