Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recaptcha experiment #1

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Open-ILS/examples/opensrf.xml.example
Original file line number Diff line number Diff line change
Expand Up @@ -1491,6 +1491,24 @@ vim:et:ts=4:sw=4:
</app_settings>
</open-ils.curbside>

<!-- ReCAPTCHA -->
<biblio.recaptcha>
<keepalive>3</keepalive>
<stateless>1</stateless>
<language>perl</language> <!-- Language of the service -->
<implementation>OpenILS::Application::Recaptcha</implementation> <!-- Path to the service module (in this case, /OpenILS/Application/Recaptcha.pm) -->
<max_requests>100</max_requests>
<unix_config>
<unix_log>biblio.recaptcha.log</unix_log>
<unix_sock>biblio.recaptcha.sock</unix_sock>
<unix_pid>biblio.recaptcha.pid</unix_pid>
<min_children>2</min_children>
<max_children>10</max_children>
<min_spare_children>1</min_spare_children>
<max_spare_children>3</max_spare_children>
</unix_config>
</biblio.recaptcha>

</apps>
</default>

Expand Down Expand Up @@ -1543,6 +1561,7 @@ vim:et:ts=4:sw=4:
<appname>open-ils.curbside</appname>
<appname>open-ils.geo</appname>
<appname>open-ils.sip2</appname>
<appname>biblio.recaptcha</appname>
</activeapps>
</localhost>
</hosts>
Expand Down
2 changes: 2 additions & 0 deletions Open-ILS/examples/opensrf_core.xml.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Example OpenSRF bootstrap configuration file for Evergreen
<service>open-ils.serial</service>
<service>open-ils.ebook_api</service>
<service>open-ils.sip2</service>
<service>biblio.recaptcha</service>
</services>
</router>

Expand Down Expand Up @@ -110,6 +111,7 @@ Example OpenSRF bootstrap configuration file for Evergreen
<service>open-ils.auth_mfa</service>
<service>open-ils.collections</service>
<service>open-ils.reporter</service>
<service>biblio.recaptcha</service>
</services>

<!-- Ejabberd -->
Expand Down
119 changes: 119 additions & 0 deletions Open-ILS/src/perlmods/lib/OpenILS/Application/Recaptcha.pm
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# -------------------------------------------------------------------------------
# Module: OpenILS::Application::Recaptcha
# Author: Ian Skelskey <ianskelskey@gmail.com>
# Organization: Bibliomation, Inc.
# Year: 2024
# Description: Implements reCAPTCHA v3 verification within Evergreen ILS as an
# OpenSRF service, using Google's API for user input validation.
# -------------------------------------------------------------------------------

package OpenILS::Application::Recaptcha;

use strict;
use warnings;
use base 'OpenSRF::Application';
use LWP::UserAgent;
use JSON;
use OpenSRF::Utils::Logger qw($logger);
use OpenILS::Utils::CStoreEditor;

# Register OpenSRF method
__PACKAGE__->register_method(
method => 'recaptcha_verify',
api_name => 'biblio.recaptcha.verify',
argc => 1, # Expects a single argument (hash with token and org_unit)
stream => 0 # Non-streaming method
);

# Singleton for CStore Editor
my $editor;
sub editor {
return $editor ||= OpenILS::Utils::CStoreEditor->new;
}

# Retrieve the reCAPTCHA secret key
sub get_secret_key {
my ($org) = @_;

my $U = 'OpenILS::Application::AppUtils';
my $secret_key = $U->ou_ancestor_setting_value($org, 'recaptcha.secret_key');

if ($secret_key) {
$logger->info("Retrieved reCAPTCHA secret key for org ID: $org");
return $secret_key;
}

$logger->error("No reCAPTCHA secret key found for org ID: $org");
return undef;
}

# Main method to verify reCAPTCHA token
sub recaptcha_verify {
my ($self, $client, $args) = @_;

my $token = $args->{token};
my $org_unit = $args->{org_unit} || 1; # Default to consortium (org_unit 1)

$logger->info("Starting reCAPTCHA verification for org_unit: $org_unit");
$logger->info("Received reCAPTCHA token");

my $response = send_recaptcha_request($token, $org_unit);
return encode_json(process_recaptcha_response($response));
}

# Send request to Google's reCAPTCHA API
sub send_recaptcha_request {
my ($token, $org) = @_;

my $secret = get_secret_key($org);
unless ($secret) {
$logger->error("Missing reCAPTCHA secret key for org ID: $org");
return { success => 0, error => 'Missing reCAPTCHA secret key' };
}

my $url = 'https://www.google.com/recaptcha/api/siteverify';
my $ua = LWP::UserAgent->new(timeout => 10);
my $response = $ua->post($url, {
secret => $secret,
response => $token
});

if (!$response->is_success) {
$logger->error("Failed to reach Google reCAPTCHA server: " . $response->status_line);
return { success => 0, error => 'Unable to reach reCAPTCHA server' };
}

$logger->info("Successfully sent reCAPTCHA verification request");
return $response;
}

