我正在寻找一个简洁的例子,说明如何在“Mojolicious”应用程序中使用“under”功能。我发现的所有例子都涉及“Mojolicious :: Lite”(我不使用)。 例如,我在这里听了截屏视频http://mojocasts.com/e3,我想我理解了功能不足的概念。但我不使用“Mojolicious :: Lite”,所以似乎我不能直接按照这个例子。我一直未能尝试采用Lite-example的非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');
因此所有这些路由都需要通过user / pass保护。我试着做这样的事情:
$r->under = sub { return 1 if ($auth) };
但这不编译,我只是找不到匹配此代码风格的示例... 任何人都可以给我正确的提示或链接吗? 请原谅我,如果这是在文档中的某个地方...它们可能是完整的,但对于像我这样的简单头脑的人来说,他们缺乏可以理解的例子:-P
答案 0 :(得分:12)
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)
答案 1 :(得分:3)
我这样做 - 在一个完整的mojo(不是精简版)app:
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;
}
我希望这会有所帮助
答案 2 :(得分: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;
}