Mojolicious basic login with

1.2k views Asked by At

iam looking for authentification in Mojolicious. I have 2 pages momcorp1 and momcorp2, But i cant pas between over pages, someone know how do this.

Iam reaading about "under", but i dont undertah how do this.

The other form do this is use -Mojolicious::Plugin::Authentication - but is more dificult.

This is the code, when 1 click link to momcorp 2, show error.

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

There are 1 answers

2
Logioniz On BEST ANSWER

Here's an example of what you want

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