]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Utils/CStoreEditor.pm
plugged in new permission checking call which uses cstore instead of storage
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Utils / CStoreEditor.pm
1 use strict; use warnings;
2 package OpenILS::Utils::CStoreEditor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::AppSession;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Event;
8 use Data::Dumper;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Logger qw($logger);
11 my $U = "OpenILS::Application::AppUtils";
12 my %PERMS;
13 my $cache;
14
15 #my %PERMS = (
16 #       'biblio.record_entry'   => { update => 'UPDATE_MARC' },
17 #       'asset.copy'                            => { update => 'UPDATE_COPY'},
18 #       'asset.call_number'             => { update => 'UPDATE_VOLUME'},
19 #       'action.circulation'            => { retrieve => 'VIEW_CIRCULATIONS'},
20 #);
21
22
23
24 # -----------------------------------------------------------------------------
25 # Export some useful functions
26 # -----------------------------------------------------------------------------
27 use vars qw(@EXPORT_OK %EXPORT_TAGS);
28 use Exporter;
29 use base qw/Exporter/;
30 push @EXPORT_OK, ( 'new_editor', 'new_rstore_editor' );
31 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
32
33 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
34
35 sub new_rstore_editor { 
36         my $e = OpenILS::Utils::CStoreEditor->new(@_); 
37         $e->app('open-ils.reporter-store');
38         return $e;
39 }
40
41
42 # -----------------------------------------------------------------------------
43 # Log levels
44 # -----------------------------------------------------------------------------
45 use constant E => 'error';
46 use constant W => 'warn';
47 use constant I => 'info';
48 use constant D => 'debug';
49 use constant A => 'activity';
50
51
52
53 # -----------------------------------------------------------------------------
54 # Params include:
55 #       xact=><true> : creates a storage transaction
56 #       authtoken=>$token : the login session key
57 # -----------------------------------------------------------------------------
58 sub new {
59         my( $class, %params ) = @_;
60         $class = ref($class) || $class;
61         my $self = bless( \%params, $class );
62         $self->{checked_perms} = {};
63         return $self;
64 }
65
66
67 sub app {
68         my( $self, $app ) = @_;
69         $self->{app} = $app if $app;
70         $self->{app} = 'open-ils.cstore' unless $self->{app};
71         return $self->{app};
72 }
73
74
75 # -----------------------------------------------------------------------------
76 # Log the editor metadata along with the log string
77 # -----------------------------------------------------------------------------
78 sub log {
79         my( $self, $lev, $str ) = @_;
80         my $s = "editor[";
81         $s .= "0|" unless $self->{xact};
82         $s .= "1|" if $self->{xact};
83         $s .= "0" unless $self->requestor;
84         $s .= $self->requestor->id if $self->requestor;
85         $s .= "]";
86         $logger->$lev("$s $str");
87 }
88
89 # -----------------------------------------------------------------------------
90 # Verifies the auth token and fetches the requestor object
91 # -----------------------------------------------------------------------------
92 sub checkauth {
93         my $self = shift;
94         $self->log(D, "checking auth token ".$self->authtoken);
95         my ($reqr, $evt) = $U->checkses($self->authtoken);
96         $self->event($evt) if $evt;
97         return $self->{requestor} = $reqr;
98 }
99
100
101 =head test
102 sub checkauth {
103         my $self = shift;
104         $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
105         $self->log(D, "checking cached auth token ".$self->authtoken);
106         my $user = $cache->get_cache("oils_auth_".$self->authtoken);
107         return $self->{requestor} = $user->{userobj} if $user;
108         $self->event(OpenILS::Event->new('NO_SESSION'));
109         return undef;
110 }
111 =cut
112
113
114 # -----------------------------------------------------------------------------
115 # Returns the last generated event
116 # -----------------------------------------------------------------------------
117 sub event {
118         my( $self, $evt ) = @_;
119         $self->{event} = $evt if $evt;
120         return $self->{event};
121 }
122
123 # -----------------------------------------------------------------------------
124 # Destroys the transaction and disconnects where necessary,
125 # then returns the last event that occurred
126 # -----------------------------------------------------------------------------
127 sub die_event {
128         my $self = shift;
129         $self->rollback;
130         return $self->event;
131 }
132
133
134 # -----------------------------------------------------------------------------
135 # Clears the last caught event
136 # -----------------------------------------------------------------------------
137 sub clear_event {
138         my $self = shift;
139         $self->{event} = undef;
140 }
141
142 sub authtoken {
143         my( $self, $auth ) = @_;
144         $self->{authtoken} = $auth if $auth;
145         return $self->{authtoken};
146 }
147
148 sub timeout {
149     my($self, $to) = @_;
150     $self->{timeout} = $to if defined $to;
151     return defined($self->{timeout}) ? $self->{timeout} : 60;
152 }
153
154 # -----------------------------------------------------------------------------
155 # fetches the session, creating if necessary.  If 'xact' is true on this
156 # object, a db session is created
157 # -----------------------------------------------------------------------------
158 sub session {
159         my( $self, $session ) = @_;
160         $self->{session} = $session if $session;
161
162         if(!$self->{session}) {
163                 $self->{session} = OpenSRF::AppSession->create($self->app);
164
165                 if( ! $self->{session} ) {
166                         my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
167                         $self->log(E, $str);
168                         throw OpenSRF::EX::ERROR ($str);
169                 }
170
171                 $self->{session}->connect if $self->{xact} or $self->{connect};
172                 $self->xact_start if $self->{xact};
173         }
174         return $self->{session};
175 }
176
177
178 # -----------------------------------------------------------------------------
179 # Starts a storage transaction
180 # -----------------------------------------------------------------------------
181 sub xact_start {
182         my $self = shift;
183         $self->log(D, "starting new db session");
184         my $stat = $self->request($self->app . '.transaction.begin');
185         $self->log(E, "error starting database transaction") unless $stat;
186         return $stat;
187 }
188
189 # -----------------------------------------------------------------------------
190 # Commits a storage transaction
191 # -----------------------------------------------------------------------------
192 sub xact_commit {
193         my $self = shift;
194         $self->log(D, "comitting db session");
195         my $stat = $self->request($self->app.'.transaction.commit');
196         $self->log(E, "error comitting database transaction") unless $stat;
197         return $stat;
198 }
199
200 # -----------------------------------------------------------------------------
201 # Rolls back a storage stransaction
202 # -----------------------------------------------------------------------------
203 sub xact_rollback {
204         my $self = shift;
205    return unless $self->{session};
206         $self->log(I, "rolling back db session");
207         return $self->request($self->app.".transaction.rollback");
208 }
209
210
211
212 # -----------------------------------------------------------------------------
213 # Rolls back the transaction and disconnects
214 # -----------------------------------------------------------------------------
215 sub rollback {
216         my $self = shift;
217         $self->xact_rollback if $self->{xact};
218    delete $self->{xact};
219         $self->disconnect;
220 }
221
222 sub disconnect {
223         my $self = shift;
224         $self->session->disconnect if $self->{session};
225    delete $self->{session};
226 }
227
228
229 # -----------------------------------------------------------------------------
230 # commits the db session and destroys the session
231 # -----------------------------------------------------------------------------
232 sub commit {
233         my $self = shift;
234         return unless $self->{xact};
235         $self->xact_commit;
236         $self->session->disconnect;
237         $self->{session} = undef;
238 }
239
240 # -----------------------------------------------------------------------------
241 # clears all object data. Does not commit the db transaction.
242 # -----------------------------------------------------------------------------
243 sub reset {
244         my $self = shift;
245         $self->disconnect;
246         $$self{$_} = undef for (keys %$self);
247 }
248
249
250 # -----------------------------------------------------------------------------
251 # commits and resets
252 # -----------------------------------------------------------------------------
253 sub finish {
254         my $self = shift;
255         $self->commit;
256         $self->reset;
257 }
258
259
260
261 # -----------------------------------------------------------------------------
262 # Does a simple storage request
263 # -----------------------------------------------------------------------------
264 sub request {
265         my( $self, $method, @params ) = @_;
266
267     my $val;
268         my $err;
269         my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
270
271         $self->log(I, "request $method : $argstr");
272
273         if( $self->{xact} and 
274                         $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
275                 #$logger->error("CStoreEditor lost it's connection!!");
276                 throw OpenSRF::EX::ERROR ("CStore connection timed out - transaction cannot continue");
277         }
278
279
280         try {
281
282         my $req = $self->session->request($method, @params);
283
284         if($self->substream) {
285             $self->log(D,"running in substream mode");
286             $val = [];
287             while( my $resp = $req->recv(timeout => $self->timeout) ) {
288                 push(@$val, $resp->content) if $resp->content;
289             }
290
291         } else {
292             my $resp = $req->recv(timeout => $self->timeout);
293             $val = $resp->content;
294         }
295
296         $req->finish;
297
298         } catch Error with {
299                 $err = shift;
300                 $self->log(E, "request error $method : $argstr : $err");
301         };
302
303         throw $err if $err;
304         return $val;
305 }
306
307 sub substream {
308    my( $self, $bool ) = @_;
309    $self->{substream} = $bool if defined $bool;
310    return $self->{substream};
311 }
312
313
314 # -----------------------------------------------------------------------------
315 # Sets / Returns the requstor object.  This is set when checkauth succeeds.
316 # -----------------------------------------------------------------------------
317 sub requestor {
318         my($self, $requestor) = @_;
319         $self->{requestor} = $requestor if $requestor;
320         return $self->{requestor};
321 }
322
323
324
325 # -----------------------------------------------------------------------------
326 # Holds the last data received from a storage call
327 # -----------------------------------------------------------------------------
328 sub data {
329         my( $self, $data ) = @_;
330         $self->{data} = $data if defined $data;
331         return $self->{data};
332 }
333
334
335 # -----------------------------------------------------------------------------
336 # True if this perm has already been checked at this org
337 # -----------------------------------------------------------------------------
338 sub perm_checked {
339         my( $self, $perm, $org ) = @_;
340         $self->{checked_perms}->{$org} = {}
341                 unless $self->{checked_perms}->{$org};
342         my $checked = $self->{checked_perms}->{$org}->{$perm};
343         if(!$checked) {
344                 $self->{checked_perms}->{$org}->{$perm} = 1;
345                 return 0;
346         }
347         return 1;
348 }
349
350
351
352 # -----------------------------------------------------------------------------
353 # Returns true if the requested perm is allowed.  If the perm check fails,
354 # $e->event is set and undef is returned
355 # The perm user is $e->requestor->id and perm org defaults to the requestor's
356 # ws_ou
357 # If this perm at the given org has already been verified, true is returned
358 # and the perm is not re-checked
359 # -----------------------------------------------------------------------------
360 =head
361 sub allowed {
362         my( $self, $perm, $org ) = @_;
363         my $uid = $self->requestor->id;
364         $org ||= $self->requestor->ws_ou;
365         $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
366         return 1 if $self->perm_checked($perm, $org); 
367         return $self->checkperm($uid, $org, $perm);
368 }
369 =cut
370
371 my $PERM_QUERY = {
372     select => {
373         au => [ {
374             transform => 'permission.usr_has_perm',
375             alias => 'has_perm',
376             column => 'id',
377             params => []
378         } ]
379     },
380     from => 'au',
381     where => {},
382 };
383
384 sub allowed {
385         my( $self, $perm, $org ) = @_;
386         my $uid = $self->requestor->id;
387         $org ||= $self->requestor->ws_ou;
388         $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
389
390     # fill in the search hash
391     $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
392     $PERM_QUERY->{where}->{id} = $uid;
393
394     return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
395
396     # set the perm failure event if the permission check returned false
397         my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
398         $self->event($e);
399         return undef;
400
401 }
402
403 =head
404 sub checkperm {
405         my($self, $userid, $org, $perm) = @_;
406         my $s = $U->storagereq(
407                 "open-ils.storage.permission.user_has_perm", $userid, $perm, $org );
408
409         if(!$s) {
410                 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
411                 $self->event($e);
412                 return undef;
413         }
414
415         return 1;
416 }
417 =cut
418
419
420
421 # -----------------------------------------------------------------------------
422 # checks the appropriate perm for the operation
423 # -----------------------------------------------------------------------------
424 sub _checkperm {
425         my( $self, $ptype, $action, $org ) = @_;
426         $org ||= $self->requestor->ws_ou;
427         my $perm = $PERMS{$ptype}{$action};
428         if( $perm ) {
429                 return undef if $self->perm_checked($perm, $org);
430                 return $self->event unless $self->allowed($perm, $org);
431         } else {
432                 $self->log(I, "no perm provided for $ptype.$action");
433         }
434         return undef;
435 }
436
437
438
439 # -----------------------------------------------------------------------------
440 # Logs update actions to the activity log
441 # -----------------------------------------------------------------------------
442 sub log_activity {
443         my( $self, $type, $action, $arg ) = @_;
444         my $str = "$type.$action";
445         $str .= _prop_string($arg);
446         $self->log(A, $str);
447 }
448
449
450
451 sub _prop_string {
452         my $obj = shift;
453         my @props = $obj->properties;
454         my $str = "";
455         for(@props) {
456                 my $prop = $obj->$_() || "";
457                 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
458                 $str .= " $_=$prop";
459         }
460         return $str;
461 }
462
463
464 sub __arg_to_string {
465         my $arg = shift;
466         return "" unless defined $arg;
467         if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
468                 return (defined $arg->id) ? $arg->id : '<new object>';
469         }
470         return OpenSRF::Utils::JSON->perl2JSON($arg);
471         return "";
472 }
473
474
475 # -----------------------------------------------------------------------------
476 # This does the actual storage query.
477 #
478 # 'search' calls become search_where calls and $arg can be a search hash or
479 # an array-ref of storage search options.  
480 #
481 # 'retrieve' expects an id
482 # 'update' expects an object
483 # 'create' expects an object
484 # 'delete' expects an object
485 #
486 # All methods return true on success and undef on failure.  On failure, 
487 # $e->event is set to the generated event.  
488 # Note: this method assumes that updating a non-changed object and 
489 # thereby receiving a 0 from storage, is a successful update.  
490 #
491 # The method will therefore return true so the caller can just do 
492 # $e->update_blah($x) or return $e->event;
493 # The true value returned from storage for all methods will be stored in 
494 # $e->data, until the next method is called.
495 #
496 # not-found events are generated on retrieve and serach methods.
497 # action=search methods will return [] (==true) if no data is found.  If the
498 # caller is interested in the not found event, they can do:  
499 # return $e->event unless @$results; 
500 # -----------------------------------------------------------------------------
501 sub runmethod {
502         my( $self, $action, $type, $arg, $options ) = @_;
503
504    $options ||= {};
505
506         if( $action eq 'retrieve' ) {
507                 if(! defined($arg) ) {
508                         $self->log(W,"$action $type called with no ID...");
509                         $self->event(_mk_not_found($type, $arg));
510                         return undef;
511                 } elsif( ref($arg) =~ /Fieldmapper/ ) {
512                         $self->log(E,"$action $type called with an object.. attempting ID retrieval..");
513                         $arg = $arg->id;
514                 }
515         }
516
517         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
518         my $method = $self->app.".direct.$type.$action";
519
520         if( $action eq 'search' ) {
521                 $method .= '.atomic';
522
523         } elsif( $action eq 'batch_retrieve' ) {
524                 $action = 'search';
525                 @arg = ( { id => $arg } );
526                 $method =~ s/batch_retrieve/search/o;
527                 $method .= '.atomic';
528
529         } elsif( $action eq 'retrieve_all' ) {
530                 $action = 'search';
531                 $method =~ s/retrieve_all/search/o;
532                 my $tt = $type;
533                 $tt =~ s/\./::/og;
534                 my $fmobj = "Fieldmapper::$tt";
535                 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
536                 $method .= '.atomic';
537         }
538
539         $method =~ s/search/id_list/o if $options->{idlist};
540
541     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
542     $self->timeout($$options{timeout});
543
544         # remove any stale events
545         $self->clear_event;
546
547         if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
548                 if(!$self->{xact}) {
549                         $logger->error("Attempt to update DB while not in a transaction : $method");
550                         throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
551                 }
552                 $self->log_activity($type, $action, $arg);
553         }
554
555         if($$options{checkperm}) {
556                 my $a = ($action eq 'search') ? 'retrieve' : $action;
557                 my $e = $self->_checkperm($type, $a, $$options{permorg});
558                 if($e) {
559                         $self->event($e);
560                         return undef;
561                 }
562         }
563
564         my $obj; 
565         my $err;
566
567         try {
568                 $obj = $self->request($method, @arg);
569         } catch Error with { $err = shift; };
570         
571
572         if(!defined $obj) {
573                 $self->log(I, "request returned no data : $method");
574
575                 if( $action eq 'retrieve' ) {
576                         $self->event(_mk_not_found($type, $arg));
577
578                 } elsif( $action eq 'update' or 
579                                 $action eq 'delete' or $action eq 'create' ) {
580                         my $evt = OpenILS::Event->new(
581                                 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
582                         $self->event($evt);
583                 }
584
585                 if( $err ) {
586                         $self->event( 
587                                 OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
588                                         payload => $arg, debug => "$err" ));
589                         return undef;
590                 }
591
592                 return undef;
593         }
594
595         if( $action eq 'create' and $obj == 0 ) {
596                 my $evt = OpenILS::Event->new(
597                         'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
598                 $self->event($evt);
599                 return undef;
600         }
601
602         # If we havn't dealt with the error in a nice way, go ahead and throw it
603         if( $err ) {
604                 $self->event( 
605                         OpenILS::Event->new( 'DATABASE_QUERY_FAILED', 
606                                 payload => $arg, debug => "$err" ));
607                 return undef;
608         }
609
610         if( $action eq 'search' ) {
611                 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
612                 $self->event(_mk_not_found($type, $arg)) unless @$obj;
613         }
614
615         if( $action eq 'create' ) {
616                 $self->log(I, "created a new $type object with ID " . $obj->id);
617                 $arg->id($obj->id);
618         }
619
620         $self->data($obj); # cache the data for convenience
621
622         return ($obj) ? $obj : 1;
623 }
624
625
626 sub _mk_not_found {
627         my( $type, $arg ) = @_;
628         (my $t = $type) =~ s/\./_/og;
629         $t = uc($t);
630         return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
631 }
632
633
634
635 # utility method for loading
636 sub __fm2meth { 
637         my $str = shift;
638         my $sep = shift;
639         $str =~ s/Fieldmapper:://o;
640         $str =~ s/::/$sep/g;
641         return $str;
642 }
643
644
645 # -------------------------------------------------------------
646 # Load up the methods from the FM classes
647 # -------------------------------------------------------------
648 my $map = $Fieldmapper::fieldmap;
649 for my $object (keys %$map) {
650         my $obj = __fm2meth($object,'_');
651         my $type = __fm2meth($object, '.');
652
653         my $update = "update_$obj";
654         my $updatef = 
655                 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
656         eval $updatef;
657
658         my $retrieve = "retrieve_$obj";
659         my $retrievef = 
660                 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
661         eval $retrievef;
662
663         my $search = "search_$obj";
664         my $searchf = 
665                 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
666         eval $searchf;
667
668         my $create = "create_$obj";
669         my $createf = 
670                 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
671         eval $createf;
672
673         my $delete = "delete_$obj";
674         my $deletef = 
675                 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
676         eval $deletef;
677
678         my $bretrieve = "batch_retrieve_$obj";
679         my $bretrievef = 
680                 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
681         eval $bretrievef;
682
683         my $retrieveall = "retrieve_all_$obj";
684         my $retrieveallf = 
685                 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";
686         eval $retrieveallf;
687 }
688
689 sub json_query {
690     my( $self, $arg, $options ) = @_;
691     $options ||= {};
692         my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
693     my $method = $self->app.'.json_query.atomic';
694     $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
695         $self->clear_event;
696     my $obj;
697     my $err;
698     
699     try {
700         $obj = $self->request($method, @arg);
701     } catch Error with { $err = shift; };
702
703     if( $err ) {
704         $self->event(
705             OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
706             payload => $arg, debug => "$err" ));
707         return undef;
708     }
709
710     $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)");
711     return $obj;
712 }
713
714
715
716 1;
717
718