View | Details | Raw Unified | Return to bug 30988
Collapse All | Expand All

(-)a/C4/Auth.pm (+7 lines)
Lines 1478-1483 sub checkauth { Link Here
1478
        }
1478
        }
1479
    }
1479
    }
1480
1480
1481
    if (C4::Context->preference('OIDC')) {
1482
        if ($query->param("OIDCFailed")) {
1483
            my $reason = $query->param('OIDCFailed');
1484
            $template->param(invalidOIDCLogin => $reason);
1485
        }
1486
    }
1487
1481
    $template->param(
1488
    $template->param(
1482
        LibraryName => C4::Context->preference("LibraryName"),
1489
        LibraryName => C4::Context->preference("LibraryName"),
1483
    );
1490
    );
(-)a/installer/data/mysql/atomicupdate/bug_30988-add_oidc_syspref.pl (+24 lines)
Line 0 Link Here
1
use Modern::Perl;
2
3
return {
4
    bug_number => "30988",
5
    description => "Add OIDC related system preferences",
6
    up => sub {
7
        my ($args) = @_;
8
        my ($dbh, $out) = @$args{qw(dbh out)};
9
10
        $dbh->do(q{
11
            INSERT IGNORE INTO systempreferences (variable,value,explanation,options,type)
12
            VALUES
13
            ('OIDC','0',NULL,'if ON, allows the use of OpenID Connect for login','YesNo'),
14
            ('OIDCConfigURL','',NULL,"URL to identity provider's OpenID Connect config",'Free'),
15
            ('OIDCClientID','', NULL,'Client ID for the web app','Free'),
16
            ('OIDCClientSecret','',NULL,'Client Secret for the web app','Free'),
17
            ('OIDCAutoRegister','0',NULL,'OpenID Connect logins to auto-register patrons','YesNo'),
18
            ('OIDCDefaultBranch',  '','','This branch code will be used to create OpenID Connect patrons.','Textarea'),
19
            ('OIDCDefaultCategory','','','This category code will be used to create OpenID Connect patrons.','Textarea'),
20
            ('OIDCDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all domains', 'Free'),
21
            ('OIDCProviderName', 'OpenID Connect', NULL, 'Name of identity provider to display', 'Free')
22
        });
23
    },
24
};
(-)a/installer/data/mysql/mandatory/sysprefs.sql (+9 lines)
Lines 393-398 INSERT INTO systempreferences ( `variable`, `value`, `options`, `explanation`, ` Link Here
393
('OAI-PMH:ConfFile','',NULL,'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','File'),
393
('OAI-PMH:ConfFile','',NULL,'If empty, Koha OAI Server operates in normal mode, otherwise it operates in extended mode.','File'),
394
('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent), might be deleted (transient), or will never have any data in it (no)','transient|persistent|no','Choice'),
394
('OAI-PMH:DeletedRecord','persistent','Koha\'s deletedbiblio table will never be deleted (persistent), might be deleted (transient), or will never have any data in it (no)','transient|persistent|no','Choice'),
395
('OAI-PMH:MaxCount','50',NULL,'OAI-PMH maximum number of records by answer to ListRecords and ListIdentifiers queries','Integer'),
395
('OAI-PMH:MaxCount','50',NULL,'OAI-PMH maximum number of records by answer to ListRecords and ListIdentifiers queries','Integer'),
396
('OIDC','0',NULL,'if ON, allows the use of OpenID Connect for login','YesNo'),
397
('OIDCAutoRegister','0',NULL,'OpenID Connect logins to auto-register patrons','YesNo'),
398
('OIDCClientID', '', NULL, 'Client ID for the web app', 'Free'),
399
('OIDCClientSecret', '', NULL, 'Client Secret for the web app', 'Free'),
400
('OIDCConfigURL','',NULL,"URL to identity provider's OpenID Connect config",'Free'),
401
('OIDCDefaultBranch',  '','','This branch code will be used to create OpenID Connect patrons.','Textarea'),
402
('OIDCDefaultCategory','','','This category code will be used to create OpenID Connect patrons.','Textarea'),
403
('OIDCDomain', '', NULL, 'Restrict OpenID Connect to this domain (or subdomains of this domain). Leave blank for all domains', 'Free'),
404
('OIDCProviderName', 'OpenID Connect', NULL, 'Name of identity provider to display', 'Free'),
396
('OPACAcquisitionDetails','0','','Show the acquisition details at the OPAC','YesNo'),
405
('OPACAcquisitionDetails','0','','Show the acquisition details at the OPAC','YesNo'),
397
('OpacAddMastheadLibraryPulldown','0','','Adds a pulldown menu to select the library to search on the opac masthead.','YesNo'),
406
('OpacAddMastheadLibraryPulldown','0','','Adds a pulldown menu to select the library to search on the opac masthead.','YesNo'),
398
('OpacAdvSearchMoreOptions','pubdate,itemtype,language,subtype,sorting,location','Show search options for the expanded view (More options)','pubdate|itemtype|language|subtype|sorting|location','multiple'),
407
('OpacAdvSearchMoreOptions','pubdate,itemtype,language,subtype,sorting,location','Show search options for the expanded view (More options)','pubdate|itemtype|language|subtype|sorting|location','multiple'),
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/preferences/admin.pref (+43 lines)
Lines 171-176 Administration: Link Here
171
                  None: "None"
171
                  None: "None"
172
                  Common Name: Common Name
172
                  Common Name: Common Name
173
                  emailAddress: emailAddress
173
                  emailAddress: emailAddress
174
    OpenID Connect:
175
        -
176
            - "Use OpenID Connect login in the OPAC: "
177
            - pref: OIDC
178
              choices:
179
                1: "Yes"
180
                0: "No"
181
            - You will need to create an app in your chosen identity provider and activate OAuth2. Requires <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCConfigURL">OIDCConfigURL</a>, <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCClientID">OIDCClientID</a> and <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCClientSecret">OIDCClientSecret</a>
182
        -
183
            - "URL to your identity provider's OpenID Connect configuration: "
184
            - pref: OIDCConfigURL
185
            - Along with <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCClientID">OIDCClientID</a> and <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCClientSecret">OIDCClientSecret</a>. Enables <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC.</a>
186
        -
187
            - "OIDC Client ID: "
188
            - pref: OIDCClientID
189
            - Along with <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCConfigURL">OIDCConfigURL</a> and <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCClientSecret">OIDCClientSecret</a>. Enables <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC.</a>
190
        -
191
            - "OIDC Client Secret: "
192
            - pref: OIDCClientSecret
193
            - Along with <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCConfigURL">OIDCConfigURL</a> and <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCClientID">OIDCClientID</a>. Enables <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC.</a>
194
        -
195
            - pref: OIDCAutoRegister
196
              choices:
197
                1: Allow
198
                0: "Don't allow"
199
            - patrons logging in with OpenID Connect to automatically register. Requires <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC</a>.
200
        -
201
            - "Use this category code when automatically registering a patron using OpenID Connect: "
202
            - pref: OIDCDefaultCategory
203
              choices: patron-categories
204
            - Requires <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC</a>.
205
        -
206
            - "Use this branch code when automatically registering a patron using OpenID Connect: "
207
            - pref: OIDCDefaultBranch
208
            - Requires <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC</a>.
209
        -
210
            - "Restrict OpenID Connect to this domain (or subdomain of this domain): "
211
            - pref: OIDCDomain
212
            - Leave blank for all domains. Requires <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDC">OIDC</a>.
213
        -
214
            - "Name of identity provider : "
215
            - pref: OIDCProviderName
216
            - Associated with <a href="/cgi-bin/koha/admin/preferences.pl?op=search&searchfield=OIDCConfigURL">OIDCConfigURL</a>.
174
    Google OpenID Connect:
217
    Google OpenID Connect:
175
        -
218
        -
176
            - "Use Google OpenID Connect login in the OPAC: "
219
            - "Use Google OpenID Connect login in the OPAC: "
(-)a/koha-tmpl/opac-tmpl/bootstrap/en/includes/masthead.inc (+5 lines)
Lines 101-106 Link Here
101
                                        <a class="nav-link login-link" href="/cgi-bin/koha/opac-user.pl"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
101
                                        <a class="nav-link login-link" href="/cgi-bin/koha/opac-user.pl"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
102
                                [% ELSIF ( Koha.Preference('GoogleOpenIDConnect') == 1 ) %]
102
                                [% ELSIF ( Koha.Preference('GoogleOpenIDConnect') == 1 ) %]
103
                                    <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="nav-link login-link loginModal-trigger"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
103
                                    <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="nav-link login-link loginModal-trigger"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
104
                                [% ELSIF ( Koha.Preference('OIDC') == 1 ) %]
105
                                    <a href="/cgi-bin/koha/svc/auth/openidconnect" class="nav-link login-link loginModal-trigger"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
104
                                [% ELSE %]
106
                                [% ELSE %]
105
                                    <a href="/cgi-bin/koha/opac-user.pl" class="nav-link login-link loginModal-trigger"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
107
                                    <a href="/cgi-bin/koha/opac-user.pl" class="nav-link login-link loginModal-trigger"><i class="fa fa-user fa-icon-black fa-fw" aria-hidden="true"></i> <span class="userlabel">Log in to your account</span></a>
106
                                [% END %]
108
                                [% END %]
Lines 368-373 Link Here
368
                            <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="btn btn-light" id="openid_connect"><i class="fa fa-google" aria-hidden="true"></i> Log in with Google</a>
370
                            <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="btn btn-light" id="openid_connect"><i class="fa fa-google" aria-hidden="true"></i> Log in with Google</a>
369
                            <p>If you do not have a Google account, but do have a local account, you can still log in: </p>
371
                            <p>If you do not have a Google account, but do have a local account, you can still log in: </p>
370
                        [% END # /IF GoogleOpenIDConnect %]
372
                        [% END # /IF GoogleOpenIDConnect %]
373
                        [% IF ( Koha.Preference('OIDC') == 1 ) %]
374
                            <a href="/cgi-bin/koha/svc/auth/openidconnect" class="btn btn-light" id="oidc">Log in with [% Koha.Preference('OIDCProviderName') | html %]</a>
375
                        [% END # /IF OIDC %]
371
                        [% IF ( shibbolethAuthentication ) %]
376
                        [% IF ( shibbolethAuthentication ) %]
372
                            [% IF ( invalidShibLogin ) %]
377
                            [% IF ( invalidShibLogin ) %]
373
                                <!-- This is what is displayed if shibboleth login has failed to match a koha user -->
378
                                <!-- This is what is displayed if shibboleth login has failed to match a koha user -->
(-)a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-auth.tt (+8 lines)
Lines 165-170 Link Here
165
                                <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="btn btn-light" id="openid_connect"><i class="fa fa-google" aria-hidden="true"></i> Log in with Google</a>
165
                                <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="btn btn-light" id="openid_connect"><i class="fa fa-google" aria-hidden="true"></i> Log in with Google</a>
166
                                <p>If you do not have a Google account, but do have a local account, you can still log in: </p>
166
                                <p>If you do not have a Google account, but do have a local account, you can still log in: </p>
167
                            [% END # /IF GoogleOpenIDConnect %]
167
                            [% END # /IF GoogleOpenIDConnect %]
168
                            [% IF ( Koha.Preference('OIDC') == 1 ) %]
169
                                [% IF ( invalidOIDCLogin ) %]
170
                                    <h2>OpenID login</h2>
171
                                    <p>Sorry, your login using [% Koha.Preference('OIDCProviderName') | html %] failed. <span class="error">[% invalidOIDCLogin | html %]</span></p>
172
                                    <p>Please note that the login will only work if you are using the e-mail address registered with this library.</p>
173
                                [% END %]
174
                                <a href="/cgi-bin/koha/svc/auth/openidconnect" class="btn btn-light" id="oidc">Log in with [% Koha.Preference('OIDCProviderName') | html %]</a>
175
                            [% END # /IF OIDC %]
168
                        [% END # /UNLESS OPACShibOnly %]
176
                        [% END # /UNLESS OPACShibOnly %]
169
177
170
                        [% IF !(invalid_username_or_password || too_many_login_attempts) and password_has_expired %]
178
                        [% IF !(invalid_username_or_password || too_many_login_attempts) and password_has_expired %]
(-)a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-main.tt (+3 lines)
Lines 189-194 Link Here
189
                                            <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="btn btn-light" id="openid_connect"><i class="fa fa-google" aria-hidden="true"></i> Log in with Google</a>
189
                                            <a href="/cgi-bin/koha/svc/auth/googleopenidconnect" class="btn btn-light" id="openid_connect"><i class="fa fa-google" aria-hidden="true"></i> Log in with Google</a>
190
                                            <p>If you do not have a Google account, but do have a local account, you can still log in: </p>
190
                                            <p>If you do not have a Google account, but do have a local account, you can still log in: </p>
191
                                        [% END # /IF GoogleOpenIDConnect %]
191
                                        [% END # /IF GoogleOpenIDConnect %]
192
                                        [% IF ( Koha.Preference('OIDC') == 1 ) %]
193
                                            <a href="/cgi-bin/koha/svc/auth/openidconnect" class="btn btn-light" id="oidc">Log in with [% Koha.Preference('OIDCProviderName') | html %]</a>
194
                                        [% END # /IF OIDC %]
192
                                        <div class="local-login">
195
                                        <div class="local-login">
193
                                            <label for="userid">Login:</label>
196
                                            <label for="userid">Login:</label>
194
                                            <input class="form-control" type="text" id="userid" name="userid" autocomplete="off" />
197
                                            <input class="form-control" type="text" id="userid" name="userid" autocomplete="off" />
(-)a/opac/svc/auth/openidconnect (-1 / +273 lines)
Line 0 Link Here
0
- 
1
#!/usr/bin/perl
2
#
3
# This file is part of Koha.
4
#
5
# Koha is free software; you can redistribute it and/or modify it
6
# under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# Koha is distributed in the hope that it will be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with Koha; if not, see <http://www.gnu.org/licenses>.
17
#
18
#
19
# Basic OAuth2/OpenID Connect authentication goes like this
20
#
21
# The first thing that happens when this script is called is
22
# that one gets redirected to an authentication url
23
#
24
# If successful, that then redirects back to this script, setting
25
# a CODE parameter which we use to look up a json authentication
26
# token. This token includes an encrypted json id_token, which we
27
# round-trip back to decrypt. Finally, we can extract
28
# the email address from this.
29
#
30
31
use Modern::Perl;
32
use CGI qw ( -utf8 escape );
33
use C4::Auth qw{ checkauth get_session get_template_and_user };
34
use C4::Context;
35
use C4::Output;
36
use Koha::Patrons;
37
38
use LWP::UserAgent;
39
use HTTP::Request::Common qw{ POST };
40
use JSON;
41
use MIME::Base64 qw{ decode_base64url };
42
use URI;
43
use URI::QueryParam;
44
45
my $discoveryDocURL  = C4::Context->preference('OIDCConfigURL');
46
my $issuer           = '';
47
my $authendpoint     = '';
48
my $tokenendpoint    = '';
49
my $scope            = 'openid email profile';
50
my $host             = C4::Context->preference('OPACBaseURL') // q{};
51
my $restricttodomain = C4::Context->preference('OIDCDomain')
52
  // q{};
53
54
# protocol is assumed in OPACBaseURL see bug 5010.
55
my $redirecturl  = $host . '/cgi-bin/koha/svc/auth/openidconnect';
56
my $clientid     = C4::Context->preference('OIDCClientID');
57
my $clientsecret = C4::Context->preference('OIDCClientSecret');
58
59
my $ua       = LWP::UserAgent->new();
60
my $response = $ua->get($discoveryDocURL);
61
if ( $response->is_success ) {
62
    my $json = decode_json( $response->decoded_content );
63
    if ( exists( $json->{'issuer'} ) ) {
64
        $issuer = $json->{'issuer'};
65
    }
66
    if ( exists( $json->{'authorization_endpoint'} ) ) {
67
        $authendpoint = $json->{'authorization_endpoint'};
68
    }
69
    if ( exists( $json->{'token_endpoint'} ) ) {
70
        $tokenendpoint = $json->{'token_endpoint'};
71
    }
72
}
73
74
my $query = CGI->new;
75
76
sub loginfailed {
77
    my $cgi_query = shift;
78
    my $reason    = shift;
79
    $cgi_query->delete('code');
80
    $cgi_query->param( 'OIDCFailed' => $reason );
81
    my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
82
        {
83
            template_name   => 'opac-user.tt',
84
            query           => $cgi_query,
85
            type            => 'opac',
86
        }
87
    );
88
    $template->param( 'invalidOIDCLogin' => $reason );
89
    $template->param( 'loginprompt'                     => 1 );
90
    output_html_with_http_headers $cgi_query, $cookie, $template->output, undef, { force_no_caching => 1 };
91
    return;
92
}
93
94
if ( defined $query->param('error') ) {
95
    loginfailed( $query,
96
            'An authentication error occurred. (Error:'
97
          . $query->param('error')
98
          . ')' );
99
}
100
elsif ( defined $query->param('code') ) {
101
    my $stateclaim = $query->param('state');
102
    my $session    = get_session( $query->cookie('CGISESSID') );
103
    if ( $session->param('openid-state') ne $stateclaim ) {
104
        $session->clear( ["openid-state"] );
105
        $session->flush();
106
        loginfailed( $query,
107
            'Authentication failed. Your session has an unexpected state.' );
108
    }
109
    $session->clear( ["openid-state"] );
110
    $session->flush();
111
112
    my $code = $query->param('code');
113
    my $ua   = LWP::UserAgent->new();
114
    if ( $tokenendpoint eq q{} ) {
115
        loginfailed( $query, 'Unable to discover token endpoint.' );
116
    }
117
    my $request = POST(
118
        $tokenendpoint,
119
        [
120
            code          => $code,
121
            client_id     => $clientid,
122
            client_secret => $clientsecret,
123
            redirect_uri  => $redirecturl,
124
            grant_type    => 'authorization_code',
125
            $scope        => $scope
126
        ]
127
    );
128
    my $response = $ua->request($request)->decoded_content;
129
    my $json     = decode_json($response);
130
    if ( exists( $json->{'id_token'} ) ) {
131
        if ( lc( $json->{'token_type'} ) ne 'bearer' ) {
132
            loginfailed( $query,
133
                'Authentication failed. Incorrect token type.' );
134
        }
135
        my $idtoken = $json->{'id_token'};
136
137
        # need to validate the token here
138
139
        my @segments = split( '\.', $idtoken );
140
        unless ( scalar(@segments) == 3 ) {
141
            loginfailed( $query,
142
                'Login token broken: either too many or too few segments.' );
143
        }
144
        my ( $header, $claims, $validation ) = @segments;
145
        $claims = decode_base64url($claims);
146
        my $claims_json = decode_json($claims);
147
        if ( $issuer eq q{} ) {
148
            loginfailed( $query, 'Unable to discover issuer.' );
149
        }
150
        if (   ( $claims_json->{'iss'} ne ( 'https://' . $issuer ) )
151
            && ( $claims_json->{'iss'} ne $issuer ) )
152
        {
153
            loginfailed( $query,
154
                "Authentication failed. Issuer of authentication is different from what we expected."
155
            );
156
        }
157
        if ( ref( $claims_json->{'aud'} ) eq 'ARRAY' ) {
158
            warn "Audience is an array of size: "
159
              . scalar( @$claims_json->{'aud'} );
160
            if ( scalar( @$claims_json->{'aud'} ) > 1 )
161
            {    # We don't want any other audiences
162
                loginfailed( $query,
163
                    "Authentication failed. Unexpected audience provided." );
164
            }
165
        }
166
        if (   ( $claims_json->{'aud'} ne $clientid ) )
167
        {
168
            loginfailed( $query,
169
                "Authentication failed. Unexpected audience." );
170
        }
171
        if ( $claims_json->{'exp'} < time() ) {
172
            loginfailed( $query, 'Sorry, your authentication has timed out.' );
173
        }
174
175
        if ( exists( $claims_json->{'email'} ) ) {
176
            my $email = $claims_json->{'email'};
177
            if (   ( $restricttodomain ne q{} )
178
                && ( index( $email, $restricttodomain ) < 0 ) )
179
            {
180
                loginfailed( $query,
181
'The email you have used is not valid for this library. Email addresses should conclude with '
182
                      . $restricttodomain
183
                      . ' .' );
184
            }
185
            else {
186
                my $error_feedback =
187
'The email address you are trying to use is not associated with a borrower at this library.';
188
                my $auto_registration = C4::Context->preference('OIDCAutoRegister') // q{0};
189
                my $borrower = Koha::Patrons->find( { email => $email } );
190
                if (! $borrower && $auto_registration==1) {
191
                    my $firstname = $claims_json->{'given_name'} // q{};
192
                    my $surname = $claims_json->{'family_name'} // q{};
193
                    if ($firstname && $surname) {
194
                        my $delimiter = $firstname ? q{.} : q{};
195
                        my $userid = $firstname . $delimiter . $surname;
196
                        my $categorycode = C4::Context->preference('OIDCDefaultCategory') // q{};
197
                        my $patron_category = Koha::Patron::Categories->find( $categorycode );
198
                        my $branchcode = C4::Context->preference('OIDCDefaultBranch') // q{};
199
                        my $library = Koha::Libraries->find( $branchcode );
200
                        if (defined $patron_category && defined $library) {
201
                            my $password = undef;
202
                            # TODO errors handling!
203
                            my $borrower = Koha::Patron->new({
204
                                firstname    => $firstname,
205
                                surname      => $surname,
206
                                email        => $email,
207
                                categorycode => $categorycode,
208
                                branchcode   => $branchcode,
209
                                userid       => $userid,
210
                                password     => $password
211
                            })->store;
212
                        } else {
213
                            $error_feedback = 'The OIDCDefaultBranch or OIDCDefaultCategory system preferences are not configured properly. Please contact the library with this error message.';
214
                        }
215
                    } else {
216
                        $error_feedback = 'We could not find given name and/or family name.'
217
                    }
218
                }
219
                my ( $userid, $cookie, $session_id ) =
220
                  checkauth( $query, 1, {}, 'opac', $email );
221
                if ($userid) {    # A user with this email is registered in koha
222
223
                    #handle redirect to main.pl, for private opac
224
                    my $uri;
225
                    if (C4::Context->preference('OpacPublic') ) {
226
                        $uri    =  '/cgi-bin/koha/opac-user.pl';
227
                    } else {
228
                        $uri    =  '/cgi-bin/koha/opac-main.pl';
229
                    }
230
                    print $query->redirect(
231
                        -uri    => $uri,
232
                        -cookie => $cookie
233
                    );
234
                }
235
                else {
236
                    loginfailed( $query, $error_feedback );
237
                }
238
            }
239
        }
240
        else {
241
            loginfailed( $query,
242
'Unexpectedly, no email seems to be associated with that acccount.'
243
            );
244
        }
245
    }
246
    else {
247
        loginfailed( $query, 'Failed to get proper credentials.' );
248
    }
249
}
250
else {
251
    my $session     = get_session( $query->cookie('CGISESSID') );
252
    my $openidstate = 'auth_';
253
    $openidstate .= sprintf( "%x", rand 16 ) for 1 .. 32;
254
    $session->param( 'openid-state', $openidstate );
255
    $session->flush();
256
257
    my $prompt = $query->param('reauthenticate') // q{};
258
    if ( $authendpoint eq q{} ) {
259
        loginfailed( $query, 'Unable to discover authorisation endpoint.' );
260
    }
261
    my $authorisationurl = URI->new($authendpoint);
262
    $authorisationurl->query_form(
263
        response_type => "code",
264
        redirect_uri => $redirecturl,
265
        client_id => $clientid,
266
        scope => $scope,
267
        state => $openidstate
268
    );
269
    if ( $prompt || ( defined $prompt && length $prompt > 0 ) ) {
270
        $authorisationurl->query_param_append( prompt => $prompt );
271
    }
272
    print $query->redirect($authorisationurl->as_string);
273
}

Return to bug 30988