source: trunk/LATMOS-Accounts/lib/LATMOS/Accounts/Bases/Sql/User.pm @ 2297

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

Fix 1 not treat as true

  • Property svn:keywords set to Id Rev
File size: 84.5 KB
Line 
1package LATMOS::Accounts::Bases::Sql::User;
2
3use 5.010000;
4use strict;
5use warnings;
6use overload '""' => 'stringify';
7
8use LATMOS::Accounts::Utils;
9use LATMOS::Accounts::Log;
10use POSIX qw(strftime);
11use Date::Parse qw(str2time);
12use DateTime;
13use DateTime::TimeZone;
14use DateTime::Format::Pg;
15use base qw(LATMOS::Accounts::Bases::Sql::objects);
16use LATMOS::Accounts::I18N;
17use Date::Calc;
18use LATMOS::Accounts::Mail;
19
20our $VERSION = (q$Rev: 2158 $ =~ /^Rev: (\d+) /)[0];
21
22=head1 NAME
23
24LATMOS::Ad - Perl extension for blah blah blah
25
26=head1 DESCRIPTION
27
28Account base access over standard unix file format.
29
30=head1 FUNCTIONS
31
32=cut
33
34=head2 new(%config)
35
36Create a new LATMOS::Ad object for windows AD $domain.
37
38domain / server: either the Ad domain or directly the server
39
40ldap_args is an optionnal list of arguments to pass to L<Net::LDAP>.
41
42=cut
43
44sub _object_table { 'user' }
45
46sub _key_field { 'name' }
47
48sub _has_extended_attributes { 1 }
49
50sub stringify {
51    my ($self) = @_;
52
53    return join(' ', grep { $_ }
54        (
55            $self->get_field('givenName'),
56            $self->get_field('sn')
57        )
58    )
59    || $self->get_field('description')
60    || $self->id;
61}
62
63sub GetOtypeDef {
64    my ($class) = @_;
65
66    {
67        address => 'user',
68        employment => 'user',
69        nethost => [ 'owner', 'user' ],
70    },
71}
72
73sub _get_attr_schema {
74    my ($class, $base) = @_;
75
76    my $subsetaddress = sub {
77        my ($self, $data) = @_;
78        my $fmainaddress = $self->object->_get_c_field('mainaddress');
79
80        # set address attribute => create address object on the fly
81        # except if attr is empty !
82        if (!$fmainaddress && $data) {
83            $fmainaddress = $self->object->id . '-' . join('', map { ('a'..'z')[rand(26)] }
84                (0..4));
85            $self->base->_create_c_object(
86                'address', $fmainaddress,
87                user => $self->object->id,
88                isMainAddress => 1, ) or do {
89                $self->base->log(LA_ERR,
90                    "Cannot create main address for user %s", $self->object->id);
91                return;
92            };
93        }
94        if ($fmainaddress && 
95            (my $address = $self->base->get_object('address', $fmainaddress))) {
96            if ($address->attribute($self->name) &&
97                !$address->attribute($self->name)->ro) {
98                return $address->set_c_fields($self->name => $data) ||0;
99            }
100        }
101    };
102
103    my $attrs = {
104            exported => {
105                post => sub {
106                    my ($self, $value) = @_;
107                    my $attr = $self->name;
108
109                    if (my $obj = $self->base->
110                            get_object('revaliases', $self->object->id)) {
111                        my $ares = $obj->set_c_fields(
112                            ($attr eq 'exported' ? 'exported' : 'unexported') => $value
113                        );
114                        if (!defined($ares)) {
115                            $self->base->log(LA_ERR,
116                                'Cannot set revaliases exported attribute for user %s',
117                                $self->object->id);
118                        }
119                    }
120                    my $must_expire = $self->name eq 'exported'
121                        ? ($value ? 0 : 1 )
122                        : ($value ? 1 : 0 );
123
124                    foreach my $al (grep { $_ } $self->object->get_attributes('aliases'), $self->object->id) {
125                        my $obj = $self->base->get_object('aliases', $al) or next;
126                        $obj->_set_c_fields(
127                            exported => $value,
128                        );
129                    }
130                    foreach my $al ($self->object->get_attributes('_otheraddress')) {
131                        my $obj = $self->base->get_object('address', $al) or next;
132                        $obj->_set_c_fields(
133                            exported => $value,
134                        );
135                    }
136                },
137            },
138            uidNumber => {
139                inline => 1,
140                iname => 'uidnumber',
141                uniq => 1,
142                mandatory => 1,
143                formopts => { length => 7 },
144                label => l('UID'),
145            },
146            uidnumber => { inline => 1, hide => 1, monitored => 1 },
147            gidNumber => {
148                inline => 1,
149                iname => 'gidnumber',
150                mandatory => 1,
151                can_values => sub {
152                    map { $_->id, $_->get_attributes('gidNumber') }
153                    map { $base->get_object('group', $_) }
154                    $base->list_objects('group')
155                },
156                can_values => sub {
157                    my $sth = $base->db->prepare_cached(
158                        q{
159                        select name, gidnumber from "group" where exported = true
160                        }
161                    );
162                    $sth->execute();
163                    my @res;
164                    while (my $res = $sth->fetchrow_hashref) {
165                        push(@res, $res->{name});
166                        push(@res, $res->{gidnumber});
167                    }
168                    return @res;
169                },
170                display => sub {
171                    my ($self, $val) = @_;
172                    if ($val =~ /^\d+$/) {
173                        my ($gr) = $self->base->search_objects('group', "gidNumber=$val")
174                            or return;
175                        return $gr;
176                    } else {
177                        my ($gr) = $self->base->search_objects('group', "name=$val")
178                            or return;
179                        return $gr;
180                    }
181                },
182                input => sub {
183                    my ($val) = @_;
184                    $val =~ /^\d+$/ and return $val;
185                    my ($gr) = $base->search_objects('group', "name=$val") or return;
186                    return $base->get_object('group', $gr)->get_attributes('gidNumber');
187                },
188                #reference => 'group',
189                label => l('GID'),
190            },
191            loginShell => {
192                mandatory => 1,
193                label => l('Shell'),
194            },
195            gidnumber => { inline => 1, hide => 1,
196                can_values => sub {
197                    map { $_->id, $_->get_attributes('gidNumber') }
198                    map { $base->get_object('group', $_) }
199                    $base->list_objects('group')
200                },
201                display => sub {
202                    my ($self, $val) = @_;
203                    my ($gr) = $self->base->search_objects('group', "gidNumber=$val")
204                        or return;
205                    return $gr;
206                },
207                input => sub {
208                    my ($val) = @_;
209                    $val =~ /^\d+$/ and return $val;
210                    my ($gr) = $base->search_objects('group', "name=$val") or return;
211                    return $base->get_object('group', $gr)->get_attributes('gidNumber');
212                },
213                mandatory => 1,
214                reference => 'group',
215                monitored => 1,
216            },
217            locked    => {
218                formtype => 'CHECKBOX',
219                formopts => { rawvalue => 1, },
220                monitored => 1,
221                label => l('Locked'),
222            },
223            expire        => {
224                inline => 1,
225                formtype => 'DATETIME',
226                monitored => 1,
227                label => l('Expire on'),
228            },
229            endcircuit    => {
230                inline => 1,
231                formtype => 'DATE',
232                monitored => 1,
233                label => l('End of entrance'),
234            },
235            lastlogin    => {
236                inline => 1,
237                formtype => 'DATETIME',
238                monitored => 1,
239                label => l('Last login'),
240                set => sub {
241                    my ($self, $values) = @_;
242                    if ($values) {
243                        my $sth = $base->db->prepare_cached(
244                            q{ update "user" set lastlogin = $1 where (lastlogin < $1 or lastlogin IS NULL) and name = $2 }
245                        );
246                        return $sth->execute($values, $self->object->id);
247                    } else {
248                        my $sth = $base->db->prepare_cached(
249                            q{ update "user" set lastlogin = NULL where name = $2 }
250                        );
251                        return $sth->execute($self->object->id);
252                    }
253                },
254            },
255            _endEmployment => {
256                formtype => 'DATETIME',
257                managed => 1,
258                ro => 1,
259                hide => 1,
260                get => sub {
261                    my ($attr) = @_;
262                    my $self = $attr->object;
263                    $self->_computeEndEmployment($self->base->config('employment_delay') || 0);
264                },
265                label => l('End of employment'),
266            },
267            endEmployment => {
268                formtype => 'DATETIME',
269                ro => 1,
270                label => l('End of employment'),
271            },
272            _departure => {
273                formtype => 'DATETIME',
274                managed => 1,
275                ro => 1,
276                hide => 1,
277                get => sub {
278                    my ($attr) = @_;
279                    my $self = $attr->object;
280                    $self->_computeEndEmployment($self->base->config('employment_delay') || 0, 1, 1);
281                },
282                label => l('Start of employment'),
283            },
284            departure => {
285                formtype => 'DATETIME',
286                ro => 1,
287                label => l('Leaving'),
288            },
289            _endStrictEmployment => {
290                formtype => 'DATETIME',
291                managed => 1,
292                ro => 1,
293                hide => 1,
294                get => sub {
295                    my ($attr) = @_;
296                    my $self = $attr->object;
297                    $self->_computeEndEmployment();
298                },
299            },
300            endStrictEmployment => {
301                formtype => 'DATETIME',
302                ro => 1,
303            },
304            _endCurrentEmployment => {
305                formtype => 'DATETIME',
306                managed => 1,
307                ro => 1,
308                hide => 1,
309                get => sub {
310                    my ($attr) = @_;
311                    my $self = $attr->object;
312
313                    my $list_empl = $self->base->db->prepare_cached(q{
314                        SELECT * FROM employment WHERE "user" = ? and
315                            firstday <= now() and
316                            (lastday is null or lastday >= now() - '1 days'::interval)
317                            order by firstday asc
318                    });
319                    $list_empl->execute($self->id);
320                    my $end;
321                    while (my $res = $list_empl->fetchrow_hashref) {
322                        if (!$res->{lastday}) {
323                            # Ultimate employment.
324                            $list_empl->finish;
325                            return undef;
326                        } else {
327                            $end = DateTime->from_epoch(epoch => str2time($res->{lastday}));
328                            $end->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
329                            $end->add(hours => 23, minutes => 59, seconds => 59);
330                        }
331                        last;
332                    }
333                    $list_empl->finish;
334
335                    return $end ? $end->iso8601 : undef
336                },
337            },
338            endCurrentEmployment => {
339                formtype => 'DATETIME',
340                ro => 1,
341            },
342            _endLastEmployment => {
343                formtype => 'DATETIME',
344                managed => 1,
345                ro => 1,
346                hide => 1,
347                get => sub {
348                    my ($attr) = @_;
349                    my $self = $attr->object;
350
351                    my $list_empl = $self->base->db->prepare_cached(q{
352                        SELECT * FROM employment WHERE "user" = ?
353                        order by lastday desc nulls first
354                    });
355                    $list_empl->execute($self->id);
356                    my $res = $list_empl->fetchrow_hashref;
357                    $list_empl->finish;
358                    my $end;
359                    if ($res && $res->{lastday}) {
360                        $end = DateTime->from_epoch(epoch => str2time($res->{lastday}));
361                        $end->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
362                        $end->add(hours => 23, minutes => 59, seconds => 59);
363                    }
364                    return $end ? $end->iso8601 : undef
365                },
366                label => l('End of any employment'),
367            },
368            endLastEmployment => {
369                formtype => 'DATETIME',
370                ro => 1,
371                label => l('End of any employment'),
372            },
373            _startEmployment => {
374                formtype => 'DATETIME',
375                managed => 1,
376                ro => 1,
377                hide => 1,
378                get => sub {
379                    my ($attr) = @_;
380                    my $self = $attr->object;
381                    $self->_computeStartEmployment($self->base->config('employment_delay') || 0);
382                },
383                label => l('Start of employment'),
384            },
385            startEmployment => {
386                formtype => 'DATETIME',
387                ro => 1,
388                label => l('Start of employment'),
389            },
390            _arrival => {
391                formtype => 'DATETIME',
392                managed => 1,
393                ro => 1,
394                hide => 1,
395                get => sub {
396                    my ($attr) = @_;
397                    my $self = $attr->object;
398                    $self->_computeStartEmployment($self->base->config('employment_delay') || 0, 1, 1);
399                },
400                label => l('Start of employment'),
401            },
402            arrival => {
403                formtype => 'DATETIME',
404                ro => 1,
405                label => l('Arrival'),
406            },           
407            _startStrictEmployment => {
408                formtype => 'DATETIME',
409                managed => 1,
410                ro => 1,
411                hide => 1,
412                get => sub {
413                    my ($attr) = @_;
414                    my $self = $attr->object;
415                    $self->_computeStartEmployment();
416                },
417            },
418            startStrictEmployment => {
419                formtype => 'DATETIME',
420                ro => 1,
421            },
422            _startCurrentEmployment => {
423                formtype => 'DATETIME',
424                managed => 1,
425                ro => 1,
426                hide => 1,
427                get => sub {
428                    my ($attr) = @_;
429                    my $self = $attr->object;
430
431                    my $list_empl = $self->base->db->prepare_cached(q{
432                        SELECT * FROM employment WHERE "user" = ? and
433                            firstday <= now() and
434                            (lastday is null or lastday >= now() - '1 days'::interval)
435                            order by firstday asc
436                    });
437                    $list_empl->execute($self->id);
438                    my $start;
439                    while (my $res = $list_empl->fetchrow_hashref) {
440                        $start = DateTime->from_epoch(epoch => str2time($res->{firstday}));
441                        $start->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
442                        last;
443                    }
444                    $list_empl->finish;
445
446                    return $start ? $start->iso8601 : undef
447                },
448            },
449            startCurrentEmployment => {
450                formtype => 'DATETIME',
451                ro => 1,
452            },
453            _startFirstEmployment => {
454                formtype => 'DATETIME',
455                managed => 1,
456                ro => 1,
457                hide => 1,
458                get => sub {
459                    my ($attr) = @_;
460                    my $self = $attr->object;
461
462                    my $list_empl = $self->base->db->prepare_cached(q{
463                        SELECT * FROM employment WHERE "user" = ?
464                        order by firstday asc
465                    });
466                    $list_empl->execute($self->id);
467                    my $res = $list_empl->fetchrow_hashref;
468                    $list_empl->finish;
469                    my $start;
470                    if ($res && $res->{firstday}) {
471                        $start = DateTime->from_epoch(epoch => str2time($res->{firstday}));
472                        $start->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
473                    }
474                    return $start ? $start->iso8601 : undef
475                },
476                label => l('Start of any employment'),
477            },
478            startFirstEmployment => {
479                formtype => 'DATETIME',
480                ro => 1,
481                label => l('Start of any employment'),
482            },
483            employmentLength => {
484                ro => 1,
485                auto => 1,
486            },
487            _employmentLength => {
488                ro => 1,
489                managed => 1,
490                hide => 1,
491                get => sub {
492                    my ($self) = @_;
493                    my $lastday = $self->object->get_attributes('endEmployment') || DateTime->now->ymd('-');
494                    my $firstday = $self->object->get_attributes('startEmployment') or return;
495
496                    my @fd = split('-', DateTime->from_epoch(epoch => str2time($firstday))->ymd('-'));
497                    my @ld = split('-', DateTime->from_epoch(epoch => str2time($lastday))->ymd('-'));
498
499                    return Date::Calc::Delta_Days(@fd, @ld) +1;
500                },
501                label => l('Work duration'),
502            },
503            employmentLengthText => {
504                ro => 1,
505                auto => 1,
506            },
507            _employmentLengthText => {
508                ro => 1,
509                managed => 1,
510                hide => 1,
511                get => sub {
512                    my ($self) = @_;
513                    my $firstday = $self->object->get_attributes('startEmployment') or return;
514                    my $lastday = $self->object->get_attributes('endEmployment')|| DateTime->now->ymd('-');
515                    {
516                        my $dtlast = DateTime->from_epoch(epoch => str2time($lastday));
517                        $dtlast->add(days => 1);
518                        $lastday = $dtlast->ymd('-');
519                    }
520
521                    my @fd = split('-', DateTime->from_epoch(epoch => str2time($firstday))->ymd('-'));
522                    my @ld = split('-', DateTime->from_epoch(epoch => str2time($lastday))->ymd('-'));
523
524                    my ($Dy,$Dm,$Dd) = Date::Calc::N_Delta_YMD(@fd, @ld);
525                    return join(', ',
526                        ($Dy ? l('%d years', $Dy)  : ()),
527                        ($Dm ? l('%d months', $Dm) : ()),
528                        ($Dd ? l('%d days', $Dd)   : ()),
529                    );
530                },
531                label => l('Work duration'),
532            },
533            cn        => {
534                inline => 1, ro => 1,
535                get => sub {
536                    my ($self) = @_;
537                    return join(' ', grep { $_ } 
538                        (
539                            $self->object->_get_c_field('givenName'),
540                            $self->object->_get_c_field('sn')
541                        )
542                    )
543                    || $self->object->_get_c_field('description')
544                    || $self->object->id;
545                },
546            },
547            memberOf  => {
548                reference => 'group',
549                multiple => 1, delayed => 1,
550                get => sub {
551                    my ($self) = @_;
552                    my $obj = $self->object;
553                    my $sth = $obj->db->prepare_cached(
554                        q{
555                        select name from "group" join
556                        group_attributes on group_attributes.okey = "group".ikey
557                        where value = ? and attr = ? and internobject = false
558                        } . ($self->base->{wexported} ? '' : ' and "group".exported = true')
559                    );
560                    $sth->execute($obj->id, 'memberUID');
561                    my @res;
562                    while (my $res = $sth->fetchrow_hashref) {
563                        push(@res, $res->{name});
564                    }
565                    return \@res;
566                },
567                set => sub {
568                    my ($self, $values) = @_;
569                    my %old = map { $_ => 'o' } @{ $self->get };
570                    foreach my $group (grep { $_ } ref $values ? @{ $values } : $values) {
571                        if ($old{$group}) {
572                            $old{$group} = undef; # no change
573                        } else {
574                            $old{$group} = 'n';
575                        }
576                    }
577
578                    my $res = 0;
579                    foreach my $group (keys %old) {
580                        $old{$group} or next; # no change
581
582                        my $ogroup = $self->base->get_object('group', $group) or next;
583                        ($ogroup->_get_c_field('sutype') || '') =~ /^(jobtype|contrattype)$/ and next;
584
585                        if ($old{$group} eq 'n') {
586                            $res += $ogroup->_addAttributeValue('memberUID', $self->object->id);
587                        } else {
588                            if (($self->object->_get_c_field('department') || '') eq $ogroup->id) {
589                                $self->base->log(LA_WARN,
590                                    "Don't removing user %s from group %s: is its department",
591                                    $self->object->id, $ogroup->id);
592                                next;
593                            }
594                            $res += $ogroup->_delAttributeValue('memberUID', $self->object->id);
595                        }
596                    }
597                    return $res;
598                },
599                label => l('Member of'),
600            },
601            forward => {
602                managed => 1,
603                multiple => 1,
604                get => sub {
605                    my ($self) = @_;
606                    my $sth = $self->base->db->prepare(q{
607                        select forward from aliases where name = ? and internobject = false
608                        } . ($self->base->{wexported} ? '' : ' and exported = true'));
609                    $sth->execute($self->object->id);
610                    my $res = $sth->fetchrow_hashref;
611                    $sth->finish;
612                    return $res->{forward}
613                },
614                set => sub {
615                    my ($self, $data) = @_;
616                    if ($data) {
617                        my @datas = ref $data ? @$data : split(/\s*,\s*/, $data);
618                        if (my $f = $self->base->get_object('aliases', $self->object->id)) {
619                            return $f->_set_c_fields(
620                                forward => \@datas,
621                                comment => undef,
622                                description => 'Forward for user ' . $self->object->id,
623                            );
624                        } else {
625                            if ($self->base->_create_c_object(
626                                    'aliases', $self->object->id,
627                                    forward => \@datas,
628                                    description => 'automatically created for ' . $self->object->id,
629                                )) {
630                                return 1;
631                            } else {
632                                $self->base->log(LA_ERR, "Cannot add forward for %s",
633                                    $self->object->id);
634                            }
635                        }
636                    } elsif ($self->base->get_object('aliases', $self->object->id)) {
637                        if (my $res = $self->base->_delete_object('aliases', $self->object->id)) {
638                            return $res;
639                        } else {
640                            $self->base->log(LA_ERR, "Cannot remove forward for %s",
641                                $self->object->id);
642                        }
643                    } else {
644                        return 1;
645                    }
646                    return;
647                },
648                label => l('Forward'),
649            },
650            aliases   => {
651                #reference => 'aliases',
652                delayed => 1,
653                formtype => 'TEXT',
654                multiple => 1,
655                get => sub {
656                    my ($self) = @_;
657                    my $sth = $self->base->db->prepare(q{
658                        select name from aliases where internobject = false and lower($1) =
659                        lower(array_to_string("forward", ','))
660                        } . ($self->base->{wexported} ? '' : 'and exported = true'));
661                    $sth->execute($self->object->id);
662                    my @values;
663                    while (my $res = $sth->fetchrow_hashref) {
664                        push(@values, $res->{name});
665                    }
666                    return \@values;
667                },
668                set => sub {
669                    my ($self, $data) = @_;
670
671                    my $res = 0;
672                    my %aliases = map { $_ => 1 } grep { $_ } (ref $data ? @{$data} : $data);
673                    foreach ($self->object->_get_attributes('aliases')) {
674                        $aliases{$_} ||= 0;
675                        $aliases{$_} +=2;
676                    }
677                    foreach (keys %aliases) {
678                        if ($aliases{$_} == 2) {
679                            if ($self->base->_delete_object('aliases', $_)) {
680                                $res++
681                            } else {
682                                $self->base->log(LA_ERR,
683                                    "Cannot remove aliases %s from user %s", $_,
684                                    $self->object->id);
685                            }
686                        } elsif ($aliases{$_} == 1) {
687                            if ($self->base->_create_c_object(
688                                    'aliases', $_,
689                                    forward => [ $self->object->id ],
690                                    description => 'automatically created for ' . $self->object->id,
691                                )) {
692                                $res++
693                            } else {
694                                $self->base->log(LA_ERR, 'Cannot set forward %s to user %s',
695                                    $_, $self->object->id);
696                                return;
697                            }
698                        } # 3 no change
699                    }
700                    $res
701                },
702                label => l('Aliases'),
703            },
704            revaliases => {
705                formtype => 'TEXT',
706                get => sub {
707                    my ($self) = @_;
708
709                    if (my $obj = $self->base->
710                        get_object('revaliases', $self->object->id)) {
711                        return $obj->get_attributes('as');
712                    } else {
713                        return;
714                    }
715                },
716                set => sub {
717                    my ($self, $data) = @_;
718               
719                    my $res = 0;
720                    if ($data) {
721                        if (my $obj = $self->base->
722                            get_object('revaliases', $self->object->id)) {
723                            my $ares = $obj->set_c_fields(
724                                'as' => $data,
725                                'exported' => ($self->object->get_attributes('exported') || 0),
726                            );
727                            if (defined($ares)) {
728                                $res+=$ares;
729                            } else {
730                                $self->base->log(LA_ERR, 'Cannot set revaliases for user %s',
731                                    $self->object->id);
732                            }
733                        } else {
734                            if ($self->base->_create_c_object(
735                                    'revaliases',
736                                    $self->object->id, as => $data,
737                                    'exported' => ($self->object->get_attributes('exported') || 0),
738                                    description => 'automatically created for ' . $self->object->id,
739                                )) {
740                                $res++;
741                            } else {
742                                $self->base->log(LA_ERR, 'Cannot set revaliases for user %s',
743                                    $self->object->id);
744                            }
745                        }
746                    } else {
747                        $self->base->_delete_object('revaliases', $self->object->id);
748                        $res++;
749                    }
750
751                    $res
752                },
753            },
754            manager => {
755                reference => 'user',
756                ro => 1,
757                get => sub {
758                    my ($self) = @_;
759                    if (my $manager = $self->object->_get_c_field('managerContact')) {
760                        return $manager;
761                    } elsif (my $department = $self->object->_get_c_field('department')) {
762                        my $obj = $self->base->get_object('group', $department);
763                        return $obj->_get_c_field('managedBy');
764                    } else {
765                        return;
766                    }
767                },
768                label => l('Responsible'),
769            },
770            department => {
771                reference => 'group',
772                can_values => sub {
773                    $base->search_objects('group', 'sutype=dpmt')
774                },
775                monitored => 1,
776                label => l('Department'),
777            },
778            contratType => {
779                reference => 'group',
780                can_values => sub {
781                    $base->search_objects('group', 'sutype=contrattype')
782                },
783                monitored => 1,
784                label => l('Type of contract'),
785            },
786            site => {
787                reference => 'site',
788                can_values => sub {
789                    $base->search_objects('site')
790                },
791                get => sub {
792                    my ($self) = @_;
793                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
794                        $self->base->get_object('address', $fmainaddress)
795                            ->_get_c_field($self->name);
796                    } else {
797                        return;
798                    }
799                },
800                set => $subsetaddress,
801                label => l('Site'),
802            },
803            co => {
804                get => sub {
805                    my ($self) = @_;
806                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
807                        $self->base->get_object('address', $fmainaddress)
808                            ->_get_c_field($self->name);
809                    } else {
810                        return;
811                    }
812                },
813                set => $subsetaddress,
814            },
815            l => {
816                get => sub {
817                    my ($self) = @_;
818                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
819                        $self->base->get_object('address', $fmainaddress)
820                            ->_get_c_field($self->name);
821                    } else {
822                        return;
823                    }
824                },
825                set => $subsetaddress,
826                label => l('City'),
827            },
828            postalCode => {
829                get => sub {
830                    my ($self) = @_;
831                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
832                        $self->base->get_object('address', $fmainaddress)
833                            ->_get_c_field($self->name);
834                    } else {
835                        return;
836                    }
837                },
838                set => $subsetaddress,
839                label => l('Postal code'),
840            },
841            streetAddress => {
842                formtype => 'TEXTAREA',
843                get => sub {
844                    my ($self) = @_;
845                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
846                        $self->base->get_object('address', $fmainaddress)
847                            ->_get_c_field($self->name);
848                    } else {
849                        return;
850                    }
851                },
852                set => $subsetaddress,
853                label => l('Street'),
854            },
855            postOfficeBox => {
856                get => sub {
857                    my ($self) = @_;
858                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
859                        $self->base->get_object('address', $fmainaddress)
860                            ->_get_c_field($self->name);
861                    } else {
862                        return;
863                    }
864                },
865                set => $subsetaddress,
866                label => l('Post office box'),
867            },
868            st => {
869                get => sub {
870                    my ($self) = @_;
871                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
872                        $self->base->get_object('address', $fmainaddress)
873                            ->_get_c_field($self->name);
874                    } else {
875                        return;
876                    }
877                },
878                set => $subsetaddress,
879            },
880            facsimileTelephoneNumber => {
881                get => sub {
882                    my ($self) = @_;
883                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
884                        $self->base->get_object('address', $fmainaddress)
885                            ->_get_c_field($self->name);
886                    } else {
887                        return;
888                    }
889                },
890                set => $subsetaddress,
891                label => l('Fax number'),
892            },
893            o => {
894                ro => 1,
895                iname => 'company',
896                label => l('Company'),
897            },
898            ou => {
899                iname => 'department',
900                ro => 1,
901                label => l('Department'),
902            },
903            telephoneNumber => {
904                get => sub {
905                    my ($self) = @_;
906                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
907                        $self->base->get_object('address', $fmainaddress)
908                            ->_get_c_field($self->name);
909                    } else {
910                        return;
911                    }
912                },
913                set => $subsetaddress,
914                label => l('Phone number'),
915            },
916            physicalDeliveryOfficeName => {
917                get => sub {
918                    my ($self) = @_;
919                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
920                        $self->base->get_object('address', $fmainaddress)
921                            ->_get_c_field($self->name);
922                    } else {
923                        return;
924                    }
925                },
926                set => $subsetaddress,
927                label => l('Office'),
928            },
929            uid => {
930                iname => 'name',
931                ro => 1,
932                label => l('Login'),
933            },
934            cn =>  { iname => 'name', ro => 1 },
935            gecos => {
936                ro => 1,
937                auto => 1,
938            },
939            _gecos => {
940                managed => 1,
941                hide => 1,
942                ro => 1,
943                get => sub {
944                    my ($self) = @_;
945                    my $obj = $self->object;
946
947                    my $fmt = $self->base->config('gecosformat') ||
948                        '%{_displayName},%{l}-%{physicalDeliveryOfficeName},%{telephoneNumber},%{?endcircuit:%{endcircuit}}%{?!endcircuit:%{expireText}}';
949                    my $gecos = $obj->queryformat($fmt);
950                    return to_ascii($gecos);
951                },
952                label => l('GECOS'),
953            },
954            displayName => {
955                ro => 1,
956                auto => 1,
957            },
958            _displayName  => {
959                ro => 1, managed => 1,
960                hide => 1,
961                get => sub {
962                    my ($self) = @_;
963                    return join(' ', grep { $_ } 
964                        (
965                            $self->object->_get_c_field('givenName'),
966                            $self->object->_get_c_field('sn')
967                        )
968                    )
969                    || $self->object->_get_c_field('description')
970                    || $self->object->id;
971                },
972                label => l('Name'),
973            },
974            sAMAccountName => {
975                auto => 1,
976            },
977            _sAMAccountName  => {
978                ro => 1,
979                hide => 1,
980                managed => 1,
981                iname => 'name',
982                get => sub {
983                    my ($self) = @_;
984                    substr($self->object->id, 0, 19)
985                },
986            },
987            accountExpires => {
988                ro => 1,
989                auto => 1,
990            },
991            _accountExpires => {
992                ro => 1,
993                managed => 1,
994                hide => 1,
995                get => sub {
996                    my ($self) = @_;
997                    my $obj = $self->object;
998                    my $sth = $obj->db->prepare_cached(
999                        sprintf(
1000                            q{select extract(epoch from %s) + 11644474161 as expire
1001                            from %s where %s = ?},
1002                            $base->config('endCircuitdontExpire') ? 'expire' : 'COALESCE(endcircuit,  expire)',
1003                            $obj->db->quote_identifier($obj->_object_table),
1004                            $obj->db->quote_identifier($obj->_key_field),
1005                        )
1006                    );
1007                    $sth->execute($obj->id);
1008                    my $res = $sth->fetchrow_hashref;
1009                    $sth->finish;
1010                    return $res->{expire} ? sprintf("%.f", $res->{expire} * 1E7) : '9223372036854775807';
1011                }
1012            },
1013            shadowExpire => {
1014                ro => 1,
1015                auto => 1,
1016            },
1017            _shadowExpire => {
1018                ro => 1,
1019                hide => 1,
1020                managed => 1,
1021                get => sub {
1022                    my ($self) = @_;
1023                    my $obj = $self->object;
1024                    my $sth = $obj->db->prepare_cached(
1025                        sprintf(
1026                            q{select justify_hours(%s - '1/1/1970'::timestamp) as expire
1027                            from %s where %s = ?},
1028                            $base->config('endCircuitdontExpire') ? 'expire' : 'COALESCE(endcircuit,  expire)',
1029                            $obj->db->quote_identifier($obj->_object_table),
1030                            $obj->db->quote_identifier($obj->_key_field),
1031                        )
1032                    );
1033                    $sth->execute($obj->id);
1034                    my $res = $sth->fetchrow_hashref;
1035                    $sth->finish;
1036                    return -1 unless($res->{expire});
1037                    $res->{expire} =~ /(\d+) days\s*(\w)?/;
1038                    # Add one day is time is not 00H00
1039                    return $1 + ($2 ? 1 : 0);
1040                }
1041            },
1042            directReports => {
1043                auto => 1,
1044                ro => 1,
1045                multiple => 1,
1046            },
1047            _directReports => {
1048                reference => 'user',
1049                multiple => 1,
1050                ro => 1,
1051                hide => 1,
1052                delayed => 1,
1053                get => sub {
1054                    my ($self) = @_;
1055                    my $obj = $self->object;
1056                    my $sth = $obj->db->prepare_cached(
1057                        q{
1058                        SELECT
1059                        "user".name FROM
1060                        public."user",
1061                        public.user_attributes_groups,
1062                        public.group_attributes_users,
1063                        public.group_attributes_base gb,
1064                        public."group"
1065                        WHERE
1066                        "user".ikey = user_attributes_groups.okey AND
1067                        user_attributes_groups.value = "group".name AND
1068                        group_attributes_users.okey = gb.okey AND
1069                        "group".ikey = group_attributes_users.okey AND
1070                        gb.attr = 'sutype' AND
1071                        gb.value = 'dpmt' AND
1072                        group_attributes_users.attr = 'managedBy' AND
1073                        group_attributes_users.value = ?
1074                        } . ($self->base->{wexported} ? '' : ' and "user".exported = true') . q{
1075                            and "user".ikey not in
1076                        (select okey from user_attributes_users
1077                        where attr = 'manager' and value != ? )
1078                        union
1079                        select "user".name FROM public."user",
1080                        user_attributes_users where
1081                        user_attributes_users.attr = 'manager' and user_attributes_users.value = ?
1082                            and "user".ikey = user_attributes_users.okey
1083                        } . ($self->base->{wexported} ? '' : ' and "user".exported = true')
1084                    );
1085                    $sth->execute($obj->id, $obj->id, $obj->id);
1086                    my @res;
1087                    while (my $res = $sth->fetchrow_hashref) {
1088                        push(@res, $res->{name});
1089                    }
1090                    return \@res;
1091                },
1092            },
1093            managedObjects => { ro => 1, reference => 'group', },
1094            otheraddress => {
1095                auto => 1,
1096                multiple => 1,
1097                reference => 'address',
1098            },
1099            _otheraddress => {
1100                ro => 1,
1101                multiple => 1,
1102                reference => 'address',
1103                get => sub {
1104                    my ($self) = @_;
1105                    my $sth = $self->base->db->prepare_cached(q{
1106                        select name from address left join address_attributes
1107                        on address.ikey = address_attributes.okey and
1108                        address_attributes.attr = 'isMainAddress'
1109                        where "user" = ?
1110                        } . ($self->base->{wexported} ? '' : ' and "address".exported = true') . q{
1111                        order by address_attributes.attr
1112                        } );
1113                    $sth->execute($self->object->id);
1114                    my @values;
1115                    while (my $res = $sth->fetchrow_hashref) {
1116                        push(@values, $res->{name});
1117                    }
1118                    return \@values;
1119                },
1120            },
1121            mainaddress => {
1122                auto => 1,
1123                reference => 'address',
1124            },
1125            _mainaddress => {
1126                hide => 1,
1127                ro => 1,
1128                reference => 'address',
1129                get => sub {
1130                    my ($self) = @_;
1131                    my $sth = $self->base->db->prepare_cached(q{
1132                        select name from address join address_attributes on ikey = okey
1133                        where "user" = ? and attr = 'isMainAddress'
1134                        } . ($self->base->{wexported} ? '' : ' and "address".exported = true'));
1135                    $sth->execute($self->object->id);
1136                    my $res = $sth->fetchrow_hashref;
1137                    $sth->finish;
1138                    return $res->{name};
1139                },
1140            },
1141            postalAddress => {
1142                auto => 1,
1143            },
1144            _postalAddress => {
1145                hide => 1,
1146                ro => 1,
1147                get => sub {
1148                    my ($self) = @_;
1149                    if (my $fmainaddress = $self->object->_get_c_field('_mainaddress')) {
1150                        $self->base->get_object('address', $fmainaddress)
1151                            ->_get_c_field('postalAddress');
1152                    } else {
1153                        return;
1154                    }
1155                },
1156                label => l('Postal Address'),
1157            },
1158            facsimileTelephoneNumber => {
1159                ro => 1,
1160                label => l('Fax number'),
1161            },
1162            allsite   => {
1163                ro => 1,
1164                reference => 'site',
1165            },
1166            managerContact => {
1167                delayed => 1,
1168                can_values => sub {
1169                    my %uniq = map { $_ => 1 } grep { $_ }
1170                    (($_[1] ? $_[1]->get_attributes('managerContact') : ()),
1171                    $base->search_objects('user', 'active=1'));
1172                    sort keys %uniq;
1173                },
1174                reference => 'user',
1175                monitored => 1,
1176                iname => 'manager',
1177                label => l('Manager'),
1178            },
1179            expireTextEC => {
1180                ro => 1,
1181                auto => 1,
1182            },
1183            _expireTextEC => {
1184                ro => 1,
1185                managed => 1,
1186                hide => 1,
1187                get => sub {
1188                    my ($self) = @_;
1189                    my $obj = $self->object;
1190                    my $sth = $obj->db->prepare_cached(
1191                        sprintf(
1192                            q{select to_char(%s, 'YYYY/MM/DD') as expire
1193                            from %s where %s = ?},
1194                            $base->config('endCircuitdontExpire') ? 'expire' : 'COALESCE(endcircuit,  expire)',
1195                            $obj->db->quote_identifier($obj->_object_table),
1196                            $obj->db->quote_identifier($obj->_key_field),
1197                        )
1198                    );
1199                    $sth->execute($obj->id) or $obj->db->rollback;
1200                    my $res = $sth->fetchrow_hashref;
1201                    $sth->finish;
1202                    return $res->{expire}
1203                },
1204            },
1205            expireText => {
1206                ro => 1,
1207                auto => 1,
1208            },
1209            _expireText => {
1210                ro => 1,
1211                hide => 1,
1212                managed => 1,
1213                get => sub {
1214                    my ($self) = @_;
1215                    my $obj = $self->object;
1216                    my $sth = $obj->db->prepare_cached(
1217                        sprintf(
1218                            q{select to_char(expire, 'YYYY/MM/DD') as expire
1219                            from %s where %s = ?},
1220                            $obj->db->quote_identifier($obj->_object_table),
1221                            $obj->db->quote_identifier($obj->_key_field),
1222                        )
1223                    );
1224                    $sth->execute($obj->id) or $obj->db->rollback;
1225                    my $res = $sth->fetchrow_hashref;
1226                    $sth->finish;
1227                    return $res->{expire}
1228                },
1229            },
1230            krb5ValidEnd => {
1231                ro => 1,
1232                auto => 1,
1233            },
1234            _krb5ValidEnd => {
1235                ro => 1,
1236                managed => 1,
1237                hide => 1,
1238                get => sub {
1239                    my ($self) = @_;
1240                    my $sth = $self->object->db->prepare_cached(
1241                        sprintf(
1242                            q{select date_part('epoch', COALESCE(endcircuit,  expire))::int as expire
1243                            from %s where %s = ?},
1244                            $self->object->db->quote_identifier($self->object->_object_table),
1245                            $self->object->db->quote_identifier($self->object->_key_field),
1246                        )
1247                    );
1248                    $sth->execute($self->object->id) or $self->object->db->rollback;
1249                    my $res = $sth->fetchrow_hashref;
1250                    $sth->finish;
1251                    return $res->{expire}
1252                },
1253            },
1254            cells  => {
1255                ro => 1,
1256                reference => 'group',
1257            },
1258            departments => {
1259                reference => 'group',
1260                delayed => 1,
1261                ro => 1,
1262                label => l('Departments'),
1263            },
1264            arrivalDate => { },
1265            expired => {
1266                ro => 1,
1267                label => l('Expired'),
1268            },
1269            active => {
1270                ro => 1,
1271                label => l('Active'),
1272            },
1273            status => {
1274                ro => 1,
1275                label => l('Statut du compte'),
1276            },
1277            pwdAccountLockedTime => {
1278                auto => 1,
1279                ro => 1,
1280            },
1281            _pwdAccountLockedTime => {
1282                managed => 1,
1283                ro => 1,
1284                hide => 1,
1285                get => sub {
1286                    my ($self) = @_;
1287                    my $obj = $self->object;
1288                    if ($obj->_get_c_field('locked')) {
1289                        return '000001010000Z';
1290                    } else {
1291                        my $sth = $obj->db->prepare_cached(
1292                            sprintf(
1293                                q{select to_char(%s AT TIME ZONE 'Z', 'YYYYMMDDHH24MISSZ') as expire
1294                                from %s where %s = ? and expire < now()},
1295                                $base->config('endCircuitdontExpire') ? 'expire' : 'COALESCE(endcircuit,  expire)',
1296                                $obj->db->quote_identifier($obj->_object_table),
1297                                $obj->db->quote_identifier($obj->_key_field),
1298                            )
1299                        );
1300                        $sth->execute($obj->id);
1301                        my $res = $sth->fetchrow_hashref;
1302                        $sth->finish;
1303                        return $res->{expire}
1304                    }
1305                },
1306            },
1307            userPassword => { readable => 0, },
1308            wWWHomePage => {
1309                label => l('Web Page'),
1310                formopts => { length => 35 },
1311            },
1312            title => { },
1313            snNative => {
1314                label => l('Native name'),
1315            },
1316            givenNameNative => {
1317                label => l('Native first name'),
1318            },
1319            sn => {
1320                label => l('Name'),
1321            },
1322            shadowWarning => { },
1323            shadowMin => { },
1324            shadowMax => { },
1325            shadowLastChange => { },
1326            shadowInactive => { },
1327            shadowFlag => { },
1328            otherTelephone => { },
1329            nickname => {
1330                label => l('Nickname'),
1331            },
1332            mobile => { },
1333            mail => {
1334                label => l('Email'),
1335            },
1336            otherEmail => {
1337                label => l('External mail'),
1338            },
1339            labeledURI => { },
1340            jobType => { },
1341            ipPhone => { },
1342            initials => {
1343                label => l('Initials'),
1344                checkinput => sub {
1345                    $_[0] or return;
1346                    return(length($_[0]) <= 6)
1347                }
1348            },
1349            homePhone => { },
1350            homeDirectory => {
1351                label => l('Home directory'),
1352            },
1353            halReference => {
1354                label => l('HAL id'),
1355            },
1356            grade => { },
1357            givenName => {
1358                label => l('First name'),
1359            },
1360            encryptedPassword => { },
1361            description => {
1362                label => l('Description'),
1363            },
1364            company => {
1365                label => l('Company'),
1366            },
1367            employer => {
1368                label => l('Employer'),
1369            },
1370            comment => {
1371                label => l('Comment'),
1372            },
1373            college => { },
1374            passwordLastSet => {
1375                ro => 1,
1376                label => l('Password set'),
1377            },
1378            oldPassword => {
1379                multiple => 1,
1380            },
1381            bannedPassword => {
1382                multiple => 1,
1383            },
1384            sshPublicKey => {
1385                multiple => 1,
1386                formopts => { length => 45 },
1387            },
1388            sshPublicKeyFilter => {
1389                multiple => 1,
1390                formopts => { length => 45 },
1391            },
1392            delUnknownSshKey => {
1393                formtype => 'CHECKBOX',
1394            },
1395            _authorizedKeys => {
1396                multiple => 1,
1397                ro => 1,
1398                managed => 1,
1399                hide => 1,
1400                get => sub {
1401                    my ($attr) = @_;
1402                    my $self = $attr->object;
1403
1404                    my @keys = $self->_get_attributes('sshPublicKey');
1405
1406                    my @filters = $self->_get_attributes('sshPublicKeyFilter');
1407                    my $delUnknownSshKey = $self->_get_attributes('delUnknownSshKey');
1408
1409                    my %users = ( $self->id => 1 );
1410
1411                    if (@filters) {
1412                        foreach my $user ($self->base->search_objects('user', @filters, 'oalias=NULL')) {
1413                            my $ouser = $self->base->get_object('user', $user) or next;
1414                            $users{ $user } and next;
1415                            $users{ $user } = 1;
1416                            push(@keys, $ouser->_get_attributes('sshPublicKey'));
1417                        }
1418                    }
1419
1420                    return @keys
1421                        ? \@keys
1422                        : (@filters || $delUnknownSshKey
1423                            ? [ '# No key (' . DateTime->now->iso8601 . ')' ]
1424                            : undef);
1425                },
1426            },
1427            authorizedKeys => {
1428                multiple => 1,
1429                ro => 1,
1430            },
1431            currentEmployment => {
1432                managed => 1,
1433                ro => 1,
1434                reference => 'employment',
1435                get => sub {
1436                    my ($attr) = @_;
1437                    my $self = $attr->object;
1438
1439                    my $now = DateTime->now()->iso8601 . 'Z';
1440
1441                    my $sth = $self->base->db->prepare_cached(
1442                        q{
1443                        select name from employment where firstday <= ?::timestamp and
1444                        (lastday is null or lastday >= ?::timestamp - '1 days'::interval) and "user" = ?
1445                        limit 1
1446                        }
1447                    );
1448                    $sth->execute($now, $now, $self->id);
1449                    my $res = $sth->fetchrow_hashref;
1450                    $sth->finish;
1451                    if ($res) {
1452                        return $res->{name}
1453                    } else {
1454                        return;
1455                    }
1456                },
1457            },
1458            nextEmployment => {
1459                managed => 1,
1460                ro => 1,
1461                reference => 'employment',
1462                get => sub {
1463                    my ($attr) = @_;
1464                    my $self = $attr->object;
1465
1466                    my $now = DateTime->now()->iso8601 . 'Z';
1467
1468                    my $sth = $self->base->db->prepare_cached(
1469                        q{
1470                        select name from employment where firstday > ?::timestamp and "user" = ?
1471                        order by firstday asc
1472                        limit 1
1473                        }
1474                    );
1475                    $sth->execute($now, $self->id);
1476                    my $res = $sth->fetchrow_hashref;
1477                    $sth->finish;
1478                    if ($res) {
1479                        return $res->{name}
1480                    } else {
1481                        return;
1482                    }
1483                }
1484            },
1485            activeEmployment => {
1486                managed => 1,
1487                ro => 1,
1488                reference => 'employment',
1489                multiple => 1,
1490                get => sub {
1491                    my ($attr) = @_;
1492                    my $self = $attr->object;
1493
1494                    my $now = DateTime->now()->iso8601 . 'Z';
1495
1496                    my $sth = $self->base->db->prepare_cached(
1497                        q{
1498                        select name from employment where (lastday > ?::timestamp or lastday IS NULL) and "user" = ?
1499                        order by firstday asc
1500                        limit 1
1501                        }
1502                    );
1503                    $sth->execute($now, $self->id);
1504                    my @Res;
1505                    while (my  $res = $sth->fetchrow_hashref) {
1506                        push(@Res, $res->{name});
1507                    }
1508
1509                    return \@Res;
1510                }
1511            },
1512            prevEmployment => {
1513                managed => 1,
1514                ro => 1,
1515                reference => 'employment',
1516                get => sub {
1517                    my ($attr) = @_;
1518                    my $self = $attr->object;
1519
1520                    my $now = DateTime->now()->iso8601 . 'Z';
1521
1522                    my $sth = $self->base->db->prepare_cached(
1523                        q{
1524                        select name from employment where
1525                        (lastday is not null and lastday <= ?::timestamp - '1 days'::interval) and "user" = ?
1526                        order by firstday desc
1527                        limit 1
1528                        }
1529                    );
1530                    $sth->execute($now, $self->id);
1531                    my $res = $sth->fetchrow_hashref;
1532                    $sth->finish;
1533                    if ($res) {
1534                        return $res->{name}
1535                    } else {
1536                        return;
1537                    }
1538                }
1539            },
1540            appliedEmployement => {
1541                hide => 1,
1542                reference => 'employment',
1543            },
1544            contratTypeHistory => {
1545                reference => 'group',
1546                can_values => sub {
1547                    $base->search_objects('group', 'sutype=contrattype')
1548                },
1549                multiple => 1,
1550            },
1551            employmentHistory => {
1552                reference => 'employment',
1553                multiple => 1,
1554                ro => 1,
1555            },
1556            hosted => {
1557                formtype => 'CHECKBOX',
1558                label => l('Hosted'),
1559            },
1560            assigned => {
1561                formtype => 'CHECKBOX',
1562                label => l('Assigned'),
1563            },
1564            createRequestId => {
1565                label => l('Account Request id')
1566            },
1567            requestId => {
1568                label => l('Request id'),
1569            },
1570            nationality => {
1571                label => l('Nationality'),
1572            },
1573            nativeCountry => {
1574                label => l('Native country'),
1575            },
1576            firstAidTrainingValidity => {
1577                formtype => 'DATE',
1578                label => l('Validité formation SST'),
1579            },
1580    };
1581
1582    my $employmentro = sub {
1583        my $setting = $base->config('employment_lock_user') || 'any';
1584
1585        for ($setting) {
1586            /^always$/ and return 1;
1587            /^never$/ and return 0;
1588
1589            $_[0] or return 0;
1590
1591            /^any$/i and return $_[0]->listEmployment ? 1 : 0;
1592            /^active/i and do {
1593                return $_[0]->_get_c_field('currentEmployment')
1594                ? 1
1595                : $_[0]->_get_c_field('nextEmployment') ? 1 : 0;
1596            };
1597            /(\S+)=(\S+)/ and do {
1598                my $attr = $_[0]->_get_c_field($1);
1599                if (defined($attr)) {
1600                    if ($2 eq '*') {
1601                        return 1;
1602                    } elsif($2 eq $attr) {
1603                        return 1;
1604                    } else {
1605                        return 0;
1606                    }
1607                } else {
1608                    return 0;
1609                }
1610            };
1611        }
1612        return $_[0]->listEmployment ? 1 : 0; # default is any!
1613    };
1614
1615    foreach (_reported_atributes(), qw(department managerContact contratTypeHistory)) {
1616        $attrs->{$_}{ro} = $employmentro;
1617    }
1618
1619    $attrs->{expire}{ro} = sub {
1620        my $expireOn = $base->config('expireOn') || '';
1621        if ($expireOn eq 'never') {
1622            return 0;
1623        }
1624
1625        $employmentro->($_[0]);
1626    };
1627
1628    $class->SUPER::_get_attr_schema($base, $attrs)
1629}
1630
1631sub CreateAlias {
1632    my ($class, $base, $name, $for) = @_;
1633
1634    my $stAddAlias = $base->db->prepare_cached(
1635        q{INSERT INTO "user" (name, uidnumber,            gidnumber, oalias, oaliascache) values
1636                             (?,    -nextval('ikey_seq'), ?,         ?,      ?)}
1637    );
1638
1639    my $ref = $base->_derefObject($class->type, $for);
1640    my $res = $stAddAlias->execute($name, -1, $for, $ref ? $ref->id : undef);
1641    return $res ? 1 : 0;
1642}
1643
1644sub _get_state {
1645    my ($self, $state) = @_;
1646    for ($state) {
1647        /^expired$/ and do {
1648            my $attribute = $self->attribute('expire');
1649            $attribute->check_acl('r') or return;
1650            my $sth = $self->db->prepare_cached(
1651                q{ select coalesce(expire < now(), false) as exp from "user"
1652                where "user".name = ?}
1653            );
1654            $sth->execute($self->id);
1655            my $res = $sth->fetchrow_hashref;
1656            $sth->finish;
1657            return $res->{exp} ? 1 : 0;
1658        };
1659    }
1660}
1661
1662sub set_fields {
1663    my ($self, %data) = @_;
1664
1665    my $old;
1666    if (exists($data{department})) {
1667        $old = $self->_get_attributes('department');
1668    }
1669
1670    if (($data{department} || '') eq ($old || '')) {
1671        # We do not remove the group, there is no change
1672        $old = undef;
1673    }
1674
1675    if ($old) {
1676        # If the department is no longer a department
1677        # we do nothing
1678        my @names = $self->base->search_objects('group', 'name=' . $old, 'sutype=dpmt');
1679        if (! @names) {
1680            $old = undef;
1681        }
1682    }
1683
1684    my $res = $self->SUPER::set_fields(%data) or return;
1685
1686    if ($self->base->config('remove_old_dpmt') && $old) {
1687        $self->base->log(LA_DEBUG,
1688            "Removing %s from group %s (department change to %s)",
1689            $self->id,
1690            $old,
1691            $data{department} || '');
1692        $self->_delAttributeValue('memberOf', $old) or return;
1693        $res++;
1694    }
1695
1696    $res
1697}
1698
1699=head2 listEmployment
1700
1701Return the ordered list of contract
1702
1703=cut
1704
1705sub listEmployment {
1706    my ($self) = @_;
1707
1708    my $sth = $self->base->db->prepare_cached(
1709        q{
1710        select name from employment where "user" = ?
1711        order by lastday desc NULLS first
1712        }
1713    );
1714    $sth->execute($self->id);
1715    my @list = ();
1716    while (my $res = $sth->fetchrow_hashref) {
1717        push(@list, $res->{name});
1718    }
1719
1720    @list
1721}
1722
1723sub _reported_atributes { qw(contratType endcircuit hosted assigned requestId company employer) }
1724
1725=head2 applyCurrentEmployment
1726
1727Search the current employment is any and apply paramter to user
1728
1729=cut
1730
1731sub applyCurrentEmployment {
1732    my ($self) = @_;
1733
1734    # Get current employment name
1735    my $currentempl = $self->get_attributes('currentEmployment') || '';
1736
1737    $self->base->log(
1738        LA_DEBUG,
1739        "Applying Employement %s to user %s",
1740        $currentempl || '(none)',
1741        $self->id
1742    );
1743
1744    if (my $currentemployment = $self->base->get_object('employment', $currentempl)) {
1745
1746        # If an employement apply we set the value to the user object
1747
1748        $self->computeEmploymentDate;
1749
1750        my %attrsets = (
1751            appliedEmployement => $currentemployment->id,
1752        );
1753        foreach my $attr (_reported_atributes(), qw(department managerContact)) {
1754            my $uval = $self->get_attributes($attr) || '';
1755            my $cval = $currentemployment->get_attributes($attr) || '';
1756
1757            if ($attr eq 'managerContact') {
1758                if (!$cval) {
1759                    my $dpmt  = $currentemployment->get_attributes('department') or last;
1760                    my $odmpt = $currentemployment->base->get_object('group', $dpmt) or last;
1761                    $cval = $odmpt->get_attributes('managedBy');
1762                }
1763            }
1764
1765            if ($uval ne $cval) {
1766                my $oattr = $currentemployment->base->attribute('user', $attr);
1767                $attrsets{$oattr->iname} = $cval;
1768            }
1769        }
1770
1771        if (keys %attrsets) {
1772            if (my $res = $self->set_fields(%attrsets)) {
1773                $self->ReportChange('Update', 'Attr %s updated to match Employment %s', join(', ', sort keys %attrsets), $currentemployment->id);
1774                return $res;
1775            }
1776        } else {
1777            return 1;
1778        }
1779    } else {
1780        # No current employment, resetting values:
1781
1782        return $self->_resetEmployment;
1783    }
1784
1785}
1786
1787# Reset attribute value set by employment
1788# except managerContact and expire
1789
1790sub _resetEmployment {
1791    my ($self) = @_;
1792
1793    $self->computeEmploymentDate;
1794
1795    my %changes = (
1796        appliedEmployement => undef,
1797    );
1798
1799    my @attributesToReset = (_reported_atributes(), qw(department));
1800
1801    foreach my $attr (@attributesToReset) {
1802        my $default = $self->base->config("unemployment.$attr") || '';
1803        my $old = $self->_get_attributes($attr) || '';
1804
1805        if ($old ne $default) {
1806            $changes{$attr} = $default || undef;
1807        }
1808    }
1809
1810    if(!$self->get_attributes('managerContact')) {
1811        if (my $next = $self->_get_attributes('nextEmployment')) {
1812            my $onext = $self->base->get_object('employment', $next);
1813            $changes{'manager'} = $onext->_get_attributes('managerContact');
1814        }
1815    }
1816
1817    # Managing expire:
1818    # If we found next status apply, keep it for expiration
1819    # Otherwise we reset to previous end of status
1820
1821    if (my $expire = $self->_computeEndEmployment($self->base->config('employment_delay') || 0)) {
1822        $changes{ 'expire' } = $expire;
1823    } elsif (my $prevEmployment = $self->_get_attributes('prevEmployment')) {
1824        my $oprev = $self->base->get_object('employment', $prevEmployment);
1825        $changes{ 'expire' } = $oprev->_get_attributes('lastday');
1826    } elsif (($self->base->config('unemployed_expire') ||'') ne 'no') {
1827        if (my $def = $self->base->{defattr}{'user.expire'}) {
1828            $changes{ 'expire' } = $def;
1829        }
1830    }
1831
1832
1833    if (%changes) {
1834        if ($self->set_fields(%changes)) {
1835            $self->base->log(LA_NOTICE, "Updating user %s to match unemployment", $self->id);
1836            $self->ReportChange('Update', 'Update %s to match unemployment', join(', ', sort keys %changes));
1837            return 1;
1838        } else {
1839            return 0;
1840        }
1841    } else {
1842        return 1;
1843    }
1844
1845}
1846
1847=head2 computeEmploymentDate
1848
1849Compute and copy to user start and end employment date
1850
1851=cut
1852
1853sub computeEmploymentDate {
1854    my ($self) = @_;
1855
1856    my $currentemployment = $self->get_attributes('currentEmployment') || '';
1857
1858    my $expire = str2time($self->_get_attributes('expire') || '1970-01-01T00:00:00');
1859
1860    my %changes;
1861    my @employmentDate = qw(
1862        endEmployment   endStrictEmployment   endCurrentEmployment   endLastEmployment
1863        startEmployment startStrictEmployment startCurrentEmployment startFirstEmployment
1864        arrival departure
1865    );
1866    foreach (@employmentDate) {
1867        my $old = $self->_get_attributes($_) || '';
1868        my $new = $self->_get_attributes("_$_") || '';
1869        if ($old ne $new) {
1870            $changes{$_} = $new || undef;
1871        }
1872    }
1873
1874    # If there is no current employment we try to find any to not let expire
1875    # unset
1876
1877    my $expireOn = $self->base->config('expireOn') || '';
1878    if (!grep { $_ eq $expireOn } (@employmentDate, '', 'never')) {
1879        $self->base->log(LA_ERR, "expireOn set to invalid parameter %s, using endEmployment instead", $expireOn);
1880        $expireOn = undef;
1881    }
1882    $expireOn ||= 'endEmployment';
1883
1884    # We check if matching start exists to know if using end* for expiration is
1885    # safe, even undef
1886    my %end2start = (
1887        endEmployment        => 'startEmployment',
1888        endStrictEmployment  => 'startStrictEmployment',
1889        endCurrentEmployment => 'startCurrentEmployment',
1890        endLastEmployment    => 'startFirstEmployment',
1891    );
1892
1893    # TODO rework this, working code but bloat
1894    if ($expireOn ne 'never') {
1895        my $endemploy = '';
1896        if ($self->_get_attributes("_$end2start{$expireOn}")) {
1897            $endemploy = $self->_get_attributes("_$expireOn") || '';
1898            $endemploy ||= 'UNCHANGED' unless($currentemployment);
1899        } elsif (($self->base->config('unemployed_expire') ||'') eq 'no') {
1900            $endemploy = '';
1901        } else {
1902            # No expiration date apply, don't touch
1903            $endemploy = 'UNCHANGED';
1904        }
1905
1906        if ($endemploy ne 'UNCHANGED') {
1907            my $nextexpire = str2time( $endemploy || '1970-01-01T00:00:00' );
1908
1909            if ($expire != $nextexpire) {
1910                $changes{expire} = $endemploy;
1911            }
1912        }
1913    }
1914
1915    if (keys %changes) {
1916        $self->base->log(LA_DEBUG, 'Applying employment state to user %s for field %s', $self->id, join(', ', keys %changes));
1917        $self->ReportChange('Update', 'Update %s to match employment', join(', ', sort keys %changes));
1918        if (exists($changes{expire})) {
1919            $self->ReportChange('Update', 'Expire update to %s to match employment', ($changes{expire} || '(none)'));
1920            $self->base->log(LA_DEBUG, 'New expiration is %s for user %s', ($changes{expire} || '(none)'), $self->id);
1921        }
1922        $self->set_fields(%changes);
1923    } else {
1924        $self->base->log(LA_DEBUG, 'No employment change for user %s', $self->id);
1925    }
1926
1927    $self->_computeEmploymentHistory();
1928
1929    return 1;
1930}
1931
1932sub _computeStartEmployment {
1933    my ($self, $delay, $any, $workday) = @_;
1934
1935    $delay ||= 0;
1936    my $start;
1937    my $nstart;
1938
1939    if (my $next = $self->_get_attributes('nextEmployment')) {
1940        my $onext = $self->base->get_object('employment', $next);
1941        $nstart = DateTime->from_epoch(epoch => str2time($onext->_get_attributes('firstday')));
1942        $nstart->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
1943    }
1944
1945    my $list_empl = $self->base->db->prepare_cached(q{
1946        SELECT *, (lastday is null or lastday >= now() - '1days'::interval) as "current" FROM employment
1947        WHERE "user" = ? and firstday < now()
1948        order by firstday desc
1949        });
1950    $list_empl->execute($self->id);
1951
1952    while (my $res = $list_empl->fetchrow_hashref) {
1953        if ($res->{current}) {
1954        } elsif ($nstart) {
1955            my $prevend = DateTime->from_epoch(epoch => str2time($res->{lastday}));
1956            $prevend->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
1957            my $tstart = $nstart->clone;
1958            $tstart->subtract(days => $delay + 1);
1959            if ($tstart->ymd gt $prevend->ymd) {
1960                last;
1961            }
1962        } elsif ((!$res->{current}) && (!$any)) {
1963            last;
1964        }
1965        $nstart = DateTime->from_epoch(epoch => str2time($res->{firstday}));
1966        $nstart->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
1967        $start = $nstart->clone;
1968    }
1969    $list_empl->finish;
1970
1971    $start ||= $nstart if ($any);
1972
1973    if ($start) {
1974        if ($workday) {
1975            my $day_of_week = $start->day_of_week;
1976            $start->add(days =>
1977                $day_of_week == 6 ? 2 :
1978                $day_of_week == 7 ? 1 : 0
1979            );
1980        }
1981    }
1982
1983    return $start ? $start->iso8601 : undef
1984}
1985
1986sub _computeEndEmployment {
1987    my ($self, $delay, $any, $workday) = @_;
1988
1989    $delay ||= 0;
1990    my $end;
1991    my $pend;
1992
1993    if (my $prev = $self->_get_attributes('prevEmployment')) {
1994        my $oprev = $self->base->get_object('employment', $prev);
1995        $pend = DateTime->from_epoch(epoch => str2time($oprev->_get_attributes('lastday')));
1996        $pend->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
1997        $pend->add(hours => 23, minutes => 59, seconds => 59);
1998    }
1999
2000    my $list_empl = $self->base->db->prepare_cached(q{
2001        SELECT *, firstday <= now() as "current" FROM employment WHERE "user" = ? and
2002        (lastday is null or lastday >= now() - '1 days'::interval)
2003        order by firstday asc
2004        });
2005    $list_empl->execute($self->id);
2006    while (my $res = $list_empl->fetchrow_hashref) {
2007        if (!$res->{lastday}) {
2008            # Ultimate employment.
2009            $list_empl->finish;
2010            return undef;
2011        }
2012        if ($res->{current}) {
2013        } elsif ($end) {
2014            my $nextstart = DateTime->from_epoch(epoch => str2time($res->{firstday}));
2015            $nextstart->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
2016            my $tend = $end->clone;
2017            $tend->add(days => $delay + 1);
2018            if ($tend->ymd lt $nextstart->ymd) {
2019                last;
2020            }
2021        } elsif ($pend) {
2022            my $nextstart = DateTime->from_epoch(epoch => str2time($res->{firstday}));
2023            $nextstart->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
2024            my $tend = $pend->clone;
2025            $tend->add(days => $delay + 1);
2026            if ($tend->ymd lt $nextstart->ymd) {
2027                last;
2028            }
2029            $end = $tend
2030        } elsif ((!$res->{current}) && (!$any)) {
2031            last;
2032        }
2033        $end = DateTime->from_epoch(epoch => str2time($res->{lastday}));
2034        $end->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
2035        $end->add(hours => 23, minutes => 59, seconds => 59);
2036    }
2037    $list_empl->finish;
2038
2039    $end ||= $pend if($any);
2040
2041    if ($end) {
2042        if ($workday) {
2043            my $day_of_week = $end->day_of_week;
2044            $end->subtract(days =>
2045                $day_of_week == 7 ? 2 :
2046                $day_of_week == 6 ? 1 : 0
2047            );
2048        }
2049    }
2050
2051    return $end ? $end->iso8601 : undef
2052}
2053
2054# Compute a summary of employement and store the value
2055# into an attribute
2056
2057sub _computeEmploymentHistory {
2058    my ($self) = @_;
2059
2060    my %changes;
2061
2062    {
2063        my $sth = $self->db->prepare_cached(q{
2064            select employment.name from employment
2065            where "user" = ? and employment.firstday < now()
2066        });
2067        $sth->execute($self->id);
2068        my @values;
2069        while (my $res = $sth->fetchrow_hashref) {
2070            push(@values, $res->{name});
2071        }
2072        $changes{"employmentHistory"} = \@values;
2073    }
2074
2075    foreach my $attribute (qw(contratType)) {
2076        my $sth = $self->db->prepare_cached(q{
2077            select employment_attributes.value from employment
2078            join employment_attributes
2079            on employment.ikey = employment_attributes.okey
2080            where "user" = ? and employment_attributes.attr = ?
2081            and employment.firstday < now()
2082            group by employment_attributes.value
2083            });
2084        $sth->execute($self->id, $attribute);
2085        my @values;
2086        while (my $res = $sth->fetchrow_hashref) {
2087            push(@values, $res->{value});
2088        }
2089        $changes{$attribute . "History"} = \@values;
2090    }
2091
2092    $self->set_fields(%changes);
2093}
2094
2095=head2 EmploymentSummary
2096
2097Return an array of employment information group by successive contratType
2098
2099=cut
2100
2101sub EmploymentSummary {
2102    my ( $self ) = @_;
2103
2104    my $sth = $self->db->prepare_cached(q{
2105        select employment.name from employment
2106        where "user" = ? order by employment.firstday asc
2107    });
2108    $sth->execute($self->id);
2109    warn $self->id;
2110    my @values;
2111    my $prevContrat = ':';
2112    my $prevEnd = undef;
2113    while (my $res = $sth->fetchrow_hashref) {
2114        my $Emp = $self->base->get_object('employment', $res->{name});
2115
2116        my $new = 0;
2117
2118        my $curContrat  = $Emp->get_attributes('contratType') || '';
2119        my $DTfirstday  = DateTime::Format::Pg->parse_datetime( $Emp->get_attributes('firstday') );
2120
2121        warn $DTfirstday->ymd('-');
2122
2123        if ($curContrat ne $prevContrat) {
2124            $new = 1;
2125        }
2126        if ($prevEnd) {
2127            if ($DTfirstday->epoch - $prevEnd->epoch > 86400 * 2) {
2128                $new = 1;
2129            }
2130        }
2131        if (!@values) {
2132            $new = 1;
2133        }
2134
2135        if ( my $lastday = $Emp->get_attributes('lastday') ) {
2136            $prevEnd = DateTime::Format::Pg->parse_datetime( $lastday );
2137        }
2138
2139        if ( $new ) {
2140            $prevContrat = $curContrat;
2141            push(
2142                @values,
2143                {
2144                    firstday => $DTfirstday->ymd('-'),
2145                    lastday  => $prevEnd ? $prevEnd->ymd('-') : undef,
2146                    contratType => $curContrat,
2147                }
2148            );
2149        } else {
2150            $values[-1]->{lastday} = $prevEnd ? $prevEnd->ymd('-') : undef;
2151        }
2152    }
2153
2154    @values
2155}
2156
2157=head2 StoreEmployementSummary
2158
2159Store into database the employment summary
2160
2161=cut
2162
2163sub StoreEmployementSummary {
2164    my ( $self ) = @_;
2165
2166    my $stu = $self->base->db->prepare_cached(q{
2167        UPDATE employmentsum set
2168            "user" = ?,
2169            firstday = ?,
2170            lastday  = ?,
2171            contrattype = ?,
2172            nodelete = 't'
2173        WHERE name = ?
2174    });
2175    my $sti = $self->base->db->prepare_cached(q{
2176        INSERT INTO employmentsum
2177        ("user", firstday, lastday, contrattype, name, nodelete)
2178        VALUES
2179        (?, ?, ?, ?, ?, 't')
2180    });
2181
2182    my @values = $self->EmploymentSummary;
2183
2184    my @names;
2185
2186    foreach (@values) {
2187        my $name = $self->id . '-' . $_->{firstday};
2188        my $res = $stu->execute($self->id, $_->{firstday}, $_->{lastday}, $_->{contrattype}, $name);
2189        if ($res == 0) {
2190            $sti->execute($self->id, $_->{firstday}, $_->{lastday}, $_->{contrattype}, $name);
2191        }
2192        push(@names, $name);
2193    }
2194
2195    my $std = $self->base->db->prepare_cached(q{
2196        DELETE FROM employmentsum WHERE "user" = ? AND name != ALL (?)
2197    });
2198    $std->execute($self->id, \@names);
2199}
2200
2201=head2 storeBannedPassword($epassword)
2202
2203Add an encrypted password to untrust list
2204
2205=cut
2206
2207sub storeBannedPassword {
2208    my ($self, $EncPass) = @_;
2209
2210    my @banned = sort { $b cmp $a } $self->_get_attributes('bannedPassword');
2211    my $now = DateTime->now; 
2212    unshift(@banned, $now->iso8601 . ';' . $EncPass);
2213    $self->set_fields('bannedPassword', [ grep { $_ } @banned ]);
2214
2215}
2216
2217=head2 banCurrentPassword
2218
2219Store the current password as banned
2220
2221=cut
2222
2223sub banCurrentPassword {
2224    my ($self) = @_;
2225   
2226    my $old = $self->get_field('userPassword') or return;
2227    $self->storeBannedPassword($old);
2228}
2229
2230sub check_password {
2231    my ( $self, $password ) = @_;
2232
2233    my $res = $self->SUPER::check_password($password);
2234    if ($res !~ /^ok$/) {
2235        return $res;
2236    }
2237
2238    foreach my $banned ($self->_get_attributes('bannedPassword')) {
2239        my ($date, $oldPassword) = $banned =~ /^([^;]*);(.*)/;
2240        if (crypt($password, $oldPassword) eq $oldPassword) {
2241            return "Banned password, cannot be used anymore";
2242        }
2243    }
2244
2245    return 'ok';
2246}
2247
2248sub _set_password {
2249    my ($self, $clear_pass) = @_;
2250    if (my $attr = $self->base->attribute($self->type, 'userPassword')) {
2251        my $field = $attr->iname;
2252
2253        # Storing as old password
2254        my @olds = sort { $b cmp $a } $self->_get_attributes('oldPassword');
2255        if (my $old = $self->get_field('userPassword')) {
2256            my $now = DateTime->now; 
2257            unshift(@olds, $now->iso8601 . ';' . $old);
2258            $self->set_fields('oldPassword', [ grep { $_ } @olds[0 .. 14] ]);
2259        }
2260
2261        my $res = $self->set_fields($field, $self->base->passCrypt($clear_pass));
2262        if ($res) {
2263            if ($self->base->get_global_value('rsa_public_key')) {
2264                $self->setCryptPassword($clear_pass) or return;
2265            }
2266        }
2267
2268        $self->set_fields('passwordLastSet', DateTime->now->datetime);
2269        $self->base->log(LA_NOTICE,
2270            'Mot de passe changé pour %s',
2271            $self->id
2272        );
2273
2274
2275        return $res;
2276    } else {
2277        $self->log(LA_WARN,
2278            "Cannot set password: userPassword attributes is unsupported");
2279    }
2280}
2281
2282=head2 setCryptPassword($clear_pass)
2283
2284Store password encrypted using RSA encryption.
2285
2286=cut
2287
2288sub setCryptPassword {
2289    my ($self, $clear_pass) = @_;
2290    if (my $serialize = $self->base->get_global_value('rsa_public_key')) {
2291        my $public = Crypt::RSA::Key::Public->new;
2292        $public = $public->deserialize(String => [ $serialize ]);
2293        my $rsa = new Crypt::RSA ES => 'PKCS1v15';
2294        my $rsa_password = $rsa->encrypt (
2295            Message    => $clear_pass,
2296            Key        => $public,
2297            Armour     => 1,
2298        ) || die $rsa->errstr();
2299        if (!$self->_set_c_fields('encryptedPassword', $rsa_password)) {
2300            $self->log(LA_ERR,
2301                "Cannot set 'encryptedPassword' attribute for object %s/%s",
2302                $self->type, $self->id,
2303            );
2304            return;
2305        }
2306    }
2307    $self->ReportChange('Password', 'Password stored using internal key');
2308    return 1;
2309}
2310
2311=head2 _InjectCryptPasswd($cryptpasswd)
2312
2313Inject a password encrypted using standard UNIX method.
2314
2315The passwrod will be used to authenticate user inside the application but it
2316will not be transmit to any other database.
2317
2318=cut
2319
2320sub _InjectCryptPasswd {
2321    my ($self, $cryptpasswd) = @_;
2322
2323    if (my $current = $self->get_field('userPassword')) {
2324        if ($cryptpasswd eq $current) {
2325            return 1;
2326        }
2327    }
2328    my $res = $self->set_fields('userPassword', $cryptpasswd);
2329
2330    if ($res) {
2331        $self->base->log(LA_NOTICE, 'Crypted password injected for %s', $self->id);
2332        return 1;
2333    } else {
2334        $self->base->log(LA_ERR, 'Cannot inject crypted password for %s', $self->id);
2335        return 0;
2336    }
2337}
2338
2339=head2 GenPasswordResetId
2340
2341Return a new id allowing passowrd reset
2342
2343=cut
2344
2345sub GenPasswordResetId {
2346    my ($self) = @_;
2347
2348    my $id = LATMOS::Accounts::Utils::genpassword(length => 32);
2349
2350    my $sth = $self->base->db->prepare_cached(q{
2351        INSERT INTO passwordreset (id, "user") values (?,?)
2352    });
2353
2354    if ($sth->execute($id, $self->id)) {
2355        return $id;
2356    } else {
2357        return;
2358    }
2359}
2360
2361=head2 SendPasswordReset($url)
2362
2363Generate a password reset Id and the to the user.
2364
2365C<$url> is the URL where the password can changed (printf forward, the %s is
2366replaced by the request id)
2367
2368=cut
2369
2370sub SendPasswordReset {
2371    my ($self, $url) = @_;
2372
2373    my $id = $self->GenPasswordResetId;
2374
2375    my $mail = $self->_get_attributes('mail') or do {
2376        $self->base->log(LA_ERR, "Cannot sent reset password mail: no mail found");
2377        return;
2378    };
2379
2380    my $MailSubject = $self->base->la->val('_default_', 'mailSubject', 'LATMOS::Accounts');
2381
2382    my %mail = (
2383        Subject => "$MailSubject: pasword reset",
2384        'X-LATMOS-Reason' => 'Password Reset',
2385        to => $mail,
2386    );
2387
2388    if (my $otherEmail = $self->_get_attributes('otherEmail')) {
2389        $mail{cc} = $otherEmail;
2390    }
2391
2392    my $vars = {
2393        url => sprintf($url, $id),
2394    };
2395    $vars->{id} =  $id;
2396    $vars->{obj} = $self;
2397
2398    my $lamail = LATMOS::Accounts::Mail->new(
2399        $self->base->la,
2400        'passwordreset.mail',
2401    );
2402
2403    if ($lamail->process(\%mail, $vars)) {
2404        $self->base->log(LA_NOTICE,
2405            "Reset password sent to %s for user %s",
2406            $mail{to},
2407            $self->id,
2408        );
2409        return 1;
2410    } else {
2411        return;
2412    }
2413
2414}
2415
2416=head2 CheckPasswordResetId($id)
2417
2418Return True if the reset password ID can be found and is less than one day old
2419
2420=cut
2421
2422sub CheckPasswordResetId {
2423    my ($self, $id) = @_;
2424
2425    my $sth = $self->base->db->prepare_cached(q{
2426        SELECT * FROM passwordreset WHERE
2427            "user" = ? and
2428            id = ? and
2429            "create" >= now() - '1 days'::interval
2430    });
2431    $sth->execute($self->id, $id);
2432
2433    my $res = $sth->fetchrow_hashref;
2434    $sth->finish;
2435
2436    return $res ? 1 : 0;
2437}
2438
2439=head2 DeletePasswordId($id)
2440
2441Delete password reset C<$id> and all expired request
2442
2443=cut
2444
2445sub DeletePasswordId {
2446    my ($self, $id) = @_;
2447
2448    my $sth = $self->base->db->prepare_cached(q{
2449        DELETE FROM passwordreset WHERE
2450        "user" = ? AND (id = ? or "create" < now() - '1 days'::interval)
2451    });
2452
2453    $sth->execute($self->id, $id);
2454}
2455
24561;
2457
2458__END__
2459
2460=head1 SEE ALSO
2461
2462=head1 AUTHOR
2463
2464Olivier Thauvin, E<lt>olivier.thauvin@latmos.ipsl.frE<gt>
2465
2466=head1 COPYRIGHT AND LICENSE
2467
2468Copyright (C) 2008, 2009 CNRS SA/CETP/LATMOS
2469
2470This library is free software; you can redistribute it and/or modify
2471it under the same terms as Perl itself, either Perl version 5.10.0 or,
2472at your option, any later version of Perl 5 you may have available.
2473
2474=cut
Note: See TracBrowser for help on using the repository browser.