Need help with routing in Mojolicious
Asked Answered
F

1

5

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');
Flinger answered 24/1, 2011 at 12:56 Comment(2)
Could you explain what "does not want to work properly" mean? You have explained what it should do, but not what actually happens.Retene
Are you sure check() returns true when it's suppose to?Nickolasnickolaus
B
11

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.

Bagwig answered 24/2, 2011 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.