# Process the response from Google's reCAPTCHA API
sub process_recaptcha_response {
my ($response) = @_;

my $content = $response->decoded_content || '{}';
my $json;
eval { $json = decode_json($content); };
if ($@) {
$logger->error("Error parsing JSON from Google: $@");
return { success => 0, error => 'Invalid JSON response' };
}

$logger->info("Decoded reCAPTCHA response: $content");

unless ($json->{success}) {
my $errors = join(", ", @{$json->{'error-codes'} || []});
$logger->error("reCAPTCHA verification failed: $errors");
return { success => 0, 'error-codes' => $json->{'error-codes'} };
}

if ($json->{score} < 0.5) {
$logger->warn("Low reCAPTCHA score: " . $json->{score});
return { success => 0, error => 'Low reCAPTCHA score' };
}

$logger->info("reCAPTCHA successfully verified with score: " . $json->{score});
return { success => 1 };
}

1;
5 changes: 5 additions & 0 deletions Open-ILS/src/templates-bootstrap/opac/parts/login/form.tt2
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,8 @@
</form>

</div>
[% INCLUDE "opac/parts/recaptcha.tt2"
action_name="opac_login"
submit_action="submit"
target_element_id="login_form"
%]
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,8 @@
</div>
</div>
</dialog>
[% INCLUDE "opac/parts/recaptcha.tt2"
action_name="opac_login"
submit_action="submit"
target_element_id="login_form"
%]
28 changes: 28 additions & 0 deletions Open-ILS/src/templates-bootstrap/opac/parts/recaptcha.tt2
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[%
org_unit = ctx.search_ou;
recaptcha_site_key = ctx.get_org_setting(org_unit, 'recaptcha.site_key');
action_name = action_name || 'register'; # Default action name if none is provided
submit_action = submit_action || 'submit'; # Default submit action if none is provided
target_element_id = target_element_id || 'recaptcha-form'; # Default target element ID
recaptcha_enabled = ctx.get_org_setting(ctx.search_ou, 'recaptcha.enabled');
%]
[% IF recaptcha_enabled && recaptcha_enabled == 1 %]
<!-- Dependencies -->
<script src="https://www.google.com/recaptcha/api.js?render=[% recaptcha_site_key %]"></script>
<script src="/opac/common/js/opensrf.js"></script>
<script src="/opac/common/js/opensrf_xhr.js"></script>
<script src="/opac/common/js/JSON_v1.js"></script>
<script src="/opac/common/js/recaptcha.js"></script>

<script>
document.addEventListener('DOMContentLoaded', () => {
initializeRecaptcha('[% target_element_id %]', '[% recaptcha_site_key %]', '[% action_name %]', '[% submit_action %]');
});
</script>
[% ELSE %]
<script>
console.log('org_unit:', '[% org_unit %]');
console.log('recaptcha_enabled:', '[% recaptcha_enabled %]');
console.log('reCAPTCHA is not enabled for this organization unit.');
</script>
[% END %]
51 changes: 36 additions & 15 deletions Open-ILS/src/templates-bootstrap/opac/parts/searchbar.tt2
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ END;

<div id="search-wrapper" class="container-fluid">
[% UNLESS took_care_of_form -%]
<form action="[% ctx.opac_root %]/results" method="get">
<form id="opac-search-form" data-org-unit="[% ctx.search_ou %]">
[%- END %]
[% IF ctx.page == 'rresult' && ctx.metarecord && search.metarecord_default %]
<input type="hidden" name="modifier" value="metabib"/>
Expand Down Expand Up @@ -110,17 +110,22 @@ END;

<div class="col col-auto col-search-button">
<input id="detail" type="hidden" name="detail_record_view" value="[% show_detail_view %]"/>
<button id='search-submit-go' type="submit" class="btn btn-sm btn-opac"
onclick='setTimeout(function(){$("search-submit-spinner").className=""; $("search-submit-go").className="hidden";[% IF ctx.depth_sel_button AND NOT took_care_of_form %] $("search-submit-go-depth").className="hidden";[% END %]}, 2000)'><i class="fas fa-search" aria-hidden="true"></i> [% l('Search') %]</button>

