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

Last change on this file since 2208 was 2182, checked in by nanardon, 5 years ago

Really ensure all attributes get created

  • Property svn:keywords set to Id Rev
File size: 20.1 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: 2072 $ =~ /^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 listReal($base)
49
50List object supported by this module existing in base $base
51
52Can be override by base driver. The result must exclude specials object such alias.
53
54=cut
55
56sub listReal {
57    my ($class, $base) = @_;
58    $class->list($base);
59}
60
61=head2 list_from_rev($base, $rev)
62
63List objects create or modified after base revision C<$rev>.
64
65=cut
66
67=head2 new($base, $id)
68
69Create a new object having $id as uid.
70
71=cut
72
73sub new {
74    my ($class, $base, $id, @args) = @_;
75    # So can be call as $class->SUPER::new()
76    bless {
77        _base => $base,
78        _type => lc(($class =~ m/::([^:]*)$/)[0]),
79        _id => $id,
80    }, $class;
81}
82
83=head2 _create($class, $base, $id, %data)
84
85Must create a new object in database.
86
87Is called if underling base does not override create_object
88
89    sub _create(
90        my ($class, $base, $id, %data)
91    }
92
93=cut
94
95=head2 type
96
97Return the type of the object
98
99=cut
100
101sub type {
102    my ($self) = @_;
103    if (ref $self) {
104        return $self->{_type}
105    } else {
106        return lc(($self =~ /::([^:]+)$/)[0]);
107    }
108}
109
110=head2 base
111
112Return the base handle for this object.
113
114=cut
115
116sub base {
117    return $_[0]->{_base}
118}
119
120=head2 id
121
122Must return the unique identifier for this object
123
124=cut
125
126sub id {
127    my ($self) = @_;
128    $self->{_id}
129}
130
131=head2 Iid
132
133Return internal id if different from Id
134
135=cut
136
137sub Iid {
138    my ($self) = @_;
139    $self->id
140}
141
142=head2 stringify
143
144Display object as a string
145
146=cut
147
148sub stringify {
149    my ($self) = @_;
150
151    return $self->id
152}
153
154=head2 list_canonical_fields($for)
155
156Object shortcut to get the list of field supported by the object.
157
158=cut
159
160sub list_canonical_fields {
161    my ($self, $for) = @_;
162    $for ||= 'rw';
163    $self->_canonical_fields($for);
164}
165
166=head2 attribute ($attribute)
167
168Return L<LATMOS::Accounts::Bases::Attributes> object for C<$attribute>
169
170=cut
171
172sub attribute {
173    my ($self, $attribute) = @_;
174
175    my $attrinfo;
176    if (! ref $attribute) {
177        $attrinfo = $self->_get_attr_schema(
178            $self->base)->{$attribute}
179        or return;
180        $attrinfo->{name} = $attribute;
181    } else {
182        $attrinfo = $attribute;
183    }
184
185    return LATMOS::Accounts::Bases::Attributes->new(
186        $attrinfo,
187        $self,
188    );
189}   
190
191sub _canonical_fields {
192    my ($class, $base, $for) = @_;
193    $for ||= 'rw';
194    my $info = $base->_get_attr_schema($class->type);
195    my @attrs = map { $base->attribute($class->type, $_) } keys %{$info || {}};
196    @attrs = grep { ! $_->ro } @attrs if($for =~ /w/);
197    @attrs = grep { $_->readable } @attrs if($for =~ /r/);
198    @attrs = grep { !$_->hidden }  @attrs unless($for =~ /a/);
199    map { $_->name } @attrs;
200}
201
202=head2 GetOtypeDef
203
204This function is called to provide sub object definition. Must be overwritten
205per object class when need.
206
207Must return a hashref listing each sub object type and their related key atribute:
208
209    return {
210        addresses => 'user',
211    }
212
213=cut
214
215sub GetOtypeDef {
216    my ($class) = @_;
217
218    return;
219}
220
221=head2 get_field($field)
222
223Return the value for $field, must be provide by data base.
224
225    sub get_field {
226        my ($self, $field)
227    }
228
229=cut
230
231=head2 get_c_field($cfield)
232
233Return the value for canonical field $cfield.
234
235Call driver specific get_field()
236
237=cut
238
239sub get_c_field {
240    my ($self, $cfield) = @_;
241    $self->base->check_acl($self, $cfield, 'r') or do {
242        $self->base->log(LA_ERR, "Permission denied to get %s/%s",
243            $self->id, $cfield
244        );
245        return;
246    };
247    return $self->_get_c_field($cfield);
248}
249
250=head2 get_attributes($attr)
251
252Like get_c_field but always return an array
253
254=cut
255
256sub get_attributes {
257    my ($self, $cfield) = @_;
258    my $res = $self->get_c_field($cfield);
259    if ($res) {
260        return(ref $res ? @{$res} : $res);
261    } else {
262        return;
263    }
264}
265
266sub _get_attributes {
267    my ($self, $cfield) = @_;
268    my $res = $self->_get_c_field($cfield);
269    if ($res) {
270        return(ref $res ? @{$res} : ($res));
271    } else {
272        return;
273    }
274}
275
276sub _get_c_field {
277    my ($self, $cfield) = @_;
278    my $attribute = $self->attribute($cfield) or do {
279        $self->base->log(LA_WARN, "Unknow attribute $cfield");
280        return;
281    };
282    $attribute->readable or do {
283        $self->base->log(LA_WARN, "Attribute $cfield is not readable");
284        return;
285    };
286    return $attribute->get; 
287}
288
289=head2 GetAttributeValue($cfield)
290
291Return the value to exposed to other base
292
293=cut
294
295sub GetAttributeValue {
296    my ($self, $cfield) = @_;
297
298    return $self->get_c_field($cfield);
299}
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) : (defined($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(', ', sort @{ $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 $res = $self->set_fields($attribute->iname, $self->base->passCrypt($clear_pass));
547        $self->base->log(LA_NOTICE, 'Mot de passe changé pour %s', $self->id)
548            if($res);
549        return $res;
550    } else {
551        $self->base->log(LA_WARN,
552            "Cannot set password: userPassword attributes is unsupported");
553    }
554}
555
556=head2 check_password ($password)
557
558Check given password is secure using L<Crypt::Cracklib>
559
560=cut
561
562sub check_password {
563    my ( $self, $password ) = @_;
564    my $dictionary = $self->base->config('cracklib_dictionnary');
565
566    if ($password !~ /^[[:ascii:]]*$/) {
567       return "the password must contains ascii characters only";
568    }
569
570    return fascist_check($password, $dictionary);
571}
572
573=head2 InjectCryptPasswd($cryptpasswd)
574
575Inject a password encrypted using standard UNIX method.
576
577=cut
578
579sub InjectCryptPasswd {
580    my ($self, $cryptpasswd) = @_;
581
582    if ($self->can('_InjectCryptPasswd')) {
583        return $self->_InjectCryptPasswd($cryptpasswd);
584    } else {
585        $self->base->log(LA_ERR, 'Injecting unix crypt password is not supported');
586        return;
587    }
588}
589
590=head2 search ($base, @filter)
591
592Search object matching C<@filter>
593
594=cut
595
596sub search {
597    my ($class, $base, @filter) = @_;
598    my @results;
599    my %parsed_filter;
600    while (my $item = shift(@filter)) {
601        # attr=foo => no extra white space !
602        # \W is false, it is possible to have two char
603        my ($attr, $mode, $val) = $item =~ /^(\w+)(?:(\W)(.+))?$/ or next;
604        if (!$mode) {
605            $mode = '~';
606            $val = shift(@filter);
607        }
608        push(
609            @{$parsed_filter{$attr}},
610            {
611                attr => $attr,
612                mode => $mode,
613                val  => $val,
614            }
615        );
616    }
617    foreach my $id ($base->list_objects($class->type)) {
618        my $obj = $base->get_object($class->type, $id);
619        my $match = 1;
620        foreach my $field (keys %parsed_filter) {
621            $base->attribute($class->type, $field) or
622                la_log(LA_WARN, "Unsupported attribute %s", $field);
623            my $tmatch = 0;
624            foreach (@{$parsed_filter{$field}}) {
625                my $value = $_->{val};
626                my $fval = $obj->_get_c_field($field) || '';
627                if ($value eq '*') {
628                    if ($fval ne '') {
629                        $tmatch = 1;
630                        last;
631                    }
632                } elsif ($value eq '!') {
633                    if ($fval eq '') {
634                        $match = 1;
635                        last;
636                    }
637                } elsif ($_->{mode} eq '=') {
638                    if ($fval eq $value) {
639                        $tmatch = 1;
640                        last;
641                    }
642                } elsif($_->{mode} eq '~') {
643                    if ($fval =~ m/\Q$value\E/i) {
644                        $tmatch = 1;
645                        last;
646                    }
647                }
648            }
649            $match = 0 unless($tmatch);
650        }
651        push(@results, $id) if($match);
652    }
653    @results;
654}
655
656=head2 attributes_summary ($base, $attribute)
657
658Return list of values existing in base for C<$attribute>
659
660=cut
661
662sub attributes_summary {
663    my ($class, $base, $attribute) = @_;
664    my $attr = $base->attribute($class->type, $attribute) or do {
665        $base->log(LA_ERR, "Cannot instantiate %s attribute", $attribute);
666        return;
667    };
668    if (!$attr->readable) {
669        $base->log(LA_WARN, l('Attribute %s is not readable', $attribute));
670        return;
671    }
672    if (!$base->check_acl($class->type, $attribute, 'r')) {
673        $base->log(LA_WARN, l('Permission denied to read attribute %s', $attribute));
674        return;
675    }
676    my %values;
677    foreach my $id ($base->list_objects($class->type)) {
678        my $obj = $base->get_object($class->type, $id);
679        my $value = $obj->_get_c_field($attribute);
680        if ($value) {
681            if (ref $value) {
682                foreach (@$value) {
683                    $values{$_} = 1;
684                }
685            } else {
686                $values{$value} = 1;
687            }
688        }
689    }
690    return sort(keys %values);
691}
692
693=head2 attributes_summary_by_object ($base, $attribute)
694
695Return list of peer object <=> values
696
697=cut
698
699sub attributes_summary_by_object {
700    my ($class, $base, $attribute) = @_;
701    my $attr = $base->attribute($class->type, $attribute) or do {
702        $base->log(LA_ERR, "Cannot instantiate %s attribute", $attribute);
703        return;
704    };
705    if (!$attr->readable) {
706        $base->log(LA_WARN, l('Attribute %s is not readable', $attribute));
707        return;
708    }
709    if (!$base->check_acl($class->type, $attribute, 'r')) {
710        $base->log(LA_WARN, l('Permission denied to read attribute %s', $attribute));
711        return;
712    }
713    my %values;
714    foreach my $id ($base->list_objects($class->type)) {
715        my $obj = $base->get_object($class->type, $id);
716        my $value = $obj->_get_c_field($attribute);
717        if ($value) {
718            if (ref $value) {
719                foreach (@$value) {
720                    push(@{ $values{ $id } }, $_);
721                }
722            } else {
723                push(@{ $values{ $id } }, $value);
724            }
725        }
726    }
727    return %values;
728}
729
730=head2 find_next_numeric_id ($base, $field, $min, $max)
731
732Find next free uniq id for attribute C<$field>
733
734=cut
735
736sub find_next_numeric_id {
737    my ($class, $base, $field, $min, $max) = @_;
738    $base->attribute($class->type, $field) or return;
739    $min ||= 
740        $field eq 'uidNumber' ? 500 :
741        $field eq 'gidNumber' ? 500 :
742        1;
743    $max ||= 65635;
744    $base->log(LA_DEBUG, "Trying to find %s in range %d - %d",
745        $field, $min, $max);
746    my %existsid;
747    $base->temp_switch_unexported(sub {
748        foreach ($base->list_objects($class->type)) {
749            my $obj = $base->get_object($class->type, $_) or next;
750            my $id = $obj->_get_c_field($field) or next;
751            $existsid{$id + 0} = 1;
752        }
753    }, 1);
754    $min += 0;
755    $max += 0;
756    for(my $i = $min; $i <= $max; $i++) {
757        $existsid{$i + 0} or do {
758            $base->log(LA_DEBUG, "Next %s found: %d", $field, $i);
759            return $i;
760        };
761    }
762    return;
763}
764
765=head2 text_dump ($handle, $config, $base)
766
767Dump object into C<$handle>
768
769=cut
770
771sub text_dump {
772    my ($self, $handle, $config, $base) = @_;
773    print $handle $self->dump($config, $base);
774    return 1;
775}
776
777=head2 dump
778
779Return dump for tihs object
780
781=cut
782
783sub dump {
784    my ($self, $config, $base) = @_;
785
786    my $otype = $self->type;
787    $base ||= $self->base;
788    my $dump;
789    if (ref $self) {
790        $dump .= sprintf "# base %s: object %s/%s\n",
791            $base->label, $self->type, $self->id;
792    }
793    $dump .= sprintf "# %s\n", scalar(localtime);
794
795    foreach my $attr (sort { $a cmp $b } $base->list_canonical_fields($otype,
796        $config->{only_rw} ? 'rw' : 'r')) {
797        my $oattr = ref $self ? $self->attribute($attr) : $base->attribute($otype, $attr);
798        if ($oattr->hidden) { next; }
799        if (ref $self) {
800            my $val = $self->get_c_field($attr);
801            if ($val || $config->{empty_attr}) {
802                if (my @allowed = $base->obj_attr_allowed_values($otype, $attr)) {
803                    $dump .= sprintf("# %s must be%s: %s\n",
804                        $attr,
805                        ($oattr->mandatory ? '' : ' empty or either'),
806                        join(', ', @allowed)
807                    );
808                }
809                my @vals = ref $val ? @{ $val } : $val;
810                foreach (@vals) {
811                    $_ ||= '';
812                    s/\r?\n/\\n/g;
813                    $dump .= sprintf("%s%s:%s\n", 
814                        $oattr->ro ? '# (ro) ' : '',
815                        $attr, $_ ? " $_" : '');
816                }
817            }
818        } else {
819            if (my @allowed = $base->obj_attr_allowed_values($otype, $attr)) {
820                $dump .= sprintf("# %s must be empty or either: %s\n",
821                    $attr,
822                    join(', ', @allowed)
823                );
824            }
825            $dump .= sprintf("%s%s: %s\n", 
826                $oattr->ro ? '# (ro) ' : '',
827                $attr, '');
828        }
829    }
830    return $dump;
831}
832
833=head2 ReportChange($changetype, $message, @args)
834
835Possible per database way to log changes
836
837=cut
838
839sub ReportChange {
840    my ($self, $changetype, $message, @args) = @_;
841
842    $self->base->ReportChange(
843        $self->type,
844        $self->id,
845        $self->Iid,
846        $changetype, $message, @args
847    )
848}
849
8501;
851
852__END__
853
854
855=head1 SEE ALSO
856
857L<LATMOS::Accounts::Bases>
858
859=head1 AUTHOR
860
861Thauvin Olivier, E<lt>olivier.thauvin.ipsl.fr@localdomainE<gt>
862
863=head1 COPYRIGHT AND LICENSE
864
865Copyright (C) 2009 by Thauvin Olivier
866
867This library is free software; you can redistribute it and/or modify
868it under the same terms as Perl itself, either Perl version 5.10.0 or,
869at your option, any later version of Perl 5 you may have available.
870
871=cut
Note: See TracBrowser for help on using the repository browser.