source: trunk/LATMOS-Accounts/lib/LATMOS/Accounts/Bases/Objects.pm @ 1453

Last change on this file since 1453 was 1453, checked in by nanardon, 9 years ago

Add the ability to aggregate data in stat

  • Property svn:keywords set to Id Rev
File size: 18.3 KB
Line 
1package LATMOS::Accounts::Bases::Objects;
2
3use 5.010000;
4use strict;
5use warnings;
6
7use overload '""' => 'stringify';
8
9use LATMOS::Accounts::Log;
10use LATMOS::Accounts::Bases::Attributes;
11use Crypt::Cracklib;
12
13our $VERSION = (q$Rev$ =~ /^Rev: (\d+) /)[0];
14
15=head1 NAME
16
17LATMOS::Accounts::Bases::Objects - Base class for account objects
18
19=head1 SYNOPSIS
20
21  use LATMOS::Accounts::Bases::Objects;
22  LATMOS::Accounts::Bases::Objects->new($base, $type, $id);
23
24=head1 DESCRIPTION
25
26=head1 FUNCTIONS
27
28=cut
29
30=head2 is_supported
31
32If exists, must return true or false if the object is supported or not
33
34=cut
35
36=head2 list($base)
37
38List object supported by this module existing in base $base
39
40Must be provide by object class
41
42    sub list {
43        my ($class, $base) = @_;
44    }
45
46=cut
47
48=head2 list_from_rev($base, $rev)
49
50List objects create or modified after base revision C<$rev>.
51
52=cut
53
54=head2 new($base, $id)
55
56Create a new object having $id as uid.
57
58=cut
59
60sub new {
61    my ($class, $base, $id, @args) = @_;
62    # So can be call as $class->SUPER::new()
63    bless {
64        _base => $base,
65        _type => lc(($class =~ m/::([^:]*)$/)[0]),
66        _id => $id,
67    }, $class;
68}
69
70# _new($base, $type, $id, ...)
71
72# Return a new object of type $type having unique identifier
73# $id, all remaining arguments are passed to the subclass.
74
75sub _new {
76    my ($class, $base, $otype, $id, @args) = @_;
77
78    # finding perl class:
79    my $pclass = $base->_load_obj_class($otype) or return;
80    my $newobj = "$pclass"->new($base, $id, @args);
81
82    defined($newobj) or do {
83        $base->log(LA_DEBUG, "$pclass->new() returned undef for $otype / $id");
84        return;
85    };
86
87    $newobj->{_base} = $base;
88    $newobj->{_type} = lc($otype);
89    $newobj->{_id} ||= $id;
90
91    return $newobj;
92}
93
94=head2 _create($class, $base, $id, %data)
95
96Must create a new object in database.
97
98Is called if underling base does not override create_object
99
100    sub _create(
101        my ($class, $base, $id, %data)
102    }
103
104=cut
105
106=head2 type
107
108Return the type of the object
109
110=cut
111
112sub type {
113    my ($self) = @_;
114    if (ref $self) {
115        return $self->{_type}
116    } else {
117        return lc(($self =~ /::([^:]+)$/)[0]);
118    }
119}
120
121=head2 base
122
123Return the base handle for this object.
124
125=cut
126
127sub base {
128    return $_[0]->{_base}
129}
130
131=head2 id
132
133Must return the unique identifier for this object
134
135=cut
136
137sub id {
138    my ($self) = @_;
139    $self->{_id}
140}
141
142=head2 Iid
143
144Return internal id if different from Id
145
146=cut
147
148sub Iid {
149    my ($self) = @_;
150    $self->id
151}
152
153=head2 stringify
154
155Display object as a string
156
157=cut
158
159sub stringify {
160    my ($self) = @_;
161
162    return $self->id
163}
164
165=head2 list_canonical_fields($for)
166
167Object shortcut to get the list of field supported by the object.
168
169=cut
170
171sub list_canonical_fields {
172    my ($self, $for) = @_;
173    $for ||= 'rw';
174    $self->_canonical_fields($for);
175}
176
177=head2 attribute ($attribute)
178
179Return L<LATMOS::Accounts::Bases::Attributes> object for C<$attribute>
180
181=cut
182
183sub attribute {
184    my ($self, $attribute) = @_;
185
186    my $attrinfo;
187    if (! ref $attribute) {
188        $attrinfo = $self->_get_attr_schema(
189            $self->base)->{$attribute}
190        or return;
191        $attrinfo->{name} = $attribute;
192    } else {
193        $attrinfo = $attribute;
194    }
195
196    return LATMOS::Accounts::Bases::Attributes->new(
197        $attrinfo,
198        $self,
199    );
200}   
201
202sub _canonical_fields {
203    my ($class, $base, $for) = @_;
204    $for ||= 'rw';
205    my $info = $base->_get_attr_schema($class->type);
206    my @attrs = map { $base->attribute($class->type, $_) } keys %{$info || {}};
207    @attrs = grep { ! $_->ro } @attrs if($for =~ /w/);
208    @attrs = grep { $_->readable } @attrs if($for =~ /r/);
209    map { $_->name } grep { !$_->hidden }  @attrs;
210}
211
212=head2 get_field($field)
213
214Return the value for $field, must be provide by data base.
215
216    sub get_field {
217        my ($self, $field)
218    }
219
220=cut
221
222=head2 get_c_field($cfield)
223
224Return the value for canonical field $cfield.
225
226Call driver specific get_field()
227
228=cut
229
230sub get_c_field {
231    my ($self, $cfield) = @_;
232    $self->base->check_acl($self, $cfield, 'r') or do {
233        $self->base->log(LA_ERR, "Permission denied to get %s/%s",
234            $self->id, $cfield
235        );
236        return;
237    };
238    return $self->_get_c_field($cfield);
239}
240
241=head2 get_attributes($attr)
242
243Like get_c_field but always return an array
244
245=cut
246
247sub get_attributes {
248    my ($self, $cfield) = @_;
249    my $res = $self->get_c_field($cfield);
250    return ref $res ? @{ $res } : ($res);
251}
252
253sub _get_attributes {
254    my ($self, $cfield) = @_;
255    my $res = $self->_get_c_field($cfield);
256    return ref $res ? @{ $res } : ($res);
257}
258
259=head2 get_state ($state)
260
261Return an on fly computed value
262
263=cut
264
265sub get_state {
266    my ($self, $state) = @_;
267    # hum...
268    if (defined(my $res = $self->_get_state($state))) {
269        return $res;
270    }
271    for ($state) {
272    }
273    return;
274}
275
276sub _get_state {
277    my ($self, $state) = @_;
278    return;
279}
280
281sub _get_c_field {
282    my ($self, $cfield) = @_;
283    my $attribute = $self->attribute($cfield) or do {
284        $self->base->log(LA_WARN, "Unknow attribute $cfield");
285        return;
286    };
287    $attribute->readable or do {
288        $self->base->log(LA_WARN, "Attribute $cfield is not readable");
289        return;
290    };
291    return $attribute->get; 
292}
293
294=head2 queryformat ($fmt)
295
296Return formated string according C<$fmt>
297
298=cut
299
300sub queryformat {
301    my ($self, $fmt) = @_;
302    $fmt =~ s/\\n/\n/g;
303    $fmt =~ s!
304        (?:%\{([^:}]*)(?::([^}]+))?\})
305        !
306        my $val = $self->get_c_field($1);
307        sprintf('%' . ($2 || 's'), ref $val ? join(',', @$val) : ($val||''))
308        !egx;
309    $fmt;
310}
311
312=head2 set_fields(%data)
313
314Set values for this object. %data is a list or peer field => values.
315
316    sub set_fields {
317        my ($self, %data) = @_;
318    }
319
320=cut
321
322=head2 check_allowed_values ($attr, $values)
323
324Check if value C<$values> is allowed for attributes C<$attr>
325
326=cut
327
328sub check_allowed_values {
329    my ($self, $attr, $values) = @_;
330    $self->base->check_allowed_values($self->type, $attr, $values);
331}
332
333=head2 attr_allow_values ($attr)
334
335Return allowed for attribute C<$attr>
336
337=cut
338
339sub attr_allow_values {
340    my ($self, $attr) = @_;
341    return $self->base->obj_attr_allowed_values(
342        $self->type,
343        $attr,
344    );
345}
346
347=head2 set_c_fields(%data)
348
349Set values for this object. %data is a list or peer
350canonical field => values. Fields names are translated.
351
352=cut
353
354sub set_c_fields {
355    my ($self, %cdata) = @_;
356    foreach my $cfield (keys %cdata) {
357        $self->base->check_acl($self, $cfield, 'w') or do { 
358            $self->base->log(LA_ERR, "Cannot modified %s/%s: %s",
359                $self->type, $self->id, "permission denied");
360            return;
361        };
362    }
363
364    foreach my $cfield (keys %cdata) {
365        $self->check_allowed_values($cfield, $cdata{$cfield}) or do {
366            $self->base->log(LA_ERR, "Cannot modified %s/%s: %s",
367                $self->type, $self->id, "non authorized value");
368            return;
369        };
370    }
371    $self->_set_c_fields(%cdata);
372}
373
374sub _set_c_fields {
375    my ($self, %cdata) = @_;
376    my %data;
377    my $res = 0;
378    foreach my $cfield (keys %cdata) {
379        my $attribute = $self->attribute($cfield) or do {
380            $self->base->log(LA_ERR,
381                "Cannot set unsupported attribute %s to %s (%s)",
382                $cfield, $self->id, $self->type
383            );
384            return;
385        };
386        $attribute->ro and do {
387            $self->base->log(LA_ERR,
388                "Cannot set read-only attribute %s to %s (%s)",
389                $cfield, $self->id, $self->type
390            );
391            return;
392        };
393
394        if (!$attribute->checkinput($cdata{$cfield})) {
395            $self->base->log(LA_ERR,
396                "Value for attribute %s to %s (%s) does not match requirements",
397                $cfield, $self->id, $self->type
398            );
399            return;
400        };
401    }
402
403    my %updated = ();
404    foreach my $cfield (keys %cdata) {
405        my $attribute = $self->attribute($cfield) or do {
406            $self->base->log(LA_ERR,
407                "Cannot set unsupported attribute %s to %s (%s)",
408                $cfield, $self->id, $self->type
409            );
410            return;
411        };
412        if ($attribute->set($cdata{$cfield})) {
413            $updated{$cfield} = $attribute->monitored;
414        }
415    }
416   
417    if (keys %updated) {
418        $self->ReportChange('Update', 'Attributes %s where updated', join(', ', sort keys %updated));
419        foreach (sort keys %updated) {
420            $self->ReportChange('Attributes', '%s set to %s', $_, 
421                (ref $cdata{$_}
422                    ? join(', ', @{ $cdata{$_} })
423                    : $cdata{$_}) || '(none)')
424                if ($updated{$_});
425        }
426    }
427    return scalar(keys %updated);
428}
429
430=head2 addAttributeValue($attribute, $value)
431
432Add a value to a multivalue attributes
433
434=cut
435
436sub _addAttributeValue {
437    my ($self, $attribute, @values) = @_;
438
439    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
440    $self->_set_c_fields($attribute => [ @oldvalues, @values ]);
441}
442
443sub addAttributeValue {
444    my ($self, $attribute, @values) = @_;
445
446    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
447    $self->set_c_fields($attribute => [ @oldvalues, @values ]);
448}
449
450=head2 delAttributeValue($attribute, $value)
451
452Remove a value to a multivalue attributes
453
454=cut
455
456sub _delAttributeValue {
457    my ($self, $attribute, @values) = @_;
458
459    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
460
461    foreach my $value (@values) {
462        @oldvalues = grep { $_ ne $value } @oldvalues;
463    }
464
465    $self->_set_c_fields($attribute => @oldvalues ? [ @oldvalues, ] : undef );
466}
467
468sub delAttributeValue {
469    my ($self, $attribute, @values) = @_;
470
471    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
472
473    foreach my $value (@values) {
474        @oldvalues = grep { $_ ne $value } @oldvalues;
475    }
476
477    $self->set_c_fields($attribute => @oldvalues ? [ @oldvalues, ] : undef );
478}
479
480=head2 set_password($password)
481
482Set the password into the database, $password is the clear version
483of the password.
484
485This function store it into userPassword canonical field if supported
486using crypt unix and md5 algorythm (crypt md5), the salt is 8 random
487caracters.
488
489The base driver should override it if another encryption is need.
490
491=cut
492
493sub set_password {
494    my ($self, $clear_pass) = @_;
495    if ($self->base->check_acl($self, 'userPassword', 'w')) {
496        if ($self->_set_password($clear_pass)) {
497             $self->ReportChange('Password', 'user password has changed');
498             return 1;
499        } else {
500            return;
501        }
502    } else {
503        $self->base->log(LA_ERROR, "Permission denied for %s to change its password",
504            $self->id);
505        return;
506    }
507}
508
509sub _set_password {
510    my ($self, $clear_pass) = @_;
511    if (my $attribute = $self->base->attribute($self->type, 'userPassword')) {
512        my @salt_char = (('a' .. 'z'), ('A' .. 'Z'), (0 .. 9), '/', '.');
513        my $salt = join('', map { $salt_char[rand(scalar(@salt_char))] } (1 .. 8));
514        my $res = $self->set_fields($attribute->iname, crypt($clear_pass, '$1$' . $salt));
515        $self->base->log(LA_NOTICE, 'Mot de passe changé pour %s', $self->id)
516            if($res);
517        return $res;
518    } else {
519        $self->base->log(LA_WARN,
520            "Cannot set password: userPassword attributes is unsupported");
521    }
522}
523
524=head2 check_password ($password)
525
526Check given password is secure using L<Crypt::Cracklib>
527
528=cut
529
530sub check_password {
531    my ( $self, $password ) = @_;
532    my $dictionary;
533
534    if ($password !~ /^[[:ascii:]]*$/) {
535       return "the password must contains ascii characters only";
536    }
537
538    return fascist_check($password, $dictionary);
539}
540
541=head2 search ($base, @filter)
542
543Search object matching C<@filter>
544
545=cut
546
547sub search {
548    my ($class, $base, @filter) = @_;
549    my @results;
550    my %parsed_filter;
551    while (my $item = shift(@filter)) {
552        # attr=foo => no extra white space !
553        # \W is false, it is possible to have two char
554        my ($attr, $mode, $val) = $item =~ /^(\w+)(?:(\W)(.+))?$/ or next;
555        if (!$mode) {
556            $mode = '~';
557            $val = shift(@filter);
558        }
559        push(
560            @{$parsed_filter{$attr}},
561            {
562                attr => $attr,
563                mode => $mode,
564                val  => $val,
565            }
566        );
567    }
568    foreach my $id ($base->list_objects($class->type)) {
569        my $obj = $base->get_object($class->type, $id);
570        my $match = 1;
571        foreach my $field (keys %parsed_filter) {
572            $base->attribute($class->type, $field) or
573                la_log LA_WARN "Unsupported attribute $field";
574            my $tmatch = 0;
575            foreach (@{$parsed_filter{$field}}) {
576                my $value = $_->{val};
577                my $fval = $obj->_get_c_field($field) || '';
578                if ($value eq '*') {
579                    if ($fval ne '') {
580                        $tmatch = 1;
581                        last;
582                    }
583                } elsif ($value eq '!') {
584                    if ($fval eq '') {
585                        $match = 1;
586                        last;
587                    }
588                } elsif ($_->{mode} eq '=') {
589                    if ($fval eq $value) {
590                        $tmatch = 1;
591                        last;
592                    }
593                } elsif($_->{mode} eq '~') {
594                    if ($fval =~ m/\Q$value\E/i) {
595                        $tmatch = 1;
596                        last;
597                    }
598                }
599            }
600            $match = 0 unless($tmatch);
601        }
602        push(@results, $id) if($match);
603    }
604    @results;
605}
606
607=head2 attributes_summary ($base, $attribute)
608
609Return list of values existing in base for C<$attribute>
610
611=cut
612
613sub attributes_summary {
614    my ($class, $base, $attribute) = @_;
615    my %values;
616    foreach my $id ($base->list_objects($class->type)) {
617        my $obj = $base->get_object($class->type, $id);
618        my $value = $obj->_get_c_field($attribute);
619        if ($value) {
620            if (ref $value) {
621                foreach (@$value) {
622                    $values{$_} = 1;
623                }
624            } else {
625                $values{$value} = 1;
626            }
627        }
628    }
629    return sort(keys %values);
630}
631
632=head2 attributes_summary_by_object ($base, $attribute)
633
634Return list of peer object <=> values
635
636=cut
637
638sub attributes_summary_by_object {
639    my ($class, $base, $attribute) = @_;
640    my %values;
641    foreach my $id ($base->list_objects($class->type)) {
642        my $obj = $base->get_object($class->type, $id);
643        my $value = $obj->_get_c_field($attribute);
644        if ($value) {
645            if (ref $value) {
646                foreach (@$value) {
647                    push(@{ $values{ $id } }, $_);
648                }
649            } else {
650                push(@{ $values{ $id } }, $value);
651            }
652        }
653    }
654    return %values;
655}
656
657=head2 find_next_numeric_id ($base, $field, $min, $max)
658
659Find next free uniq id for attribute C<$field>
660
661=cut
662
663sub find_next_numeric_id {
664    my ($class, $base, $field, $min, $max) = @_;
665    $base->attribute($class->type, $field) or return;
666    $min ||= 
667        $field eq 'uidNumber' ? 500 :
668        $field eq 'gidNumber' ? 500 :
669        1;
670    $max ||= 65635;
671    $base->log(LA_DEBUG, "Trying to find %s in range %d - %d",
672        $field, $min, $max);
673    my %existsid;
674    $base->temp_switch_unexported(sub {
675        foreach ($base->list_objects($class->type)) {
676            my $obj = $base->get_object($class->type, $_) or next;
677            my $id = $obj->_get_c_field($field) or next;
678            $existsid{$id + 0} = 1;
679        }
680    }, 1);
681    $min += 0;
682    $max += 0;
683    for(my $i = $min; $i <= $max; $i++) {
684        $existsid{$i + 0} or do {
685            $base->log(LA_DEBUG, "Next %s found: %d", $field, $i);
686            return $i;
687        };
688    }
689    return;
690}
691
692=head2 text_dump ($handle, $config, $base)
693
694Dump object into C<$handle>
695
696=cut
697
698sub text_dump {
699    my ($self, $handle, $config, $base) = @_;
700    print $handle $self->dump($config, $base);
701    return 1;
702}
703
704=head2 dump
705
706Return dump for tihs object
707
708=cut
709
710sub dump {
711    my ($self, $config, $base) = @_;
712
713    my $otype = $self->type;
714    $base ||= $self->base;
715    my $dump;
716    if (ref $self) {
717        $dump .= sprintf "# base %s: object %s/%s\n",
718            $base->label, $self->type, $self->id;
719    }
720    $dump .= sprintf "# %s\n", scalar(localtime);
721
722    foreach my $attr (sort { $a cmp $b } $base->list_canonical_fields($otype,
723        $config->{only_rw} ? 'rw' : 'r')) {
724        my $oattr = ref $self ? $self->attribute($attr) : $base->attribute($otype, $attr);
725        if (ref $self) {
726            my $val = $self->get_c_field($attr);
727            if ($val || $config->{empty_attr}) {
728                if (my @allowed = $base->obj_attr_allowed_values($otype, $attr)) {
729                    $dump .= sprintf("# %s must be%s: %s\n",
730                        $attr,
731                        ($oattr->mandatory ? '' : ' empty or either'),
732                        join(', ', @allowed)
733                    );
734                }
735                my @vals = ref $val ? @{ $val } : $val;
736                foreach (@vals) {
737                    $_ ||= '';
738                    s/\r?\n/\\n/g;
739                    $dump .= sprintf("%s%s:%s\n", 
740                        $oattr->ro ? '# (ro) ' : '',
741                        $attr, $_ ? " $_" : '');
742                }
743            }
744        } else {
745            if (my @allowed = $base->obj_attr_allowed_values($otype, $attr)) {
746                $dump .= sprintf("# %s must be empty or either: %s\n",
747                    $attr,
748                    join(', ', @allowed)
749                );
750            }
751            $dump .= sprintf("%s%s: %s\n", 
752                $oattr->ro ? '# (ro) ' : '',
753                $attr, '');
754        }
755    }
756    return $dump;
757}
758
759=head2 ReportChange($changetype, $message, @args)
760
761Possible per database way to log changes
762
763=cut
764
765sub ReportChange {
766    my ($self, $changetype, $message, @args) = @_;
767
768    $self->base->ReportChange(
769        $self->type,
770        $self->id,
771        $self->Iid,
772        $changetype, $message, @args
773    )
774}
775
7761;
777
778__END__
779
780
781=head1 SEE ALSO
782
783L<LATMOS::Accounts::Bases>
784
785=head1 AUTHOR
786
787Thauvin Olivier, E<lt>olivier.thauvin.ipsl.fr@localdomainE<gt>
788
789=head1 COPYRIGHT AND LICENSE
790
791Copyright (C) 2009 by Thauvin Olivier
792
793This library is free software; you can redistribute it and/or modify
794it under the same terms as Perl itself, either Perl version 5.10.0 or,
795at your option, any later version of Perl 5 you may have available.
796
797=cut
Note: See TracBrowser for help on using the repository browser.