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::Auth;
use cyberman::Account;
use cyberman::Helper;
use cyberman::API;

View File

@ -5,6 +5,8 @@ use Dancer2::Plugin::Database;
get '/api/check_availability' => sub {
# No auth req'd
# returns 'y' or 'n'
# TODO: check name validity here
if (!param("name")) {
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::Plugin::Database;
use Digest::Bcrypt;
use Math::Random::Secure qw(irand);
use cyberman::Helper;
@ -36,20 +34,14 @@ post '/register' => sub {
};
}
# Hash password
my $salt = randstring(16);
my $b = new Digest::Bcrypt;
$b->cost(8);
$b->salt($salt);
$b->add(param "password");
my ($hash, $salt) = hash_password(param("password"));
# Create the account in the database
database->quick_insert(
"user",
{
"email" => param("email"),
"password" => $b->bcrypt_b64digest,
"password" => $hash,
"salt" => $salt,
},
);
@ -76,12 +68,9 @@ post '/login' => sub {
}
if (scalar(keys(%errs)) == 0) {
my $b = new Digest::Bcrypt;
$b->cost(8);
$b->salt($user->{"salt"});
$b->add(param "password");
$errs{"e_pass"} = 1 unless $b->bcrypt_b64digest eq $user->{"password"};
my ($hash, $salt) = hash_password(param("password"), $user->{"salt"});
warn $hash;
$errs{"e_pass"} = 1 unless $hash eq $user->{"password"};
}
if (scalar(keys(%errs)) == 0) {

View File

@ -3,10 +3,11 @@ use base qw(Exporter);
use Dancer2 appname => "cyberman";
use Math::Random::Secure qw(irand);
use Digest::Bcrypt;
use Exporter qw(import);
our @EXPORT = qw(auth_test randstring);
our @EXPORT = qw(auth_test randstring hash_password);
# Helper functions
@ -41,4 +42,22 @@ sub randstring {
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;