Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with routing in Mojolicious

I have the "Pages" controller with the "show" method and "Auths" controller with the "check" method which returns 1 if user is authenticated. I have "default" page ("/profile").

I need to redirect to / if the user is authenticated and redirect all pages to / with the authorization form if the user is not authenticated. My code does not want to work properly (auth based on the FastNotes example application): (

auths#create_form - html-template with the authorization form.

    $r->route('/')       ->to('auths#create_form')   ->name('auths_create_form');
    $r->route('/login')      ->to('auths#create')    ->name('auths_create');
    $r->route('/logout')     ->to('auths#delete')    ->name('auths_delete');
    $r->route('/signup') ->via('get') ->to('users#create_form')   ->name('users_create_form');
    $r->route('/signup') ->via('post') ->to('users#create')    ->name('users_create');
    #$r->route('/profile') ->via('get') ->to('pages#show', id => 'profile') ->name('pages_profile');

    my $rn = $r->bridge('/')->to('auths#check');
    $rn->route        ->to('pages#show', id => 'profile') ->name('pages_profile');

 $rn->route('/core/:controller/:action/:id')
    ->to(controller => 'pages',
   action  => 'show',
   id   => 'profile')
    ->name('pages_profile');

 # Route to the default page controller
 $r->route('/(*id)')->to('pages#show')->name('pages_show');
like image 489
VeroLom Avatar asked Jan 24 '11 12:01

VeroLom


1 Answers

It seems you want / to render either a login form OR a profile page. The code above will always show / as login because it hits that route condition first and will never care if you're authenticated or not.

Try a switch in your initial route for / (your default route after the bridge is unnecessary).

my $r = $self->routes;
$r->get('/' => sub {
    my $self = shift;
    # Check whatever you set during authentication
    my $template = $self->session('user') ? '/profile' : '/login';
    $self->render( template => $template );
});

A couple of notes on your example:

  • Its much easier to help debug issues if you use Mojolicious::Lite for examples.
  • Try using under instead of bridge.
  • Try using $r->get(..) instead of $r->route(..)->via(..)

Hope this helps.

like image 52
CoffeeMonster Avatar answered Nov 19 '22 00:11

CoffeeMonster