I am building an authentication system based upon the one found here:
https://github.com/alexanderBendo/Experiments/blob/master/exp0001/mojolicious-auth-session.pl
The problem I am having is that if a user enters the wrong username or password, the server is returning the flash message as if they tried to access a page without being logged in. It should be displaying an Invalid Credentials message. If I enter the bad credentials a second time, I get the Invalid Credentials message.
Here is the pertinent code:
sub main {
my $self = shift;
if ( $self->is_user_authenticated ) {
$self->redirect_to('/main/cp');
} else {
$self->flash( message => 'You must log in to view this page' );
$self->render('login');
}
}
sub login {
my $self = shift;
my $user = $self->param('name') || q{};
my $pass = $self->param('pass') || q{};
if ( $self->authenticate( $user, $pass ) ) {
$self->redirect_to('/main/cp');
} else {
$self->flash( message => 'Invalid credentials!' );
$self->render('login');
return;
}
}
Template:
% layout 'default';
% title 'Login';
<h1>Log In</h1>
<% if (my $message = flash 'message' ) { %>
<b><%= $message %></b><br>
<% } %>
<%= form_for login => (method => 'post') => begin %>
Name: <%= text_field 'name' %>
<br>
Password: <%= password_field 'pass' %>
<br>
<%= submit_button 'Login' %>
<% end %>
Thanks.
Flash need to use to save data between current and next query in session. So, flash
data is placed not immediately in session.
So, you must to do redirect_to('login_page')
except render('login_page')
.
If you don't want to do redirect you must to save your data into stash
:
sub main {
my $self = shift;
if ( $self->is_user_authenticated ) {
$self->redirect_to('/main/cp');
} else {
$self->stash( message => 'You must log in to view this page' );
$self->render('login');
}
}
Template:
% layout 'default';
% title 'Login';
<h1>Log In</h1>
<% if (my $message = stash 'message' ) { %>
<b><%= $message %></b><br>
<% } %>