1 package Koha::Auth::Client::OAuth;
3 # Copyright Theke Solutions 2022
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use JSON qw( decode_json );
23 use MIME::Base64 qw{ decode_base64url };
28 use base qw( Koha::Auth::Client );
32 Koha::Auth::Client::OAuth - Koha OAuth Client
38 =head3 _get_data_and_patron
40 my $mapping = $object->_get_data_and_patron(
41 { provider => $provider,
47 Maps OAuth raw data to a patron schema, and returns a patron if it can.
51 sub _get_data_and_patron {
52 my ( $self, $params ) = @_;
54 my $provider = $params->{provider};
55 my $data = $params->{data};
56 my $config = $params->{config};
61 my $mapping = decode_json( $provider->mapping );
62 my $matchpoint = $provider->matchpoint;
64 if ( $data->{id_token} ) {
65 my ( $header_part, $claims_part, $footer_part ) = split( /\./, $data->{id_token} );
67 my $claim = decode_json( decode_base64url($claims_part) );
68 foreach my $key ( keys %$mapping ) {
69 my $pkey = $mapping->{$key};
70 $mapped_data->{$key} = $claim->{$pkey}
71 if defined $claim->{$pkey};
74 my $value = $mapped_data->{$matchpoint};
76 my $matchpoint_rs = Koha::Patrons->search( { $matchpoint => $value } );
78 if ( defined $value and $matchpoint_rs->count ) {
79 $patron = $matchpoint_rs->next;
82 return ( $mapped_data, $patron )
86 if ( defined $config->{userinfo_url} ) {
87 my $access_token = $data->{access_token};
88 my $ua = Mojo::UserAgent->new;
89 my $tx = $ua->get( $config->{userinfo_url} => { Authorization => "Bearer $access_token" } );
90 my $code = $tx->res->code || 'No response';
92 return if $code ne '200';
94 $tx->res->headers->content_type =~ m!^(application/json|text/javascript)(;\s*charset=\S+)?$!
96 : Mojo::Parameters->new( $tx->res->body )->to_hash;
98 foreach my $key ( keys %$mapping ) {
99 my $pkey = $mapping->{$key};
100 my $value = $self->_tranverse_hash( { base => $claim, keys => $pkey } );
101 $mapped_data->{$key} = $value
105 my $value = $mapped_data->{$matchpoint};
107 my $matchpoint_rs = Koha::Patrons->search( { $matchpoint => $value } );
109 if ( defined $value and $matchpoint_rs->count ) {
110 $patron = $matchpoint_rs->next;
113 return ( $mapped_data, $patron )