Merge branch 'no-cleartext-passwords-in-db'
[kivitendo-erp.git] / SL / Auth / DB.pm
index 2ad131a..66d23cd 100644 (file)
@@ -1,10 +1,14 @@
 package SL::Auth::DB;
 
+use strict;
+
+use Carp;
+use Scalar::Util qw(weaken);
+
 use SL::Auth::Constants qw(:all);
+use SL::Auth::Password;
 use SL::DBUtils;
 
-use strict;
-
 sub new {
   $main::lxdebug->enter_sub();
 
@@ -12,6 +16,7 @@ sub new {
   my $self = {};
 
   $self->{auth} = shift;
+  weaken $self->{auth};
 
   bless $self, $type;
 
@@ -26,7 +31,6 @@ sub authenticate {
   my $self       = shift;
   my $login      = shift;
   my $password   = shift;
-  my $is_crypted = shift;
 
   my $dbh        = $self->{auth}->dbconnect();
 
@@ -38,8 +42,13 @@ sub authenticate {
   my $query             = qq|SELECT password FROM auth."user" WHERE login = ?|;
   my ($stored_password) = $dbh->selectrow_array($query, undef, $login);
 
-  $password        = crypt $password, substr($login, 0, 2)        if (!$password || !$is_crypted);
-  $stored_password = crypt $stored_password, substr($login, 0, 2) if (!$stored_password);
+  my ($algorithm, $algorithm2);
+
+  # Empty password hashes in the database mean just that -- empty
+  # passwords. Hash it for easier comparison.
+  $stored_password               = SL::Auth::Password->hash(password => $stored_password) unless $stored_password;
+  ($algorithm, $stored_password) = SL::Auth::Password->parse($stored_password);
+  ($algorithm2, $password)       = SL::Auth::Password->parse(SL::Auth::Password->hash_if_unhashed(password => $password, algorithm => $algorithm, login => $login));
 
   $main::lxdebug->leave_sub();
 
@@ -50,6 +59,10 @@ sub can_change_password {
   return 1;
 }
 
+sub requires_cleartext_password {
+  return 0;
+}
+
 sub change_password {
   $main::lxdebug->enter_sub();
 
@@ -65,7 +78,7 @@ sub change_password {
     return ERR_BACKEND;
   }
 
-  $password = crypt $password, substr($login, 0, 2) if (!$is_crypted);
+  $password = SL::Auth::Password->hash(password => $password) unless $is_crypted;
 
   do_query($main::form, $dbh, qq|UPDATE auth."user" SET password = ? WHERE login = ?|, $password, $login);