Mojolicious基本登录用

时间:2017-11-30 18:44:34

标签: login mojolicious mojolicious-lite

我正在寻找Mojolicious中的身份验证。我有2页momcorp1和momcorp2,但我不能 在页面之间,有人知道这是怎么做的。

Iam reaading about“under”,但我不知道怎么做。

另一种形式是使用-Mojolicious :: Plugin :: Authentication - 但更难以理解。

这是代码,当单击链接到momcorp 2时,显示错误。

#!/usr/bin/env perl
use Mojolicious::Lite;

helper auth => sub {
my $self = shift;

return 1 if
$self->param('username') eq 'user1' and
$self->param('password') eq 'user1';
};

get '/login'=> sub { shift->render('login') };

under sub {
my $self = shift;
return 1 if $self->auth;

$self->render(text => 'denied');
return;
};

post 'momcorp' => sub { shift->render(template => 'momcorp1') };

post '/momcorp/carol' => sub { shift->render(template => 'momcorp2') 
};

app->start

__DATA__

@@ login.html.ep
%= t h1 => 'login'
%= form_for '/momcorp' => (method => 'post') => begin
username: <%= text_field 'username' %>
password: <%= text_field 'password' %>
%= submit_button 'log in' 
%= end

@@ momcorp1.html.ep
%= t h1 => 'momcorp1'
 <a href="/momcorp/carol">Link to 2</a>

@@ momcorp2.html.ep
%= t h1 => 'momcorp2'
<a href="/momcorp">Link to 1</a>

1 个答案:

答案 0 :(得分:3)

以下是您想要的示例

#!/usr/bin/env perl
use Mojolicious::Lite;

helper auth => sub {
  my $c = shift;

  return 1 if
  $c->param('username') eq 'user1' and
  $c->param('password') eq 'pass1';
  return 0;
};

get '/'=> sub { shift->render } => 'index';

post '/login' => sub {
  my $c = shift;
  if ($c->auth) {
    $c->session(auth => 1);
    return $c->redirect_to('t1');
  }
  $c->flash('error' => 'Wrong login/password');
  $c->redirect_to('index');
} => 'login';

get '/logout' => sub {
  my $c = shift;
  delete $c->session->{auth};
  $c->redirect_to('index');
} => 'logout';

under sub {
  my $c = shift;
  return 1 if ($c->session('auth') // '') eq '1';

  $c->render(text => 'denied');
  return undef;
};

get '/test1' => sub { shift->render } => 't1';

get '/test2' => sub { shift->render } => 't2';

app->start;

__DATA__

@@ index.html.ep
%= t h1 => 'login'

% if (flash('error')) {
  <h2 style="color:red"><%= flash('error') %></h2>
% }

%= form_for login => (method => 'post') => begin
username: <%= text_field 'username' %>
password: <%= text_field 'password' %>
%= submit_button 'log in'
%= end

@@ t1.html.ep
%= t h1 => 'test1'
<a href="<%= url_for('t2') %>">Link to test2</a>

@@ t2.html.ep
%= t h1 => 'This is test2'

<a href="<%= url_for('logout') %>">logout</a>
相关问题