<button id='search-submit-go' type="submit" class="btn btn-sm btn-opac">
<i class="fas fa-search" aria-hidden="true"></i> [% l('Search') %]
</button>
[%- IF ctx.depth_sel_button AND NOT took_care_of_form %]
<button id='search-submit-go-depth' type="submit" value="[% ctx.depth_sel_depth %]" name="depth" class="btn btn-sm btn-opac"
onclick='setTimeout(function(){$("search-submit-spinner").className=""; $("search-submit-go").className="hidden"; $("search-submit-go-depth").className="hidden";}, 2000)' title="[% ctx.depth_sel_tooltip | html %]"><i class="fas fa-globe" aria-hidden="true"></i> [% ctx.depth_sel_button_label | html %]</button>
<button id='search-submit-go-depth' type="submit" value="[% ctx.depth_sel_depth %]" name="depth" class="btn btn-sm btn-opac" title="[% ctx.depth_sel_tooltip | html %]"><i class="fas fa-globe" aria-hidden="true"></i> [% ctx.depth_sel_button_label | html %]</button>
[%- END %]
<img id='search-submit-spinner' src='[% ctx.media_prefix %]/opac/images/progressbar_green.gif[% ctx.cache_key %]' class='hidden' alt='[% l("Search In Progress") %]'/>
</div>
</div>

[% INCLUDE "opac/parts/recaptcha.tt2"
action_name="opac_search"
submit_action="submit"
target_element_id="opac-search-form"
%]

[% IF ctx.bookbag %]
<div id="search-only-bookbag-container" class="text-center">
<input type="checkbox" id="search-only-bookbag" name="bookbag"
Expand Down Expand Up @@ -209,15 +214,31 @@ END;
}
}
</script>
<!-- Canonicalized query:

[% ctx.canonicalized_query | html %]

-->
<!--
<div id="breadcrumb">
<a href="[% ctx.opac_root %]/home">[% l('Catalog Home') %]</a> &gt;
</div>
-->
<script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('opac-search-form');
if (!form) return;

form.addEventListener('submit', event => {
event.preventDefault();
setTimeout(() => {
document.getElementById('search-submit-spinner').className = '';
document.getElementById('search-submit-go').className = 'hidden';
// If depth button exists
const depthBtn = document.getElementById('search-submit-go-depth');
if (depthBtn) depthBtn.className = 'hidden';
}, 2000);

// Construct the GET request URL
const formData = new FormData(form);
const queryString = new URLSearchParams(formData).toString();
const actionUrl = '[% ctx.opac_root %]/results?' + queryString;

// Redirect to the constructed URL
window.location.href = actionUrl;
});
});
</script>
</div>
</div>
12 changes: 10 additions & 2 deletions Open-ILS/src/templates-bootstrap/opac/register.tt2
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ END;
) | html %]</h4>
[% END %]

<form method='POST' class="needs-validation" novalidate>
<form method='POST' id="registration-form" class="needs-validation" novalidate data-org-unit="[% ctx.search_ou %]">
<div class="form-group row">
<label class="control-label col-md-2" for='stgu.home_ou'>[% l('Home Library') %]</label>
<div class="col-md-6">
Expand All @@ -105,7 +105,7 @@ END;
can_have_users_only=1
valid_org_list=ctx.register.valid_orgs
%]
</div>
</div>
<div class="col-md-4">
[% IF ctx.register.invalid.bad_home_ou %]
<span class='patron-reg-invalid'>
Expand Down Expand Up @@ -284,6 +284,7 @@ FOR field_def IN register_fields;
</main>
[%- END %]
<script>

(function() {
'use strict';
window.addEventListener('load', function() {
Expand All @@ -292,6 +293,7 @@ FOR field_def IN register_fields;
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
console.log('Bootstrap form validation');
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
Expand All @@ -310,4 +312,10 @@ $(document).ready(function(){
});
$('.datepicker').datepicker("setDate", "");
});

</script>
[% INCLUDE "opac/parts/recaptcha.tt2"
action_name="register"
submit_action="submit"
target_element_id="registration-form"
%]
7 changes: 6 additions & 1 deletion Open-ILS/src/templates/opac/parts/searchbar.tt2
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ END;

<div id="search-wrapper">
[% UNLESS took_care_of_form -%]
<form action="[% ctx.opac_root %]/results" method="get">
<form id="opac-search-form" action="[% ctx.opac_root %]/results" method="get">
[%- END %]
[% IF ctx.page == 'rresult' && ctx.metarecord && search.metarecord_default %]
<input type="hidden" name="modifier" value="metabib"/>
Expand Down Expand Up @@ -229,3 +229,8 @@ END;
-->
<div class="clear-both"></div>
</div>
[% INCLUDE "opac/parts/recaptcha.tt2"
action_name="opac_search"
submit_action="submit"
target_element_id="opac-search-form"
%]
Loading