我正在寻找一个干净和简单的例子,如何在"Mojolicious“应用程序中使用"under”功能。我找到的所有示例都在处理"Mojolicious::Lite“(我不使用它)。例如,我在这里听了http://mojocasts.com/e3的截屏视频,我想我理解了under功能的概念。但是我没有使用"Mojolicious::Lite",所以我似乎不能直接遵循这个例子。对于非Lite风格,我一直尝试采用Lite-example失败。(这可能也是因为我对这个框架还比较陌生)
相关代码如下所示:
# 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) };但这不能编译,我就是找不到与这种代码风格相匹配的示例……有人能在这里给我正确的提示或链接吗?如果这是在文档中的某处请原谅我...它们可能是完整的,但对于像我这样头脑简单的人来说,它们缺乏可理解的例子:
发布于 2012-10-16 21:17:40
与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-16 20:59:59
我是这样做的--在一个完整的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;
}我希望这能帮到你
发布于 2016-12-31 00:39:35
我在我的应用程序中使用这个场景:
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;
}https://stackoverflow.com/questions/12915052
复制相似问题