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

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

Avoid undef warning

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