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