Bug 19550: (QA follow-up) Add missing [% USE %]
[koha.git] / Koha / OAuth.pm
blob3cce7a9672558bc53967835255f3cab6893c2624
1 package Koha::OAuth;
3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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')