Underwrite the process to be executed before all processes in Mojolicious

For example, when performing authentication, I would like to check if I am logged in just before all the processing. In such a case, use a function called under. Create an under () from the root to specify the callback you want to execute. If the return value of the callback is true, the continuation processing is performed, and if it is false, the continuation processing is not performed.

sub startup {
  my $self = shift;
  
  my $r = $self->routes;

  # certification
  $r = $r->under(sub {
    my $self = shift;
    
    if ($self->session('login_name')) {
      return 1;
    }
    else {
      my $url = $self->req->url->to_string;
      if ($url = ~ m # login $#) {
        return 1;
      }
      else {
        $self->render('denied');
        return;
      }
    }
  });

  $r->get('/')->name('index');
}

It looks a little strange, but I think the above writing is concise because the to method returns the under itself. It shares the unders with all routes, so it overwrites $r itself. If the session ID is not issued and you access other than the URL for logging in, authentication will draw a template to notify you of refusal.

Changes from Mojolicious 6

Starting with Mojolicious 6, the bridge method that creates a bridge has been integrated into the under method. The functionality is the same, so be sure to use the under method.

Associated Information