9

我正在寻找一个干净简单的示例,说明如何在“Mojolicious”应用程序中使用“under”功能。我发现的所有示例都在处理“Mojolicious::Lite”(我不使用)。例如,我在这里收听了截屏视频http://mojocasts.com/e3,我想我理解了底层功能的概念。但是我没有使用“Mojolicious::Lite”,所以我似乎无法直接按照示例进行操作。我一直未能尝试将 Lite 示例用于非 Lite 样式。(这可能也是因为我对框架还是个新手)

相关代码如下所示:

# Router
my $r = $self->routes;

# Normal route to controller
$r->get('/') ->to('x#a');
$r->get('/y')->to('y#b');
$r->any('/z')->to('z#c');

所以所有这些路由都需要由用户/通行证保护。我试图做这样的事情:

$r->under = sub { return 1 if ($auth) };

但这无法编译,我只是找不到与这种代码风格匹配的示例......有人可以在这里给我正确的提示或链接吗?如果这是文档中的某个地方,请原谅我......它们可能是完整的,但对于像我这样头脑简单的人来说,它们缺乏可以理解的例子:-P

4

3 回答 3

15

Lite-examples 的类似代码如下所示:

# Router
my $r = $self->routes;

# This route is public
$r->any('/login')->to('login#form');

# this sub does the auth-stuff
# you can use stuff like: $self->param('password')
# to check user/pw and return true if fine
my $auth = $r->under( sub { return 1 } );

# This routes are protected
$auth->get ('/') ->to('x#a');
$auth->post('/y')->to('y#b');
$auth->any ('/z')->to('z#c');

希望这对任何人都有帮助!

(在这里找到的解决方案:http: //mojolicio.us/perldoc/Mojolicious/Routes/Route#under

于 2012-10-16T13:17:40.173 回答
3

我正在这样做 - 在一个完整的 mojo(不是 lite)应用程序中:

startup方法中

$self->_add_routes_authorization();

# only users of type 'cashier' will have access to routes starting with /cashier
my $cashier_routes = $r->route('/cashier')->over( user_type => 'cashier' );
$cashier_routes->route('/bank')->to('cashier#bank');

# only users of type 'client' will have access to routes starting with /user
my $user_routes = $r->route('/user')->over( user_type => 'client' );
$user_routes->get('/orders')->to('user#orders');

在主应用程序文件中:

sub _add_routes_authorization {
  my $self = shift;

  $self->routes->add_condition(
    user_type => sub {
      my ( $r, $c, $captures, $user_type ) = @_;

      # Keep the weirdos out!
      # $self->user is the current logged in user, as a DBIC instance
      return
        if ( !defined( $self->user )
        || $self->user->user_type()->type() ne $user_type );

      # It's ok, we know him
      return 1;
    }
  );

  return;
}

我希望这有帮助

于 2012-10-16T12:59:59.333 回答
0

我在我的应用程序中使用了这个场景:

my $guest =  $r->under->to( "auth#check_level" );
my $user  =  $r->under->to( "auth#check_level", { required_level =>  100 } );
my $admin =  $r->under->to( "auth#check_level", { required_level =>  200 } );


$guest->get ( '/login'  )->to( 'auth#login'  );
$user ->get ( '/users/profile' )->to( 'user#show' );

在这之后所有的子路径$r都会遍历check_level子程序:

sub check_level {
    my( $self ) =  @_;

    # GRANT   If we do not require any access privilege
    my $rl =  $self->stash->{ required_level };
    return 1   if !$rl;

    # GRANT   If logged in user has required level OR we raise user level one time
    my $sl =  $self->session->{ user_level };
    my $fl =  $self->flash( 'user_level' );
    return 1   if $sl >= $rl  ||  $fl && $fl >= $rl;

    # RESTRICT 
    $self->render( 'auth/login',  status => 403 );
    return 0;
}
于 2016-12-30T16:39:34.800 回答