From 3dbc934f01cb8ddc81b9dbecd01764568ed7e32a Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Thu, 16 Aug 2018 07:13:56 -0300 Subject: [PATCH] Bug 21178: Add Koha::Patron::set_password This patch introduces the 'set_password' method for Koha::Patron objects. The main point is to make password changing atomic (update_password touches the userid on the DB, which should be done carefully with better error handling, and it is done there only for legacy backwards compatibility). A follow-up bug will make the codebase use this instead of update_password, and use a proper method for changing the userid if required. To test: - Apply this patchset - Run: $ kshell k$ prove t/db_dependent/Koha/Patrons.t => SUCCESS: Tests pass! - Sign off! :-D --- Koha/Patron.pm | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/Koha/Patron.pm b/Koha/Patron.pm index 660a447d12..1984b500ea 100644 --- a/Koha/Patron.pm +++ b/Koha/Patron.pm @@ -33,6 +33,7 @@ use Koha::AuthUtils; use Koha::Checkouts; use Koha::Database; use Koha::DateUtils; +use Koha::Exceptions::Password; use Koha::Holds; use Koha::Old::Checkouts; use Koha::Patron::Categories; @@ -702,6 +703,66 @@ sub update_password { return $digest; } +=head3 set_password + + $patron->set_password( $plain_text_password ); + +Set the patron's password. + +=head4 Exceptions + +The passed string is validated against the current password enforcement policy. +Exceptions are thrown if the password is not good enough. + +=over 4 + +=item Koha::Exceptions::Password::TooShort + +=item Koha::Exceptions::Password::TrailingWhitespaces + +=item Koha::Exceptions::Password::TooWeak + +=back + +=cut + +sub set_password { + my ( $self, $password ) = @_; + + my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password ); + + if ( !$is_valid ) { + if ( $error eq 'too_short' ) { + my $min_length = C4::Context->preference('minPasswordLength'); + $min_length = 3 if not $min_length or $min_length < 3; + + my $password_length = length($password); + Koha::Exceptions::Password::TooShort->throw( + { length => $password_length, min_length => $min_length } ); + } + elsif ( $error eq 'has_whitespaces' ) { + Koha::Exceptions::Password::TrailingWhitespaces->throw( + "Password contains trailing spaces, which is forbidden."); + } + elsif ( $error eq 'too_weak' ) { + Koha::Exceptions::Password::TooWeak->throw(); + } + } + + my $digest = Koha::AuthUtils::hash_password($password); + $self->update( + { password => $digest, + login_attempts => 0, + } + ); + + logaction( "MEMBERS", "CHANGE PASS", $self->borrowernumber, "" ) + if C4::Context->preference("BorrowersLog"); + + return $self; +} + + =head3 renew_account my $new_expiry_date = $patron->renew_account -- 2.18.0