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

Last change on this file since 1595 was 1595, checked in by nanardon, 8 years ago

Fix my bad english

  • Property svn:keywords set to Id Rev
File size: 20.0 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 / %s", $id || '(none)');
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    if ($res) {
251        return(ref $res ? @{$res} : $res);
252    } else {
253        return;
254    }
255}
256
257sub _get_attributes {
258    my ($self, $cfield) = @_;
259    my $res = $self->_get_c_field($cfield);
260    if ($res) {
261        return(ref $res ? @{$res} : ($res));
262    } else {
263        return;
264    }
265}
266
267=head2 get_state ($state)
268
269Return an on fly computed value
270
271=cut
272
273sub get_state {
274    my ($self, $state) = @_;
275    # hum...
276    if (defined(my $res = $self->_get_state($state))) {
277        return $res;
278    }
279    for ($state) {
280    }
281    return;
282}
283
284sub _get_state {
285    my ($self, $state) = @_;
286    return;
287}
288
289sub _get_c_field {
290    my ($self, $cfield) = @_;
291    my $attribute = $self->attribute($cfield) or do {
292        $self->base->log(LA_WARN, "Unknow attribute $cfield");
293        return;
294    };
295    $attribute->readable or do {
296        $self->base->log(LA_WARN, "Attribute $cfield is not readable");
297        return;
298    };
299    return $attribute->get; 
300}
301
302=head2 queryformat ($fmt)
303
304Return formated string according C<$fmt>
305
306=cut
307
308sub queryformat {
309    my ($self, $fmt) = @_;
310    $fmt =~ s/\\n/\n/g;
311    $fmt =~ s/\\t/\t/g;
312    $fmt =~ s!
313        (?:%\{([^:}]*)(?::([^}]+))?\})
314        !
315        my $val = $self->get_c_field($1);
316        sprintf('%' . ($2 || 's'), ref $val ? join(',', @$val) : ($val||''))
317        !egx;
318    $fmt;
319}
320
321=head2 set_fields(%data)
322
323Set values for this object. %data is a list or peer field => values.
324
325    sub set_fields {
326        my ($self, %data) = @_;
327    }
328
329=cut
330
331=head2 checkValues ($base, $obj, %attributes)
332
333Allow to pre-check values when object are modified or created
334
335C<$obj> is either the new id at object creation or the object itself on modification.
336
337=cut
338
339sub checkValues {
340    my ($class, $base, $obj, %attributes) = @_;
341
342    return 1;
343}
344
345=head2 check_allowed_values ($attr, $values)
346
347Check if value C<$values> is allowed for attributes C<$attr>
348
349=cut
350
351sub check_allowed_values {
352    my ($self, $attr, $values) = @_;
353    $self->base->check_allowed_values($self->type, $attr, $values);
354}
355
356=head2 attr_allow_values ($attr)
357
358Return allowed for attribute C<$attr>
359
360=cut
361
362sub attr_allow_values {
363    my ($self, $attr) = @_;
364    return $self->base->obj_attr_allowed_values(
365        $self->type,
366        $attr,
367    );
368}
369
370=head2 set_c_fields(%data)
371
372Set values for this object. %data is a list or peer
373canonical field => values. Fields names are translated.
374
375=cut
376
377sub set_c_fields {
378    my ($self, %cdata) = @_;
379    foreach my $cfield (keys %cdata) {
380        $self->base->check_acl($self, $cfield, 'w') or do { 
381            $self->base->log(LA_ERR, "Cannot modified %s/%s: %s",
382                $self->type, $self->id, "permission denied");
383            return;
384        };
385    }
386
387    foreach my $cfield (keys %cdata) {
388        $self->check_allowed_values($cfield, $cdata{$cfield}) or do {
389            $self->base->log(LA_ERR, "Cannot modified %s/%s: %s",
390                $self->type, $self->id, "non authorized value");
391            return;
392        };
393    }
394
395    $self->_set_c_fields(%cdata);
396}
397
398sub _set_c_fields {
399    my ($self, %cdata) = @_;
400    my %data;
401    my $res = 0;
402    foreach my $cfield (keys %cdata) {
403        my $attribute = $self->attribute($cfield) or do {
404            $self->base->log(LA_ERR,
405                "Cannot set unsupported attribute %s to %s (%s)",
406                $cfield, $self->id, $self->type
407            );
408            return;
409        };
410        $attribute->ro and do {
411            $self->base->log(LA_ERR,
412                "Cannot set read-only attribute %s to %s (%s)",
413                $cfield, $self->id, $self->type
414            );
415            return;
416        };
417
418        if (!$attribute->checkinput($cdata{$cfield})) {
419            $self->base->log(LA_ERR,
420                "Value for attribute %s to %s (%s) does not match requirements",
421                $cfield, $self->id, $self->type
422            );
423            return;
424        };
425    }
426
427    if (!$self->checkValues($self->base, $self, %cdata)) {
428        my $last = LATMOS::Accounts::Log::lastmessage(LA_ERR);
429        $self->base->log(LA_ERR,
430            "Cannot update %s (%s): wrong value%s",
431            $self->id, $self->type,
432            ($last ? ": $last" : $last)
433        );
434        return;
435    }
436
437    my %updated = ();
438    foreach my $cfield (keys %cdata) {
439        my $attribute = $self->attribute($cfield) or do {
440            $self->base->log(LA_ERR,
441                "Cannot set unsupported attribute %s to %s (%s)",
442                $cfield, $self->id, $self->type
443            );
444            return;
445        };
446        if ($attribute->set($cdata{$cfield})) {
447            $updated{$cfield} = $attribute->monitored;
448        }
449    }
450   
451    if (keys %updated) {
452        $self->ReportChange('Update', 'Attributes %s have been updated', join(', ', sort keys %updated));
453        foreach (sort keys %updated) {
454            $self->ReportChange('Attributes', '%s set to %s', $_, 
455                (ref $cdata{$_}
456                    ? join(', ', @{ $cdata{$_} })
457                    : $cdata{$_}) || '(none)')
458                if ($updated{$_});
459        }
460    }
461    return scalar(keys %updated);
462}
463
464=head2 addAttributeValue($attribute, $value)
465
466Add a value to a multivalue attributes
467
468=cut
469
470sub _addAttributeValue {
471    my ($self, $attribute, @values) = @_;
472
473    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
474    $self->_set_c_fields($attribute => [ @oldvalues, @values ]);
475}
476
477sub addAttributeValue {
478    my ($self, $attribute, @values) = @_;
479
480    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
481    $self->set_c_fields($attribute => [ @oldvalues, @values ]);
482}
483
484=head2 delAttributeValue($attribute, $value)
485
486Remove a value to a multivalue attributes
487
488=cut
489
490sub _delAttributeValue {
491    my ($self, $attribute, @values) = @_;
492
493    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
494
495    foreach my $value (@values) {
496        @oldvalues = grep { $_ ne $value } @oldvalues;
497    }
498
499    $self->_set_c_fields($attribute => @oldvalues ? [ @oldvalues, ] : undef );
500}
501
502sub delAttributeValue {
503    my ($self, $attribute, @values) = @_;
504
505    my @oldvalues = grep { $_ } $self->_get_attributes($attribute);
506
507    foreach my $value (@values) {
508        @oldvalues = grep { $_ ne $value } @oldvalues;
509    }
510
511    $self->set_c_fields($attribute => @oldvalues ? [ @oldvalues, ] : undef );
512}
513
514=head2 set_password($password)
515
516Set the password into the database, $password is the clear version
517of the password.
518
519This function store it into userPassword canonical field if supported
520using crypt unix and md5 algorythm (crypt md5), the salt is 8 random
521caracters.
522
523The base driver should override it if another encryption is need.
524
525=cut
526
527sub set_password {
528    my ($self, $clear_pass) = @_;
529    if ($self->base->check_acl($self, 'userPassword', 'w')) {
530        if ($self->_set_password($clear_pass)) {
531             $self->ReportChange('Password', 'user password has changed');
532             return 1;
533        } else {
534            return;
535        }
536    } else {
537        $self->base->log(LA_ERROR, "Permission denied for %s to change its password",
538            $self->id);
539        return;
540    }
541}
542
543sub _set_password {
544    my ($self, $clear_pass) = @_;
545    if (my $attribute = $self->base->attribute($self->type, 'userPassword')) {
546        my @salt_char = (('a' .. 'z'), ('A' .. 'Z'), (0 .. 9), '/', '.');
547        my $salt = join('', map { $salt_char[rand(scalar(@salt_char))] } (1 .. 8));
548        my $res = $self->set_fields($attribute->iname, crypt($clear_pass, '$1$' . $salt));
549        $self->base->log(LA_NOTICE, 'Mot de passe changé pour %s', $self->id)
550            if($res);
551        return $res;
552    } else {
553        $self->base->log(LA_WARN,
554            "Cannot set password: userPassword attributes is unsupported");
555    }
556}
557
558=head2 check_password ($password)
559
560Check given password is secure using L<Crypt::Cracklib>
561
562=cut
563
564sub check_password {
565    my ( $self, $password ) = @_;
566    my $dictionary;
567
568    if ($password !~ /^[[:ascii:]]*$/) {
569       return "the password must contains ascii characters only";
570    }
571
572    return fascist_check($password, $dictionary);
573}
574
575=head2 search ($base, @filter)
576
577Search object matching C<@filter>
578
579=cut
580
581sub search {
582    my ($class, $base, @filter) = @_;
583    my @results;
584    my %parsed_filter;
585    while (my $item = shift(@filter)) {
586        # attr=foo => no extra white space !
587        # \W is false, it is possible to have two char
588        my ($attr, $mode, $val) = $item =~ /^(\w+)(?:(\W)(.+))?$/ or next;
589        if (!$mode) {
590            $mode = '~';
591            $val = shift(@filter);
592        }
593        push(
594            @{$parsed_filter{$attr}},
595            {
596                attr => $attr,
597                mode => $mode,
598                val  => $val,
599            }
600        );
601    }
602    foreach my $id ($base->list_objects($class->type)) {
603        my $obj = $base->get_object($class->type, $id);
604        my $match = 1;
605        foreach my $field (keys %parsed_filter) {
606            $base->attribute($class->type, $field) or
607                la_log LA_WARN "Unsupported attribute $field";
608            my $tmatch = 0;
609            foreach (@{$parsed_filter{$field}}) {
610                my $value = $_->{val};
611                my $fval = $obj->_get_c_field($field) || '';
612                if ($value eq '*') {
613                    if ($fval ne '') {
614                        $tmatch = 1;
615                        last;
616                    }
617                } elsif ($value eq '!') {
618                    if ($fval eq '') {
619                        $match = 1;
620                        last;
621                    }
622                } elsif ($_->{mode} eq '=') {
623                    if ($fval eq $value) {
624                        $tmatch = 1;
625                        last;
626                    }
627                } elsif($_->{mode} eq '~') {
628                    if ($fval =~ m/\Q$value\E/i) {
629                        $tmatch = 1;
630                        last;
631                    }
632                }
633            }
634            $match = 0 unless($tmatch);
635        }
636        push(@results, $id) if($match);
637    }
638    @results;
639}
640
641=head2 attributes_summary ($base, $attribute)
642
643Return list of values existing in base for C<$attribute>
644
645=cut
646
647sub attributes_summary {
648    my ($class, $base, $attribute) = @_;
649    my $attr = $base->attribute($class->type, $attribute) or do {
650        $base->log(LA_ERR, "Cannot instantiate %s attribute", $attribute);
651        return;
652    };
653    if (!$attr->readable) {
654        $base->log(LA_WARN, l('Attribute %s is not readable', $attribute));
655        return;
656    }
657    if (!$base->check_acl($class->type, $attribute, 'r')) {
658        $base->log(LA_WARN, l('Permission denied to read attribute %s', $attribute));
659        return;
660    }
661    my %values;
662    foreach my $id ($base->list_objects($class->type)) {
663        my $obj = $base->get_object($class->type, $id);
664        my $value = $obj->_get_c_field($attribute);
665        if ($value) {
666            if (ref $value) {
667                foreach (@$value) {
668                    $values{$_} = 1;
669                }
670            } else {
671                $values{$value} = 1;
672            }
673        }
674    }
675    return sort(keys %values);
676}
677
678=head2 attributes_summary_by_object ($base, $attribute)
679
680Return list of peer object <=> values
681
682=cut
683
684sub attributes_summary_by_object {
685    my ($class, $base, $attribute) = @_;
686    my $attr = $base->attribute($class->type, $attribute) or do {
687        $base->log(LA_ERR, "Cannot instantiate %s attribute", $attribute);
688        return;
689    };
690    if (!$attr->readable) {
691        $base->log(LA_WARN, l('Attribute %s is not readable', $attribute));
692        return;
693    }
694    if (!$base->check_acl($class->type, $attribute, 'r')) {
695        $base->log(LA_WARN, l('Permission denied to read attribute %s', $attribute));
696        return;
697    }
698    my %values;
699    foreach my $id ($base->list_objects($class->type)) {
700        my $obj = $base->get_object($class->type, $id);
701        my $value = $obj->_get_c_field($attribute);
702        if ($value) {
703            if (ref $value) {
704                foreach (@$value) {
705                    push(@{ $values{ $id } }, $_);
706                }
707            } else {
708                push(@{ $values{ $id } }, $value);
709            }
710        }
711    }
712    return %values;
713}
714
715=head2 find_next_numeric_id ($base, $field, $min, $max)
716
717Find next free uniq id for attribute C<$field>
718
719=cut
720
721sub find_next_numeric_id {
722    my ($class, $base, $field, $min, $max) = @_;
723    $base->attribute($class->type, $field) or return;
724    $min ||= 
725        $field eq 'uidNumber' ? 500 :
726        $field eq 'gidNumber' ? 500 :
727        1;
728    $max ||= 65635;
729    $base->log(LA_DEBUG, "Trying to find %s in range %d - %d",
730        $field, $min, $max);
731    my %existsid;
732    $base->temp_switch_unexported(sub {
733        foreach ($base->list_objects($class->type)) {
734            my $obj = $base->get_object($class->type, $_) or next;
735            my $id = $obj->_get_c_field($field) or next;
736            $existsid{$id + 0} = 1;
737        }
738    }, 1);
739    $min += 0;
740    $max += 0;
741    for(my $i = $min; $i <= $max; $i++) {
742        $existsid{$i + 0} or do {
743            $base->log(LA_DEBUG, "Next %s found: %d", $field, $i);
744            return $i;
745        };
746    }
747    return;
748}
749
750=head2 text_dump ($handle, $config, $base)
751
752Dump object into C<$handle>
753
754=cut
755
756sub text_dump {
757    my ($self, $handle, $config, $base) = @_;
758    print $handle $self->dump($config, $base);
759    return 1;
760}
761
762=head2 dump
763
764Return dump for tihs object
765
766=cut
767
768sub dump {
769    my ($self, $config, $base) = @_;
770
771    my $otype = $self->type;
772    $base ||= $self->base;
773    my $dump;
774    if (ref $self) {
775        $dump .= sprintf "# base %s: object %s/%s\n",
776            $base->label, $self->type, $self->id;
777    }
778    $dump .= sprintf "# %s\n", scalar(localtime);
779
780    foreach my $attr (sort { $a cmp $b } $base->list_canonical_fields($otype,
781        $config->{only_rw} ? 'rw' : 'r')) {
782        my $oattr = ref $self ? $self->attribute($attr) : $base->attribute($otype, $attr);
783        if ($oattr->hidden) { next; }
784        if (ref $self) {
785            my $val = $self->get_c_field($attr);
786            if ($val || $config->{empty_attr}) {
787                if (my @allowed = $base->obj_attr_allowed_values($otype, $attr)) {
788                    $dump .= sprintf("# %s must be%s: %s\n",
789                        $attr,
790                        ($oattr->mandatory ? '' : ' empty or either'),
791                        join(', ', @allowed)
792                    );
793                }
794                my @vals = ref $val ? @{ $val } : $val;
795                foreach (@vals) {
796                    $_ ||= '';
797                    s/\r?\n/\\n/g;
798                    $dump .= sprintf("%s%s:%s\n", 
799                        $oattr->ro ? '# (ro) ' : '',
800                        $attr, $_ ? " $_" : '');
801                }
802            }
803        } else {
804            if (my @allowed = $base->obj_attr_allowed_values($otype, $attr)) {
805                $dump .= sprintf("# %s must be empty or either: %s\n",
806                    $attr,
807                    join(', ', @allowed)
808                );
809            }
810            $dump .= sprintf("%s%s: %s\n", 
811                $oattr->ro ? '# (ro) ' : '',
812                $attr, '');
813        }
814    }
815    return $dump;
816}
817
818=head2 ReportChange($changetype, $message, @args)
819
820Possible per database way to log changes
821
822=cut
823
824sub ReportChange {
825    my ($self, $changetype, $message, @args) = @_;
826
827    $self->base->ReportChange(
828        $self->type,
829        $self->id,
830        $self->Iid,
831        $changetype, $message, @args
832    )
833}
834
8351;
836
837__END__
838
839
840=head1 SEE ALSO
841
842L<LATMOS::Accounts::Bases>
843
844=head1 AUTHOR
845
846Thauvin Olivier, E<lt>olivier.thauvin.ipsl.fr@localdomainE<gt>
847
848=head1 COPYRIGHT AND LICENSE
849
850Copyright (C) 2009 by Thauvin Olivier
851
852This library is free software; you can redistribute it and/or modify
853it under the same terms as Perl itself, either Perl version 5.10.0 or,
854at your option, any later version of Perl 5 you may have available.
855
856=cut
Note: See TracBrowser for help on using the repository browser.