且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mojolicious基本登录

更新时间:2023-12-05 14:26:40

以下是您想要的示例

#!/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>