From be1dec7648870b48121eb8e50dd673d10b684c3b Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Mon, 7 Jan 2019 08:25:08 -0300 Subject: [PATCH] Bug 22061: Public route to change password This patch implements a route to change patron's password for unprivileged users. It's intended for using in the OPAC (or however consumers find it useful). It is a starting point for the public API, and the bug also implements the on/off switch some community members asked for. To test: - Apply this patches - Run: $ kshell k$ prove t/db_dependent/api/v1/patrons_password.t \ t/db_dependent/api/v1/auth.t => SUCCESS: Tests pass! i.e. - RESTPublicAPI is honoured - The /public/patrons/:patron_id/password endpoint works as expected - Use your favourite API testing tool to try the endpoint. - Sign off :-D Signed-off-by: Josef Moravec Signed-off-by: Kyle M Hall Signed-off-by: Nick Clemens --- Koha/REST/V1/Patrons/Password.pm | 62 ++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/Koha/REST/V1/Patrons/Password.pm b/Koha/REST/V1/Patrons/Password.pm index db8512e47c..8a1868ee51 100644 --- a/Koha/REST/V1/Patrons/Password.pm +++ b/Koha/REST/V1/Patrons/Password.pm @@ -19,6 +19,8 @@ use Modern::Perl; use Mojo::Base 'Mojolicious::Controller'; +use C4::Auth qw(checkpw_internal); + use Koha::Patrons; use Scalar::Util qw(blessed); @@ -73,4 +75,64 @@ sub set { }; } +=head3 set_public + +Controller method that sets a patron's password, for unprivileged users + +=cut + +sub set_public { + + my $c = shift->openapi->valid_input or return; + + my $body = $c->validation->param('body'); + my $patron_id = $c->validation->param('patron_id'); + + unless ( C4::Context->preference('OpacPasswordChange') ) { + return $c->render( + status => 403, + openapi => { error => "Configuration prevents password changes by unprivileged users" } + ); + } + + my $user = $c->stash('koha.user'); + + unless ( $user->borrowernumber == $patron_id ) { + return $c->render( + status => 403, + openapi => { + error => "Changing other patron's password is forbidden" + } + ); + } + + my $old_password = $body->{old_password}; + my $password = $body->{password}; + my $password_2 = $body->{password_2}; + + unless ( $password eq $password_2 ) { + return $c->render( status => 400, openapi => { error => "Passwords don't match" } ); + } + + return try { + my $dbh = C4::Context->dbh; + unless ( checkpw_internal($dbh, $user->userid, $old_password ) ) { + Koha::Exceptions::Authorization::Unauthorized->throw("Invalid password"); + } + + ## Change password + $user->set_password($password); + + return $c->render( status => 200, openapi => "" ); + } + catch { + unless ( blessed $_ && $_->can('rethrow') ) { + return $c->render( status => 500, openapi => { error => "$_" } ); + } + + # an exception was raised. return 400 with the stringified exception + return $c->render( status => 400, openapi => { error => "$_" } ); + }; +} + 1; -- 2.39.5