3 # Copyright BibLibre 2015
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use Koha::AuthUtils qw(hash_password);
24 use Koha::Exceptions::Object;
26 use List::MoreUtils qw(any);
29 use base qw(Koha::Object);
33 Koha::ApiKey - Koha API Key Object class
41 my $api_key = Koha::ApiKey->new({ patron_id => $patron_id })->store;
43 Overloaded I<store> method.
50 if ( $self->in_storage ) {
51 my %dirty_columns = $self->_result->get_dirty_columns;
53 # only allow 'description' and 'active' to be updated
54 for my $property ( keys %dirty_columns ) {
55 Koha::Exceptions::Object::ReadOnlyProperty->throw( property => $property )
56 if $property ne 'description' and $property ne 'active';
59 $self->{_plain_text_secret} = $self->_generate_unused_uuid('secret');
61 { secret => Koha::AuthUtils::hash_password( $self->{_plain_text_secret} ),
62 client_id => $self->_generate_unused_uuid('client_id'),
67 return $self->SUPER::store();
70 =head3 validate_secret
72 if ( $api_key->validate_secret( $secret ) ) { ... }
74 Returns a boolean that tells if the passed secret matches the one on the DB.
79 my ( $self, $secret ) = @_;
81 my $digest = Koha::AuthUtils::hash_password( $secret, $self->secret );
83 return ( $self->secret eq $digest ) ? 1 : 0;
86 =head3 plain_text_secret
88 my $generated_secret = $api_key->store->plain_text_secret;
90 Returns the generated I<secret> so it can be displayed to the end user.
91 This is only accessible when the object is new and has just been stored.
93 Returns I<undef> if the object was retrieved from the database.
97 sub plain_text_secret {
100 return $self->{_plain_text_secret}
101 if $self->{_plain_text_secret};
106 =head2 Internal methods
118 =head3 _generate_unused_uuid
120 my $string = $self->_generate_unused_uuid($column);
122 $column can be 'client_id' or 'secret'.
126 sub _generate_unused_uuid {
127 my ($self, $column) = @_;
129 my ( $uuid, $uuidstring );
131 UUID::generate($uuid);
132 UUID::unparse( $uuid, $uuidstring );
134 while ( Koha::ApiKeys->search({ $column => $uuidstring })->count > 0 ) {
135 # Make sure $secret is unique
136 UUID::generate($uuid);
137 UUID::unparse( $uuid, $uuidstring );