]> wagnertech.de Git - mfinanz.git/blob - SL/Auth.pm
1202887553a4dca34c261d7b1f0bef0bab48831b
[mfinanz.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
601   } else {
602     do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
603
604   }
605
606   $self->save_session($dbh);
607
608   $dbh->commit();
609
610   $main::lxdebug->leave_sub();
611 }
612
613 sub save_session {
614   my $self         = shift;
615   my $provided_dbh = shift;
616
617   my $dbh          = $provided_dbh || $self->dbconnect();
618
619   do_query($::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
620
621   if (%{ $self->{SESSION} }) {
622     my $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
623     my $sth   = prepare_query($::form, $dbh, $query);
624
625     foreach my $key (sort keys %{ $self->{SESSION} }) {
626       do_statement($::form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
627     }
628
629     $sth->finish();
630   }
631
632   $dbh->commit() unless $provided_dbh;
633 }
634
635 sub set_session_value {
636   $main::lxdebug->enter_sub();
637
638   my $self   = shift;
639   my %params = @_;
640
641   $self->{SESSION} ||= { };
642
643   while (my ($key, $value) = each %params) {
644     $self->{SESSION}->{ $key } = YAML::Dump($value);
645   }
646
647   $main::lxdebug->leave_sub();
648
649   return $self;
650 }
651
652 sub delete_session_value {
653   $main::lxdebug->enter_sub();
654
655   my $self = shift;
656
657   $self->{SESSION} ||= { };
658   delete @{ $self->{SESSION} }{ @_ };
659
660   $main::lxdebug->leave_sub();
661
662   return $self;
663 }
664
665 sub get_session_value {
666   $main::lxdebug->enter_sub();
667
668   my $self  = shift;
669   my $value = $self->{SESSION} ? $self->_load_value($self->{SESSION}->{ $_[0] }) : undef;
670
671   $main::lxdebug->leave_sub();
672
673   return $value;
674 }
675
676 sub set_cookie_environment_variable {
677   my $self = shift;
678   $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
679 }
680
681 sub get_session_cookie_name {
682   my $self = shift;
683
684   return $self->{cookie_name} || 'lx_office_erp_session_id';
685 }
686
687 sub get_session_id {
688   return $session_id;
689 }
690
691 sub session_tables_present {
692   $main::lxdebug->enter_sub();
693
694   my $self = shift;
695   my $dbh  = $self->dbconnect(1);
696
697   if (!$dbh) {
698     $main::lxdebug->leave_sub();
699     return 0;
700   }
701
702   my $query =
703     qq|SELECT COUNT(*)
704        FROM pg_tables
705        WHERE (schemaname = 'auth')
706          AND (tablename IN ('session', 'session_content'))|;
707
708   my ($count) = selectrow_query($main::form, $dbh, $query);
709
710   $main::lxdebug->leave_sub();
711
712   return 2 == $count;
713 }
714
715 # --------------------------------------
716
717 sub all_rights_full {
718   my $locale = $main::locale;
719
720   my @all_rights = (
721     ["--crm",                          $locale->text("CRM optional software")],
722     ["crm_search",                     $locale->text("CRM search")],
723     ["crm_new",                        $locale->text("CRM create customers, vendors and contacts")],
724     ["crm_service",                    $locale->text("CRM services")],
725     ["crm_admin",                      $locale->text("CRM admin")],
726     ["crm_adminuser",                  $locale->text("CRM user")],
727     ["crm_adminstatus",                $locale->text("CRM status")],
728     ["crm_email",                      $locale->text("CRM send email")],
729     ["crm_termin",                     $locale->text("CRM termin")],
730     ["crm_opportunity",                $locale->text("CRM opportunity")],
731     ["crm_knowhow",                    $locale->text("CRM know how")],
732     ["crm_follow",                     $locale->text("CRM follow up")],
733     ["crm_notices",                    $locale->text("CRM notices")],
734     ["crm_other",                      $locale->text("CRM other")],
735     ["--master_data",                  $locale->text("Master Data")],
736     ["customer_vendor_edit",           $locale->text("Create and edit customers and vendors")],
737     ["part_service_assembly_edit",     $locale->text("Create and edit parts, services, assemblies")],
738     ["project_edit",                   $locale->text("Create and edit projects")],
739     ["license_edit",                   $locale->text("Manage license keys")],
740     ["--ar",                           $locale->text("AR")],
741     ["sales_quotation_edit",           $locale->text("Create and edit sales quotations")],
742     ["sales_order_edit",               $locale->text("Create and edit sales orders")],
743     ["sales_delivery_order_edit",      $locale->text("Create and edit sales delivery orders")],
744     ["invoice_edit",                   $locale->text("Create and edit invoices and credit notes")],
745     ["dunning_edit",                   $locale->text("Create and edit dunnings")],
746     ["sales_all_edit",                 $locale->text("View/edit all employees sales documents")],
747     ["--ap",                           $locale->text("AP")],
748     ["request_quotation_edit",         $locale->text("Create and edit RFQs")],
749     ["purchase_order_edit",            $locale->text("Create and edit purchase orders")],
750     ["purchase_delivery_order_edit",   $locale->text("Create and edit purchase delivery orders")],
751     ["vendor_invoice_edit",            $locale->text("Create and edit vendor invoices")],
752     ["--warehouse_management",         $locale->text("Warehouse management")],
753     ["warehouse_contents",             $locale->text("View warehouse content")],
754     ["warehouse_management",           $locale->text("Warehouse management")],
755     ["--general_ledger_cash",          $locale->text("General ledger and cash")],
756     ["general_ledger",                 $locale->text("Transactions, AR transactions, AP transactions")],
757     ["datev_export",                   $locale->text("DATEV Export")],
758     ["cash",                           $locale->text("Receipt, payment, reconciliation")],
759     ["--reports",                      $locale->text('Reports')],
760     ["report",                         $locale->text('All reports')],
761     ["advance_turnover_tax_return",    $locale->text('Advance turnover tax return')],
762     ["--batch_printing",               $locale->text("Batch Printing")],
763     ["batch_printing",                 $locale->text("Batch Printing")],
764     ["--others",                       $locale->text("Others")],
765     ["email_bcc",                      $locale->text("May set the BCC field when sending emails")],
766     ["config",                         $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
767     );
768
769   return @all_rights;
770 }
771
772 sub all_rights {
773   return grep !/^--/, map { $_->[0] } all_rights_full();
774 }
775
776 sub read_groups {
777   $main::lxdebug->enter_sub();
778
779   my $self = shift;
780
781   my $form   = $main::form;
782   my $groups = {};
783   my $dbh    = $self->dbconnect();
784
785   my $query  = 'SELECT * FROM auth."group"';
786   my $sth    = prepare_execute_query($form, $dbh, $query);
787
788   my ($row, $group);
789
790   while ($row = $sth->fetchrow_hashref()) {
791     $groups->{$row->{id}} = $row;
792   }
793   $sth->finish();
794
795   $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
796   $sth   = prepare_query($form, $dbh, $query);
797
798   foreach $group (values %{$groups}) {
799     my @members;
800
801     do_statement($form, $sth, $query, $group->{id});
802
803     while ($row = $sth->fetchrow_hashref()) {
804       push @members, $row->{user_id};
805     }
806     $group->{members} = [ uniq @members ];
807   }
808   $sth->finish();
809
810   $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
811   $sth   = prepare_query($form, $dbh, $query);
812
813   foreach $group (values %{$groups}) {
814     $group->{rights} = {};
815
816     do_statement($form, $sth, $query, $group->{id});
817
818     while ($row = $sth->fetchrow_hashref()) {
819       $group->{rights}->{$row->{right}} |= $row->{granted};
820     }
821
822     map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
823   }
824   $sth->finish();
825
826   $main::lxdebug->leave_sub();
827
828   return $groups;
829 }
830
831 sub save_group {
832   $main::lxdebug->enter_sub();
833
834   my $self  = shift;
835   my $group = shift;
836
837   my $form  = $main::form;
838   my $dbh   = $self->dbconnect();
839
840   my ($query, $sth, $row, $rights);
841
842   if (!$group->{id}) {
843     ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
844
845     $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
846     do_query($form, $dbh, $query, $group->{id});
847   }
848
849   do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
850
851   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
852
853   $query  = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
854   $sth    = prepare_query($form, $dbh, $query);
855
856   foreach my $user_id (uniq @{ $group->{members} }) {
857     do_statement($form, $sth, $query, $user_id, $group->{id});
858   }
859   $sth->finish();
860
861   do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
862
863   $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
864   $sth   = prepare_query($form, $dbh, $query);
865
866   foreach my $right (keys %{ $group->{rights} }) {
867     do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
868   }
869   $sth->finish();
870
871   $dbh->commit();
872
873   $main::lxdebug->leave_sub();
874 }
875
876 sub delete_group {
877   $main::lxdebug->enter_sub();
878
879   my $self = shift;
880   my $id   = shift;
881
882   my $form = $main::from;
883
884   my $dbh  = $self->dbconnect();
885
886   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
887   do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
888   do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
889
890   $dbh->commit();
891
892   $main::lxdebug->leave_sub();
893 }
894
895 sub evaluate_rights_ary {
896   $main::lxdebug->enter_sub(2);
897
898   my $ary    = shift;
899
900   my $value  = 0;
901   my $action = '|';
902
903   foreach my $el (@{$ary}) {
904     if (ref $el eq "ARRAY") {
905       if ($action eq '|') {
906         $value |= evaluate_rights_ary($el);
907       } else {
908         $value &= evaluate_rights_ary($el);
909       }
910
911     } elsif (($el eq '&') || ($el eq '|')) {
912       $action = $el;
913
914     } elsif ($action eq '|') {
915       $value |= $el;
916
917     } else {
918       $value &= $el;
919
920     }
921   }
922
923   $main::lxdebug->leave_sub(2);
924
925   return $value;
926 }
927
928 sub _parse_rights_string {
929   $main::lxdebug->enter_sub(2);
930
931   my $self   = shift;
932
933   my $login  = shift;
934   my $access = shift;
935
936   my @stack;
937   my $cur_ary = [];
938
939   push @stack, $cur_ary;
940
941   while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
942     my $token = $1;
943     substr($access, 0, length $1) = "";
944
945     next if ($token =~ /\s/);
946
947     if ($token eq "(") {
948       my $new_cur_ary = [];
949       push @stack, $new_cur_ary;
950       push @{$cur_ary}, $new_cur_ary;
951       $cur_ary = $new_cur_ary;
952
953     } elsif ($token eq ")") {
954       pop @stack;
955
956       if (!@stack) {
957         $main::lxdebug->leave_sub(2);
958         return 0;
959       }
960
961       $cur_ary = $stack[-1];
962
963     } elsif (($token eq "|") || ($token eq "&")) {
964       push @{$cur_ary}, $token;
965
966     } else {
967       push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
968     }
969   }
970
971   my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
972
973   $main::lxdebug->leave_sub(2);
974
975   return $result;
976 }
977
978 sub check_right {
979   $main::lxdebug->enter_sub(2);
980
981   my $self    = shift;
982   my $login   = shift;
983   my $right   = shift;
984   my $default = shift;
985
986   $self->{FULL_RIGHTS}           ||= { };
987   $self->{FULL_RIGHTS}->{$login} ||= { };
988
989   if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
990     $self->{RIGHTS}           ||= { };
991     $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
992
993     $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
994   }
995
996   my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
997   $granted    = $default if (!defined $granted);
998
999   $main::lxdebug->leave_sub(2);
1000
1001   return $granted;
1002 }
1003
1004 sub assert {
1005   $main::lxdebug->enter_sub(2);
1006
1007   my $self       = shift;
1008   my $right      = shift;
1009   my $dont_abort = shift;
1010
1011   my $form       = $main::form;
1012
1013   if ($self->check_right($form->{login}, $right)) {
1014     $main::lxdebug->leave_sub(2);
1015     return 1;
1016   }
1017
1018   if (!$dont_abort) {
1019     delete $form->{title};
1020     $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
1021   }
1022
1023   $main::lxdebug->leave_sub(2);
1024
1025   return 0;
1026 }
1027
1028 sub load_rights_for_user {
1029   $main::lxdebug->enter_sub();
1030
1031   my $self  = shift;
1032   my $login = shift;
1033
1034   my $form  = $main::form;
1035   my $dbh   = $self->dbconnect();
1036
1037   my ($query, $sth, $row, $rights);
1038
1039   $rights = {};
1040
1041   $query =
1042     qq|SELECT gr."right", gr.granted
1043        FROM auth.group_rights gr
1044        WHERE group_id IN
1045          (SELECT ug.group_id
1046           FROM auth.user_group ug
1047           LEFT JOIN auth."user" u ON (ug.user_id = u.id)
1048           WHERE u.login = ?)|;
1049
1050   $sth = prepare_execute_query($form, $dbh, $query, $login);
1051
1052   while ($row = $sth->fetchrow_hashref()) {
1053     $rights->{$row->{right}} |= $row->{granted};
1054   }
1055   $sth->finish();
1056
1057   map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
1058
1059   $main::lxdebug->leave_sub();
1060
1061   return $rights;
1062 }
1063
1064 1;