Split out password hasing code

This commit is contained in:
Al Beano 2017-07-17 14:25:45 +01:00
parent 2d6f62eefe
commit d66b72d34e
5 changed files with 33 additions and 17 deletions

View File

@ -5,6 +5,7 @@ use Dancer2::Plugin::Database;
use cyberman::Domains; use cyberman::Domains;
use cyberman::Auth; use cyberman::Auth;
use cyberman::Account;
use cyberman::Helper; use cyberman::Helper;
use cyberman::API; use cyberman::API;

View File

@ -5,6 +5,8 @@ use Dancer2::Plugin::Database;
get '/api/check_availability' => sub { get '/api/check_availability' => sub {
# No auth req'd # No auth req'd
# returns 'y' or 'n' # returns 'y' or 'n'
# TODO: check name validity here
if (!param("name")) { if (!param("name")) {
return "n"; return "n";

5
lib/cyberman/Account.pm Normal file
View File

@ -0,0 +1,5 @@
package cyberman::Account;
use Dancer2 appname => "cyberman";
use Dancer2::Plugin::Database;
true;

View File

@ -2,8 +2,6 @@ package cyberman::Auth;
use Dancer2 appname => "cyberman"; use Dancer2 appname => "cyberman";
use Dancer2::Plugin::Database; use Dancer2::Plugin::Database;
use Digest::Bcrypt;
use Math::Random::Secure qw(irand);
use cyberman::Helper; use cyberman::Helper;
@ -36,20 +34,14 @@ post '/register' => sub {
}; };
} }
# Hash password my ($hash, $salt) = hash_password(param("password"));
my $salt = randstring(16);
my $b = new Digest::Bcrypt;
$b->cost(8);
$b->salt($salt);
$b->add(param "password");
# Create the account in the database # Create the account in the database
database->quick_insert( database->quick_insert(
"user", "user",
{ {
"email" => param("email"), "email" => param("email"),
"password" => $b->bcrypt_b64digest, "password" => $hash,
"salt" => $salt, "salt" => $salt,
}, },
); );
@ -76,12 +68,9 @@ post '/login' => sub {
} }
if (scalar(keys(%errs)) == 0) { if (scalar(keys(%errs)) == 0) {
my $b = new Digest::Bcrypt; my ($hash, $salt) = hash_password(param("password"), $user->{"salt"});
$b->cost(8); warn $hash;
$b->salt($user->{"salt"}); $errs{"e_pass"} = 1 unless $hash eq $user->{"password"};
$b->add(param "password");
$errs{"e_pass"} = 1 unless $b->bcrypt_b64digest eq $user->{"password"};
} }
if (scalar(keys(%errs)) == 0) { if (scalar(keys(%errs)) == 0) {

View File

@ -3,10 +3,11 @@ use base qw(Exporter);
use Dancer2 appname => "cyberman"; use Dancer2 appname => "cyberman";
use Math::Random::Secure qw(irand); use Math::Random::Secure qw(irand);
use Digest::Bcrypt;
use Exporter qw(import); use Exporter qw(import);
our @EXPORT = qw(auth_test randstring); our @EXPORT = qw(auth_test randstring hash_password);
# Helper functions # Helper functions
@ -41,4 +42,22 @@ sub randstring {
return $ret; return $ret;
} }
sub hash_password {
my $plaintext = shift;
my $salt;
if (scalar(@_) > 0) {
$salt = shift;
} else {
$salt = randstring(16);
}
my $b = new Digest::Bcrypt;
$b->cost(8);
$b->salt($salt);
$b->add($plaintext);
return ($b->bcrypt_b64digest, $salt);
}
1; 1;