Bug 12556: reserves/request.pl: Reuse code from Koha::Hold
[koha.git] / Koha / OAuth.pm
blob29a701114c7b904d02e52ef2d32aa1d8b018640a
1 package Koha::OAuth;
3 # This file is part of Koha.
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.
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.
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>.
18 use Modern::Perl;
20 use Koha::ApiKeys;
21 use Koha::OAuthAccessTokens;
23 =head1 NAME
25 Koha::OAuth - Koha library for OAuth2 callbacks
27 =head1 API
29 =head2 Class methods
31 =head3 config
33 my $config = Koha::OAuth->config;
35 Returns a hashref containing the callbacks Net::OAuth2::AuthorizationServer requires
37 =cut
39 sub config {
40 return {
41 verify_client_cb => \&_verify_client_cb,
42 store_access_token_cb => \&_store_access_token_cb,
43 verify_access_token_cb => \&_verify_access_token_cb
47 =head3 _verify_client_cb
49 A callback to verify if the client asking for authorization is known to the authorization server
50 and allowed to get authorization.
52 =cut
54 sub _verify_client_cb {
55 my (%args) = @_;
57 my ($client_id, $client_secret) = @args{ qw/ client_id client_secret / };
59 my $api_key;
61 if ($client_id) {
62 $api_key = Koha::ApiKeys->find( $client_id );
65 # client_id mandatory and exists on the DB
66 return (0, 'unauthorized_client') unless $api_key && $api_key->active;
68 return (0, 'access_denied') unless $api_key->secret eq $client_secret;
70 return (1, undef, []);
73 =head3 _store_access_token_cb
75 A callback to store the generated access tokens.
77 =cut
79 sub _store_access_token_cb {
80 my ( %args ) = @_;
82 my ( $client_id, $access_token, $expires_in )
83 = @args{ qw/ client_id access_token expires_in / };
85 my $at = Koha::OAuthAccessToken->new({
86 access_token => $access_token,
87 expires => time + $expires_in,
88 client_id => $client_id,
89 });
90 $at->store;
92 return;
95 =head3 _verify_access_token_cb
97 A callback to verify the access token.
99 =cut
101 sub _verify_access_token_cb {
102 my (%args) = @_;
104 my $access_token = $args{access_token};
106 my $at = Koha::OAuthAccessTokens->find($access_token);
107 if ($at) {
108 if ( $at->expires <= time ) {
109 # need to revoke the access token
110 $at->delete;
112 return (0, 'invalid_grant')
115 return $at->unblessed;
118 return (0, 'invalid_grant')