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