Acme-CPANModulesBundle-Import-MojoliciousAdvent-2018

 view release on metacpan or  search on metacpan

devdata/https_mojolicious.io_blog_2018_12_08_authenticating-with-ldap_  view on Meta::CPAN

<pre><code>sub check_credentials {
  my ($username, $password) = @_;

  my $statement = &#39;SELECT password FROM user_passwd WHERE username = ?&#39;;

  my $sth = $dbh-&gt;prepare($statement);
  $sth-&gt;execute($username) or return;
  my ($encoded) = $sth-&gt;fetchrow_array();
  $sth-&gt;finish();

  return password_verify($password, $encoded);
}
</code></pre>

<p><a href="https://metacpan.org/pod/Mojolicious::Plugin::Scrypt">Mojolicious::Plugin::Scrypt</a>
will use the Scrypt algorithm,
but can also use Argon2 (which was recommended to me at LPW), Bcrypt and more.
So, assuming that you&#39;ve stored your password with
<code>my $encoded = $app-&gt;scrypt($password);</code>
the <code>on_user_login</code> sub becomes</p>

devdata/https_mojolicious.io_blog_2018_12_08_authenticating-with-ldap_  view on Meta::CPAN

  my ($username, $password) = @_;

  my $statement = &#39;SELECT password FROM user_passwd WHERE username = ?&#39;;

  my $sth = $dbh-&gt;prepare($statement);
  $sth-&gt;execute($username) or return;
  my ($encoded) = $sth-&gt;fetchrow_array();
  $sth-&gt;finish();

  # WAIT! where did $self come from
  return $self-&gt;scrypt_verify($password, $encoded);
}
</code></pre>

<p>Oh, dear.  The above crashes because of a design decision made early on in the writing process.
I invoked <code>check_credentials</code> as a plain sub, not the method of an object.
Using a Plugin depends on having the controller available, so the following changes are necessary.</p>

<pre><code>sub on_user_login {
  my $self = shift;
...

  if ($self-&gt;check_credentials($username, $password)) {
...
}

sub check_credentials {
  my ($self, $username, $password) = @_;
...
  return $self-&gt;scrypt_verify($password, $encoded);
}
</code></pre>

<p>Y&#39;know, I&#39;m sitting here on the Group W bench thinkin&#39; ...
if I&#39;m going to re-write this whole tutorial, maybe I should&#39;ve started with
<a href="https://metacpan.org/pod/Mojolicious::Plugin::Authentication">Mojolicious::Plugin::Authentication</a>
and taken you through the code you needed for the <code>validate_user</code> option in the Plugin.
But let&#39;s leave that for next year.</p>

<p>Further reading on storing passwords:</p>



( run in 0.332 second using v1.01-cache-2.11-cpan-5467b0d2c73 )