3e0dc0ad0209c9c8bcfc3d928d11d1c763e1e2ae
[kivitendo-erp.git] / SL / Auth.pm
1 package SL::Auth;
2
3 use constant OK              =>   0;
4 use constant ERR_PASSWORD    =>   1;
5 use constant ERR_BACKEND     => 100;
6
7 use constant SESSION_OK      =>   0;
8 use constant SESSION_NONE    =>   1;
9 use constant SESSION_EXPIRED =>   2;
10
11 use Digest::MD5 qw(md5_hex);
12 use IO::File;
13 use Time::HiRes qw(gettimeofday);
14
15 use SL::Auth::DB;
16 use SL::Auth::LDAP;
17
18 use SL::User;
19 use SL::DBUtils;
20
21 sub new {
22   $main::lxdebug->enter_sub();
23
24   my $type = shift;
25   my $self = {};
26
27   bless $self, $type;
28
29   $self->{SESSION} = { };
30
31   $self->_read_auth_config();
32
33   $main::lxdebug->leave_sub();
34
35   return $self;
36 }
37
38 sub DESTROY {
39   my $self = shift;
40
41   $self->{dbh}->disconnect() if ($self->{dbh});
42 }
43
44 sub _read_auth_config {
45   $main::lxdebug->enter_sub();
46
47   my $self   = shift;
48
49   my $form   = $main::form;
50   my $locale = $main::locale;
51
52   my $code;
53   my $in = IO::File->new('config/authentication.pl', 'r');
54
55   if (!$in) {
56     $form->error($locale->text('The config file "config/authentication.pl" was not found.'));
57   }
58
59   while (<$in>) {
60     $code .= $_;
61   }
62   $in->close();
63
64   eval $code;
65
66   if ($@) {
67     $form->error($locale->text('The config file "config/authentication.pl" contained invalid Perl code:') . "\n" . $@);
68   }
69
70   if ($self->{module} eq 'DB') {
71     $self->{authenticator} = SL::Auth::DB->new($self);
72
73   } elsif ($self->{module} eq 'LDAP') {
74     $self->{authenticator} = SL::Auth::LDAP->new($self);
75   }
76
77   if (!$self->{authenticator}) {
78     $form->error($locale->text('No or an unknown authenticantion module specified in "config/authentication.pl".'));
79   }
80
81   my $cfg = $self->{DB_config};
82
83   if (!$cfg) {
84     $form->error($locale->text('config/authentication.pl: Key "DB_config" is missing.'));
85   }
86
87   if (!$cfg->{host} || !$cfg->{db} || !$cfg->{user}) {
88     $form->error($locale->text('config/authentication.pl: Missing parameters in "DB_config". Required parameters are "host", "db" and "user".'));
89   }
90
91   $self->{authenticator}->verify_config();
92
93   $self->{session_timeout} *= 1;
94   $self->{session_timeout}  = 8 * 60 if (!$self->{session_timeout});
95
96   $main::lxdebug->leave_sub();
97 }
98
99 sub authenticate_root {
100   $main::lxdebug->enter_sub();
101
102   my $self           = shift;
103   my $password       = shift;
104   my $is_crypted     = shift;
105
106   $password          = crypt $password, 'ro' if (!$password || !$is_crypted);
107   my $admin_password = crypt "$self->{admin_password}", 'ro';
108
109   $main::lxdebug->leave_sub();
110
111   return $password eq $admin_password ? OK : ERR_PASSWORD;
112 }
113
114 sub authenticate {
115   $main::lxdebug->enter_sub();
116
117   my $self = shift;
118
119   $main::lxdebug->leave_sub();
120
121   return $self->{authenticator}->authenticate(@_);
122 }
123
124 sub dbconnect {
125   $main::lxdebug->enter_sub();
126
127   my $self     = shift;
128   my $may_fail = shift;
129
130   if ($self->{dbh}) {
131     $main::lxdebug->leave_sub();
132     return $self->{dbh};
133   }
134
135   my $cfg = $self->{DB_config};
136   my $dsn = 'dbi:Pg:dbname=' . $cfg->{db} . ';host=' . $cfg->{host};
137
138   if ($cfg->{port}) {
139     $dsn .= ';port=' . $cfg->{port};
140   }
141
142   $main::lxdebug->message(LXDebug::DEBUG1, "Auth::dbconnect DSN: $dsn");
143
144   $self->{dbh} = DBI->connect($dsn, $cfg->{user}, $cfg->{password}, { 'AutoCommit' => 0 });
145
146   if (!$may_fail && !$self->{dbh}) {
147     $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr);
148   }
149
150   $main::lxdebug->leave_sub();
151
152   return $self->{dbh};
153 }
154
155 sub dbdisconnect {
156   $main::lxdebug->enter_sub();
157
158   my $self = shift;
159
160   if ($self->{dbh}) {
161     $self->{dbh}->disconnect();
162     delete $self->{dbh};
163   }
164
165   $main::lxdebug->leave_sub();
166 }
167
168 sub check_tables {
169   $main::lxdebug->enter_sub();
170
171   my $self    = shift;
172
173   my $dbh     = $self->dbconnect();
174   my $query   = qq|SELECT COUNT(*) FROM pg_tables WHERE (schemaname = 'auth') AND (tablename = 'user')|;
175
176   my ($count) = $dbh->selectrow_array($query);
177
178   $main::lxdebug->leave_sub();
179
180   return $count > 0;
181 }
182
183 sub check_database {
184   $main::lxdebug->enter_sub();
185
186   my $self = shift;
187
188   my $dbh  = $self->dbconnect(1);
189
190   $main::lxdebug->leave_sub();
191
192   return $dbh ? 1 : 0;
193 }
194
195 sub create_database {
196   $main::lxdebug->enter_sub();
197
198   my $self   = shift;
199   my %params = @_;
200
201   my $cfg    = $self->{DB_config};
202
203   if (!$params{superuser}) {
204     $params{superuser}          = $cfg->{user};
205     $params{superuser_password} = $cfg->{password};
206   }
207
208   $params{template} ||= 'template0';
209   $params{template}   =~ s|[^a-zA-Z0-9_\-]||g;
210
211   my $dsn = 'dbi:Pg:dbname=template1;host=' . $cfg->{host};
212
213   if ($cfg->{port}) {
214     $dsn .= ';port=' . $cfg->{port};
215   }
216
217   $main::lxdebug->message(LXDebug::DEBUG1, "Auth::create_database DSN: $dsn");
218
219   my $dbh = DBI->connect($dsn, $params{superuser}, $params{superuser_password});
220
221   if (!$dbh) {
222     $main::form->error($main::locale->text('The connection to the template database failed:') . "\n" . $DBI::errstr);
223   }
224
225   my $charset    = $main::dbcharset;
226   $charset     ||= Common::DEFAULT_CHARSET;
227   my $encoding   = $Common::charset_to_db_encoding{$charset};
228   $encoding    ||= 'UNICODE';
229
230   my $query = qq|CREATE DATABASE "$cfg->{db}" OWNER "$cfg->{user}" TEMPLATE "$params{template}" ENCODING '$encoding'|;
231
232   $main::lxdebug->message(LXDebug::DEBUG1, "Auth::create_database query: $query");
233
234   $dbh->do($query);
235
236   if ($dbh->err) {
237     my $error = $dbh->errstr();
238
239     $query                 = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
240     my ($cluster_encoding) = $dbh->selectrow_array($query);
241
242     if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i) && ($encoding !~ m/^(?:UTF-?8|UNICODE)$/i)) {
243       $error = $main::locale->text('Your PostgreSQL installationen uses UTF-8 as its encoding. Therefore you have to configure Lx-Office to use UTF-8 as well.');
244     }
245
246     $dbh->disconnect();
247
248     $main::form->error($main::locale->text('The creation of the authentication database failed:') . "\n" . $error);
249   }
250
251   $dbh->disconnect();
252
253   $main::lxdebug->leave_sub();
254 }
255
256 sub create_tables {
257   $main::lxdebug->enter_sub();
258
259   my $self = shift;
260   my $dbh  = $self->dbconnect();
261
262   my $charset    = $main::dbcharset;
263   $charset     ||= Common::DEFAULT_CHARSET;
264
265   $dbh->rollback();
266   User->process_query($main::form, $dbh, 'sql/auth_db.sql', undef, $charset);
267
268   $main::lxdebug->leave_sub();
269 }
270
271 sub save_user {
272   $main::lxdebug->enter_sub();
273
274   my $self   = shift;
275   my $login  = shift;
276   my %params = @_;
277
278   my $form   = $main::form;
279
280   my $dbh    = $self->dbconnect();
281
282   my ($sth, $query, $user_id);
283
284   $query     = qq|SELECT id FROM auth."user" WHERE login = ?|;
285   ($user_id) = selectrow_query($form, $dbh, $query, $login);
286
287   if (!$user_id) {
288     $query     = qq|SELECT nextval('auth.user_id_seq')|;
289     ($user_id) = selectrow_query($form, $dbh, $query);
290
291     $query     = qq|INSERT INTO auth."user" (id, login) VALUES (?, ?)|;
292     do_query($form, $dbh, $query, $user_id, $login);
293   }
294
295   $query = qq|DELETE FROM auth.user_config WHERE (user_id = ?)|;
296   do_query($form, $dbh, $query, $user_id);
297
298   $query = qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (?, ?, ?)|;
299   $sth   = prepare_query($form, $dbh, $query);
300
301   while (my ($cfg_key, $cfg_value) = each %params) {
302     next if ($cfg_key eq 'password');
303
304     do_statement($form, $sth, $query, $user_id, $cfg_key, $cfg_value);
305   }
306
307   $dbh->commit();
308
309   $main::lxdebug->leave_sub();
310 }
311
312 sub can_change_password {
313   my $self = shift;
314
315   return $self->{authenticator}->can_change_password();
316 }
317
318 sub change_password {
319   $main::lxdebug->enter_sub();
320
321   my $self   = shift;
322   my $result = $self->{authenticator}->change_password(@_);
323
324   $main::lxdebug->leave_sub();
325
326   return $result;
327 }
328
329 sub read_all_users {
330   $main::lxdebug->enter_sub();
331
332   my $self  = shift;
333
334   my $dbh   = $self->dbconnect();
335   my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
336                  FROM auth.user_config cfg
337                  LEFT JOIN auth."user" u ON (cfg.user_id = u.id)|;
338   my $sth   = prepare_execute_query($main::form, $dbh, $query);
339
340   my %users;
341
342   while (my $ref = $sth->fetchrow_hashref()) {
343     $users{$ref->{login}}                    ||= { 'login' => $ref->{login}, 'id' => $ref->{id} };
344     $users{$ref->{login}}->{$ref->{cfg_key}}   = $ref->{cfg_value} if (($ref->{cfg_key} ne 'login') && ($ref->{cfg_key} ne 'id'));
345   }
346
347   $sth->finish();
348
349   $main::lxdebug->leave_sub();
350
351   return %users;
352 }
353
354 sub read_user {
355   $main::lxdebug->enter_sub();
356
357   my $self  = shift;
358   my $login = shift;
359
360   my $dbh   = $self->dbconnect();
361   my $query = qq|SELECT cfg.cfg_key, cfg.cfg_value
362                  FROM auth.user_config cfg
363                  LEFT JOIN auth."user" u ON (cfg.user_id = u.id)
364                  WHERE (u.login = ?)|;
365   my $sth   = prepare_execute_query($main::form, $dbh, $query, $login);
366
367   my %user_data;
368
369   while (my $ref = $sth->fetchrow_hashref()) {
370     $user_data{$ref->{cfg_key}} = $ref->{cfg_value};
371     $user_data{login}           = $login;
372   }
373
374   $sth->finish();
375
376   $main::lxdebug->leave_sub();
377
378   return %user_data;
379 }
380
381 sub get_user_id {
382   $main::lxdebug->enter_sub();
383
384   my $self  = shift;
385   my $login = shift;
386
387   my $dbh   = $self->dbconnect();
388   my ($id)  = selectrow_query($main::form, $dbh, qq|SELECT id FROM auth."user" WHERE login = ?|, $login);
389
390   $main::lxdebug->leave_sub();
391
392   return $id;
393 }
394
395 sub delete_user {
396   $main::lxdebug->enter_sub();
397
398   my $self  = shift;
399   my $login = shift;
400
401   my $form  = $main::form;
402
403   my $dbh   = $self->dbconnect();
404   my $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
405
406   my ($id)  = selectrow_query($form, $dbh, $query, $login);
407
408   return $main::lxdebug->leave_sub() if (!$id);
409
410   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE user_id = ?|, $id);
411   do_query($form, $dbh, qq|DELETE FROM auth.user_config WHERE user_id = ?|, $id);
412
413   $dbh->commit();
414
415   $main::lxdebug->leave_sub();
416 }
417
418 # --------------------------------------
419
420 my $session_id;
421
422 sub restore_session {
423   $main::lxdebug->enter_sub();
424
425   my $self = shift;
426
427   my $cgi            =  $main::cgi;
428   $cgi             ||=  CGI->new('');
429
430   $session_id        =  $cgi->cookie($self->get_session_cookie_name());
431   $session_id        =~ s|[^0-9a-f]||g;
432
433   $self->{SESSION}   = { };
434
435   if (!$session_id) {
436     $main::lxdebug->leave_sub();
437     return SESSION_NONE;
438   }
439
440   my ($dbh, $query, $sth, $cookie, $ref, $form);
441
442   $form   = $main::form;
443
444   $dbh    = $self->dbconnect();
445   $query  = qq|SELECT *, (mtime < (now() - '$self->{session_timeout}m'::interval)) AS is_expired FROM auth.session WHERE id = ?|;
446
447   $cookie = selectfirst_hashref_query($form, $dbh, $query, $session_id);
448
449   if (!$cookie || $cookie->{is_expired} || ($cookie->{ip_address} ne $ENV{REMOTE_ADDR})) {
450     $self->destroy_session();
451     $main::lxdebug->leave_sub();
452     return SESSION_EXPIRED;
453   }
454
455   $query = qq|SELECT sess_key, sess_value FROM auth.session_content WHERE session_id = ?|;
456   $sth   = prepare_execute_query($form, $dbh, $query, $session_id);
457
458   while (my $ref = $sth->fetchrow_hashref()) {
459     $self->{SESSION}->{$ref->{sess_key}} = $ref->{sess_value};
460     $form->{$ref->{sess_key}}            = $ref->{sess_value} if (!defined $form->{$ref->{sess_key}});
461   }
462
463   $sth->finish();
464
465   $main::lxdebug->leave_sub();
466
467   return SESSION_OK;
468 }
469
470 sub destroy_session {
471   $main::lxdebug->enter_sub();
472
473   my $self = shift;
474
475   if ($session_id) {
476     my $dbh = $self->dbconnect();
477
478     do_query($main::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
479     do_query($main::form, $dbh, qq|DELETE FROM auth.session WHERE id = ?|, $session_id);
480
481     $dbh->commit();
482
483     $session_id      = undef;
484     $self->{SESSION} = { };
485   }
486
487   $main::lxdebug->leave_sub();
488 }
489
490 sub expire_sessions {
491   $main::lxdebug->enter_sub();
492
493   my $self  = shift;
494
495   my $dbh   = $self->dbconnect();
496   my $query =
497     qq|DELETE FROM auth.session_content
498        WHERE session_id IN
499          (SELECT id
500           FROM auth.session
501           WHERE (mtime < (now() - '$self->{session_timeout}m'::interval)))|;
502
503   do_query($main::form, $dbh, $query);
504
505   $query =
506     qq|DELETE FROM auth.session
507        WHERE (mtime < (now() - '$self->{session_timeout}m'::interval))|;
508
509   do_query($main::form, $dbh, $query);
510
511   $dbh->commit();
512
513   $main::lxdebug->leave_sub();
514 }
515
516 sub _create_session_id {
517   $main::lxdebug->enter_sub();
518
519   my @secs = gettimeofday();
520   srand $secs[1] + $$;
521
522   my @data;
523   map { push @data, int(rand() * 255); } (1..32);
524
525   my $id = md5_hex(pack 'C*', @data);
526
527   $main::lxdebug->leave_sub();
528
529   return $id;
530 }
531
532 sub create_or_refresh_session {
533   $main::lxdebug->enter_sub();
534
535   my $self = shift;
536
537   $session_id ||= $self->_create_session_id();
538
539   my ($form, $dbh, $query, $sth, $id);
540
541   $form  = $main::form;
542   $dbh   = $self->dbconnect();
543
544   $query = qq|SELECT id FROM auth.session WHERE id = ?|;
545
546   ($id)  = selectrow_query($form, $dbh, $query, $session_id);
547
548   if ($id) {
549     do_query($form, $dbh, qq|UPDATE auth.session SET mtime = now() WHERE id = ?|, $session_id);
550     do_query($form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
551
552   } else {
553     do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
554
555   }
556
557   $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
558   $sth   = prepare_query($form, $dbh, $query);
559
560   foreach my $key (sort keys %{ $self->{SESSION} }) {
561     do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
562   }
563
564   $sth->finish();
565   $dbh->commit();
566
567   $main::lxdebug->leave_sub();
568 }
569
570 sub set_session_value {
571   $main::lxdebug->enter_sub();
572
573   my $self  = shift;
574
575   $self->{SESSION} ||= { };
576
577   while (2 <= scalar @_) {
578     my $key   = shift;
579     my $value = shift;
580
581     $self->{SESSION}->{$key} = $value;
582   }
583
584   $main::lxdebug->leave_sub();
585 }
586
587 sub set_cookie_environment_variable {
588   my $self = shift;
589   $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
590 }
591
592 sub get_session_cookie_name {
593   my $self = shift;
594
595   return $self->{cookie_name} || 'lx_office_erp_session_id';
596 }
597
598 sub get_session_id {
599   return $session_id;
600 }
601
602 sub session_tables_present {
603   $main::lxdebug->enter_sub();
604
605   my $self = shift;
606   my $dbh  = $self->dbconnect(1);
607
608   if (!$dbh) {
609     $main::lxdebug->leave_sub();
610     return 0;
611   }
612
613   my $query =
614     qq|SELECT COUNT(*)
615        FROM pg_tables
616        WHERE (schemaname = 'auth')
617          AND (tablename IN ('session', 'session_content'))|;
618
619   my ($count) = selectrow_query($main::form, $dbh, $query);
620
621   $main::lxdebug->leave_sub();
622
623   return 2 == $count;
624 }
625
626 # --------------------------------------
627
628 sub all_rights_full {
629   my $locale = $main::locale;
630
631   my @all_rights = (
632     ["--crm",                          $locale->text("CRM optional software")], 
633     ["crm_search",                     $locale->text("CRM search")], 
634     ["crm_new",                        $locale->text("CRM create customers, vendors and contacts")], 
635     ["crm_service",                    $locale->text("CRM services")], 
636     ["crm_admin",                      $locale->text("CRM admin")], 
637     ["crm_adminuser",                  $locale->text("CRM user")], 
638     ["crm_adminstatus",                $locale->text("CRM status")], 
639     ["crm_email",                      $locale->text("CRM send email")], 
640     ["crm_termin",                     $locale->text("CRM termin")], 
641     ["crm_opportunity",                $locale->text("CRM opportunity")], 
642     ["crm_knowhow",                    $locale->text("CRM know how")], 
643     ["crm_follow",                     $locale->text("CRM follow up")], 
644     ["crm_notices",                    $locale->text("CRM notices")], 
645     ["crm_other",                      $locale->text("CRM other")], 
646     ["--master_data",                  $locale->text("Master Data")],
647     ["customer_vendor_edit",           $locale->text("Create and edit customers and vendors")],
648     ["part_service_assembly_edit",     $locale->text("Create and edit parts, services, assemblies")],
649     ["project_edit",                   $locale->text("Create and edit projects")],
650     ["license_edit",                   $locale->text("Manage license keys")],
651     ["--ar",                           $locale->text("AR")],
652     ["sales_quotation_edit",           $locale->text("Create and edit sales quotations")],
653     ["sales_order_edit",               $locale->text("Create and edit sales orders")],
654     ["sales_delivery_order_edit",      $locale->text("Create and edit sales delivery orders")],
655     ["invoice_edit",                   $locale->text("Create and edit invoices and credit notes")],
656     ["dunning_edit",                   $locale->text("Create and edit dunnings")],
657     ["--ap",                           $locale->text("AP")],
658     ["request_quotation_edit",         $locale->text("Create and edit RFQs")],
659     ["purchase_order_edit",            $locale->text("Create and edit purchase orders")],
660     ["purchase_delivery_order_edit",   $locale->text("Create and edit purchase delivery orders")],
661     ["vendor_invoice_edit",            $locale->text("Create and edit vendor invoices")],
662     ["--warehouse_management",         $locale->text("Warehouse management")],
663     ["warehouse_contents",             $locale->text("View warehouse content")],
664     ["warehouse_management",           $locale->text("Warehouse management")],
665     ["--general_ledger_cash",          $locale->text("General ledger and cash")],
666     ["general_ledger",                 $locale->text("Transactions, AR transactions, AP transactions")],
667     ["datev_export",                   $locale->text("DATEV Export")],
668     ["cash",                           $locale->text("Receipt, payment, reconciliation")],
669     ["--reports",                      $locale->text('Reports')],
670     ["report",                         $locale->text('All reports')],
671     ["advance_turnover_tax_return",    $locale->text('Advance turnover tax return')],
672     ["--others",                       $locale->text("Others")],
673     ["email_bcc",                      $locale->text("May set the BCC field when sending emails")],
674     ["config",                         $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
675     );
676
677   return @all_rights;
678 }
679
680 sub all_rights {
681   return grep !/^--/, map { $_->[0] } all_rights_full();
682 }
683
684 sub read_groups {
685   $main::lxdebug->enter_sub();
686
687   my $self = shift;
688
689   my $form   = $main::form;
690   my $groups = {};
691   my $dbh    = $self->dbconnect();
692
693   my $query  = 'SELECT * FROM auth."group"';
694   my $sth    = prepare_execute_query($form, $dbh, $query);
695
696   my ($row, $group);
697
698   while ($row = $sth->fetchrow_hashref()) {
699     $groups->{$row->{id}} = $row;
700   }
701   $sth->finish();
702
703   $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
704   $sth   = prepare_query($form, $dbh, $query);
705
706   foreach $group (values %{$groups}) {
707     $group->{members} = [];
708
709     do_statement($form, $sth, $query, $group->{id});
710
711     while ($row = $sth->fetchrow_hashref()) {
712       push @{$group->{members}}, $row->{user_id};
713     }
714   }
715   $sth->finish();
716
717   $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
718   $sth   = prepare_query($form, $dbh, $query);
719
720   foreach $group (values %{$groups}) {
721     $group->{rights} = {};
722
723     do_statement($form, $sth, $query, $group->{id});
724
725     while ($row = $sth->fetchrow_hashref()) {
726       $group->{rights}->{$row->{right}} |= $row->{granted};
727     }
728
729     map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
730   }
731   $sth->finish();
732
733   $main::lxdebug->leave_sub();
734
735   return $groups;
736 }
737
738 sub save_group {
739   $main::lxdebug->enter_sub();
740
741   my $self  = shift;
742   my $group = shift;
743
744   my $form  = $main::form;
745   my $dbh   = $self->dbconnect();
746
747   my ($query, $sth, $row, $rights);
748
749   if (!$group->{id}) {
750     ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
751
752     $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
753     do_query($form, $dbh, $query, $group->{id});
754   }
755
756   do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
757
758   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
759
760   $query  = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
761   $sth    = prepare_query($form, $dbh, $query);
762
763   foreach my $user_id (@{ $group->{members} }) {
764     do_statement($form, $sth, $query, $user_id, $group->{id});
765   }
766   $sth->finish();
767
768   do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
769
770   $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
771   $sth   = prepare_query($form, $dbh, $query);
772
773   foreach my $right (keys %{ $group->{rights} }) {
774     do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
775   }
776   $sth->finish();
777
778   $dbh->commit();
779
780   $main::lxdebug->leave_sub();
781 }
782
783 sub delete_group {
784   $main::lxdebug->enter_sub();
785
786   my $self = shift;
787   my $id   = shift;
788
789   my $form = $main::from;
790
791   my $dbh  = $self->dbconnect();
792
793   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
794   do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
795   do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
796
797   $dbh->commit();
798
799   $main::lxdebug->leave_sub();
800 }
801
802 sub evaluate_rights_ary {
803   $main::lxdebug->enter_sub(2);
804
805   my $ary    = shift;
806
807   my $value  = 0;
808   my $action = '|';
809
810   foreach my $el (@{$ary}) {
811     if (ref $el eq "ARRAY") {
812       if ($action eq '|') {
813         $value |= evaluate_rights_ary($el);
814       } else {
815         $value &= evaluate_rights_ary($el);
816       }
817
818     } elsif (($el eq '&') || ($el eq '|')) {
819       $action = $el;
820
821     } elsif ($action eq '|') {
822       $value |= $el;
823
824     } else {
825       $value &= $el;
826
827     }
828   }
829
830   $main::lxdebug->enter_sub(2);
831
832   return $value;
833 }
834
835 sub _parse_rights_string {
836   $main::lxdebug->enter_sub(2);
837
838   my $self   = shift;
839
840   my $login  = shift;
841   my $access = shift;
842
843   my @stack;
844   my $cur_ary = [];
845
846   push @stack, $cur_ary;
847
848   while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
849     my $token = $1;
850     substr($access, 0, length $1) = "";
851
852     next if ($token =~ /\s/);
853
854     if ($token eq "(") {
855       my $new_cur_ary = [];
856       push @stack, $new_cur_ary;
857       push @{$cur_ary}, $new_cur_ary;
858       $cur_ary = $new_cur_ary;
859
860     } elsif ($token eq ")") {
861       pop @stack;
862
863       if (!@stack) {
864         $main::lxdebug->enter_sub(2);
865         return 0;
866       }
867
868       $cur_ary = $stack[-1];
869
870     } elsif (($token eq "|") || ($token eq "&")) {
871       push @{$cur_ary}, $token;
872
873     } else {
874       push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
875     }
876   }
877
878   my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
879
880   $main::lxdebug->enter_sub(2);
881
882   return $result;
883 }
884
885 sub check_right {
886   $main::lxdebug->enter_sub(2);
887
888   my $self    = shift;
889   my $login   = shift;
890   my $right   = shift;
891   my $default = shift;
892
893   $self->{FULL_RIGHTS}           ||= { };
894   $self->{FULL_RIGHTS}->{$login} ||= { };
895
896   if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
897     $self->{RIGHTS}           ||= { };
898     $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
899
900     $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
901   }
902
903   my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
904   $granted    = $default if (!defined $granted);
905
906   $main::lxdebug->leave_sub(2);
907
908   return $granted;
909 }
910
911 sub assert {
912   $main::lxdebug->enter_sub(2);
913
914   my $self       = shift;
915   my $right      = shift;
916   my $dont_abort = shift;
917
918   my $form       = $main::form;
919
920   if ($self->check_right($form->{login}, $right)) {
921     $main::lxdebug->leave_sub(2);
922     return 1;
923   }
924
925   if (!$dont_abort) {
926     delete $form->{title};
927     $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
928   }
929
930   $main::lxdebug->leave_sub(2);
931
932   return 0;
933 }
934
935 sub load_rights_for_user {
936   $main::lxdebug->enter_sub();
937
938   my $self  = shift;
939   my $login = shift;
940
941   my $form  = $main::form;
942   my $dbh   = $self->dbconnect();
943
944   my ($query, $sth, $row, $rights);
945
946   $rights = {};
947
948   $query =
949     qq|SELECT gr."right", gr.granted
950        FROM auth.group_rights gr
951        WHERE group_id IN
952          (SELECT ug.group_id
953           FROM auth.user_group ug
954           LEFT JOIN auth."user" u ON (ug.user_id = u.id)
955           WHERE u.login = ?)|;
956
957   $sth = prepare_execute_query($form, $dbh, $query, $login);
958
959   while ($row = $sth->fetchrow_hashref()) {
960     $rights->{$row->{right}} |= $row->{granted};
961   }
962   $sth->finish();
963
964   map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
965
966   $main::lxdebug->leave_sub();
967
968   return $rights;
969 }
970
971 1;