Search code examples
perlmojolicious

How to pass additional parameters to `under` subroutine in Mojolicious?


I have two routes:

$auth =  $r->under( \&auth );
$auth->get( "/test",   { level => 'user' }  )->to( "C#A1" );
$auth->get( "/secure", { level => 'admin' } )->to( "C#A2" );

I use under to check access level. But when auth subroutine is called it has not yet { level } value. The { level } will be available only at action.

How better pass to &auth function required user level for target route?


Solution

  • I have found answer. I should use stack method:

    sub auth {
        ...
        return 1   if $c->match->stack->[-1]{ level } <= $user->level;
    }
    

    It contains:

    [
      { api => 1, cb => sub { ... } },                     # stash at &auth
      { api => 1, cb => sub { ... }, level => "user" },    # stash at &C#A*
    ]