+# Proxy CAS auth
+sub check_api_auth_cas {
+ $debug and warn "check_api_auth_cas";
+ my ($dbh, $PT, $query, $type) = @_;
+ my $retnumber;
+ my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
+
+ # If we have a Proxy Ticket
+ if ($PT) {
+ my $r = $cas->proxy_validate( $uri, $PT );
+
+ # If the PT is valid
+ if ( $r->is_success ) {
+
+ # We've got a username !
+ $debug and warn "User authenticated as: ", $r->user, "\n";
+ $debug and warn "Proxied through:\n";
+ $debug and warn " $_\n" for $r->proxies;
+
+ my $userid = $r->user;
+
+ # Does it match one of our users ?
+ my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
+ $sth->execute($userid);
+ if ( $sth->rows ) {
+ $retnumber = $sth->fetchrow;
+ return ( 1, $retnumber, $userid );
+ }
+ $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
+ return $r->user;
+ $sth->execute($userid);
+ if ( $sth->rows ) {
+ $retnumber = $sth->fetchrow;
+ return ( 1, $retnumber, $userid );
+ }
+
+ # If we reach this point, then the user is a valid CAS user, but not a Koha user
+ $debug and warn "User $userid is not a valid Koha user";
+
+ } else {
+ $debug and warn "Proxy Ticket authentication failed";
+ return 0;
+ }
+ }
+ return 0;
+}
+
+# Get CAS handler and service URI
+sub _get_cas_and_service {
+ my $query = shift;
+ my $key = shift; # optional
+ my $type = shift;
+
+ my $uri = _url_with_get_params($query, $type);
+
+ my $casparam = $defaultcasserver;
+ $casparam = $query->param('cas') if defined $query->param('cas');
+ $casparam = $key if defined $key;
+ my $cas = Authen::CAS::Client->new( $casservers->{$casparam} );
+
+ return ( $cas, $uri );
+}
+
+# Get the current URL with parameters contained directly into URL (GET params)
+# This method replaces $query->url() which will give both GET and POST params
+sub _url_with_get_params {
+ my $query = shift;
+ my $type = shift;
+
+ my $uri_base_part =
+ ( $type eq 'opac' )
+ ? C4::Context->preference('OPACBaseURL')
+ : C4::Context->preference('staffClientBaseURL');
+ $uri_base_part .= get_script_name();
+
+ my $uri_params_part = '';
+ foreach my $param ( $query->url_param() ) {
+ # url_param() always returns parameters that were deleted by delete()
+ # This additional check ensure that parameter was not deleted.
+ my $uriPiece = $query->param($param);
+ if ($uriPiece) {
+ $uri_params_part .= '&' if $uri_params_part;
+ $uri_params_part .= $param . '=';
+ $uri_params_part .= URI::Escape::uri_escape( $uriPiece );
+ }
+ }
+ $uri_base_part .= '?' if $uri_params_part;
+
+ return $uri_base_part . $uri_params_part;
+}
+