4 use constant ERR_PASSWORD => 1;
5 use constant ERR_BACKEND => 100;
7 use constant SESSION_OK => 0;
8 use constant SESSION_NONE => 1;
9 use constant SESSION_EXPIRED => 2;
11 use Digest::MD5 qw(md5_hex);
13 use Time::HiRes qw(gettimeofday);
14 use List::MoreUtils qw(uniq);
25 $main::lxdebug->enter_sub();
32 $self->{SESSION} = { };
34 $self->_read_auth_config();
36 $main::lxdebug->leave_sub();
44 $self->{dbh}->disconnect() if ($self->{dbh});
47 sub _read_auth_config {
48 $main::lxdebug->enter_sub();
52 my $form = $main::form;
53 my $locale = $main::locale;
56 my $in = IO::File->new('config/authentication.pl', 'r');
59 $form->error($locale->text('The config file "config/authentication.pl" was not found.'));
70 $form->error($locale->text('The config file "config/authentication.pl" contained invalid Perl code:') . "\n" . $@);
73 if ($self->{module} eq 'DB') {
74 $self->{authenticator} = SL::Auth::DB->new($self);
76 } elsif ($self->{module} eq 'LDAP') {
77 $self->{authenticator} = SL::Auth::LDAP->new($self);
80 if (!$self->{authenticator}) {
81 $form->error($locale->text('No or an unknown authenticantion module specified in "config/authentication.pl".'));
84 my $cfg = $self->{DB_config};
87 $form->error($locale->text('config/authentication.pl: Key "DB_config" is missing.'));
90 if (!$cfg->{host} || !$cfg->{db} || !$cfg->{user}) {
91 $form->error($locale->text('config/authentication.pl: Missing parameters in "DB_config". Required parameters are "host", "db" and "user".'));
94 $self->{authenticator}->verify_config();
96 $self->{session_timeout} *= 1;
97 $self->{session_timeout} = 8 * 60 if (!$self->{session_timeout});
99 $main::lxdebug->leave_sub();
102 sub authenticate_root {
103 $main::lxdebug->enter_sub();
106 my $password = shift;
107 my $is_crypted = shift;
109 $password = crypt $password, 'ro' if (!$password || !$is_crypted);
110 my $admin_password = crypt "$self->{admin_password}", 'ro';
112 $main::lxdebug->leave_sub();
114 return $password eq $admin_password ? OK : ERR_PASSWORD;
118 $main::lxdebug->enter_sub();
122 $main::lxdebug->leave_sub();
124 return $self->{authenticator}->authenticate(@_);
128 $main::lxdebug->enter_sub(2);
131 my $may_fail = shift;
134 $main::lxdebug->leave_sub(2);
138 my $cfg = $self->{DB_config};
139 my $dsn = 'dbi:Pg:dbname=' . $cfg->{db} . ';host=' . $cfg->{host};
142 $dsn .= ';port=' . $cfg->{port};
145 $main::lxdebug->message(LXDebug->DEBUG1, "Auth::dbconnect DSN: $dsn");
147 $self->{dbh} = DBI->connect($dsn, $cfg->{user}, $cfg->{password}, { 'AutoCommit' => 0 });
149 if (!$may_fail && !$self->{dbh}) {
150 $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr);
153 $main::lxdebug->leave_sub();
159 $main::lxdebug->enter_sub();
164 $self->{dbh}->disconnect();
168 $main::lxdebug->leave_sub();
172 $main::lxdebug->enter_sub();
176 my $dbh = $self->dbconnect();
177 my $query = qq|SELECT COUNT(*) FROM pg_tables WHERE (schemaname = 'auth') AND (tablename = 'user')|;
179 my ($count) = $dbh->selectrow_array($query);
181 $main::lxdebug->leave_sub();
187 $main::lxdebug->enter_sub();
191 my $dbh = $self->dbconnect(1);
193 $main::lxdebug->leave_sub();
198 sub create_database {
199 $main::lxdebug->enter_sub();
204 my $cfg = $self->{DB_config};
206 if (!$params{superuser}) {
207 $params{superuser} = $cfg->{user};
208 $params{superuser_password} = $cfg->{password};
211 $params{template} ||= 'template0';
212 $params{template} =~ s|[^a-zA-Z0-9_\-]||g;
214 my $dsn = 'dbi:Pg:dbname=template1;host=' . $cfg->{host};
217 $dsn .= ';port=' . $cfg->{port};
220 $main::lxdebug->message(LXDebug->DEBUG1(), "Auth::create_database DSN: $dsn");
222 my $dbh = DBI->connect($dsn, $params{superuser}, $params{superuser_password});
225 $main::form->error($main::locale->text('The connection to the template database failed:') . "\n" . $DBI::errstr);
228 my $charset = $main::dbcharset;
229 $charset ||= Common::DEFAULT_CHARSET;
230 my $encoding = $Common::charset_to_db_encoding{$charset};
231 $encoding ||= 'UNICODE';
233 my $query = qq|CREATE DATABASE "$cfg->{db}" OWNER "$cfg->{user}" TEMPLATE "$params{template}" ENCODING '$encoding'|;
235 $main::lxdebug->message(LXDebug->DEBUG1(), "Auth::create_database query: $query");
240 my $error = $dbh->errstr();
242 $query = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
243 my ($cluster_encoding) = $dbh->selectrow_array($query);
245 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i) && ($encoding !~ m/^(?:UTF-?8|UNICODE)$/i)) {
246 $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.');
251 $main::form->error($main::locale->text('The creation of the authentication database failed:') . "\n" . $error);
256 $main::lxdebug->leave_sub();
260 $main::lxdebug->enter_sub();
263 my $dbh = $self->dbconnect();
265 my $charset = $main::dbcharset;
266 $charset ||= Common::DEFAULT_CHARSET;
269 User->process_query($main::form, $dbh, 'sql/auth_db.sql', undef, $charset);
271 $main::lxdebug->leave_sub();
275 $main::lxdebug->enter_sub();
281 my $form = $main::form;
283 my $dbh = $self->dbconnect();
285 my ($sth, $query, $user_id);
287 $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
288 ($user_id) = selectrow_query($form, $dbh, $query, $login);
291 $query = qq|SELECT nextval('auth.user_id_seq')|;
292 ($user_id) = selectrow_query($form, $dbh, $query);
294 $query = qq|INSERT INTO auth."user" (id, login) VALUES (?, ?)|;
295 do_query($form, $dbh, $query, $user_id, $login);
298 $query = qq|DELETE FROM auth.user_config WHERE (user_id = ?)|;
299 do_query($form, $dbh, $query, $user_id);
301 $query = qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (?, ?, ?)|;
302 $sth = prepare_query($form, $dbh, $query);
304 while (my ($cfg_key, $cfg_value) = each %params) {
305 next if ($cfg_key eq 'password');
307 do_statement($form, $sth, $query, $user_id, $cfg_key, $cfg_value);
312 $main::lxdebug->leave_sub();
315 sub can_change_password {
318 return $self->{authenticator}->can_change_password();
321 sub change_password {
322 $main::lxdebug->enter_sub();
325 my $result = $self->{authenticator}->change_password(@_);
327 $main::lxdebug->leave_sub();
333 $main::lxdebug->enter_sub();
337 my $dbh = $self->dbconnect();
338 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
339 FROM auth.user_config cfg
340 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)|;
341 my $sth = prepare_execute_query($main::form, $dbh, $query);
345 while (my $ref = $sth->fetchrow_hashref()) {
346 $users{$ref->{login}} ||= { 'login' => $ref->{login}, 'id' => $ref->{id} };
347 $users{$ref->{login}}->{$ref->{cfg_key}} = $ref->{cfg_value} if (($ref->{cfg_key} ne 'login') && ($ref->{cfg_key} ne 'id'));
352 $main::lxdebug->leave_sub();
358 $main::lxdebug->enter_sub();
363 my $dbh = $self->dbconnect();
364 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
365 FROM auth.user_config cfg
366 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)
367 WHERE (u.login = ?)|;
368 my $sth = prepare_execute_query($main::form, $dbh, $query, $login);
372 while (my $ref = $sth->fetchrow_hashref()) {
373 $user_data{$ref->{cfg_key}} = $ref->{cfg_value};
374 @user_data{qw(id login)} = @{$ref}{qw(id login)};
379 $main::lxdebug->leave_sub();
385 $main::lxdebug->enter_sub();
390 my $dbh = $self->dbconnect();
391 my ($id) = selectrow_query($main::form, $dbh, qq|SELECT id FROM auth."user" WHERE login = ?|, $login);
393 $main::lxdebug->leave_sub();
399 $main::lxdebug->enter_sub();
404 my $form = $main::form;
406 my $dbh = $self->dbconnect();
407 my $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
409 my ($id) = selectrow_query($form, $dbh, $query, $login);
411 return $main::lxdebug->leave_sub() if (!$id);
413 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE user_id = ?|, $id);
414 do_query($form, $dbh, qq|DELETE FROM auth.user_config WHERE user_id = ?|, $id);
418 $main::lxdebug->leave_sub();
421 # --------------------------------------
425 sub restore_session {
426 $main::lxdebug->enter_sub();
430 my $cgi = $main::cgi;
431 $cgi ||= CGI->new('');
433 $session_id = $cgi->cookie($self->get_session_cookie_name());
434 $session_id =~ s|[^0-9a-f]||g;
436 $self->{SESSION} = { };
439 $main::lxdebug->leave_sub();
443 my ($dbh, $query, $sth, $cookie, $ref, $form);
447 $dbh = $self->dbconnect();
448 $query = qq|SELECT *, (mtime < (now() - '$self->{session_timeout}m'::interval)) AS is_expired FROM auth.session WHERE id = ?|;
450 $cookie = selectfirst_hashref_query($form, $dbh, $query, $session_id);
452 if (!$cookie || $cookie->{is_expired} || ($cookie->{ip_address} ne $ENV{REMOTE_ADDR})) {
453 $self->destroy_session();
454 $main::lxdebug->leave_sub();
455 return SESSION_EXPIRED;
458 $query = qq|SELECT sess_key, sess_value FROM auth.session_content WHERE session_id = ?|;
459 $sth = prepare_execute_query($form, $dbh, $query, $session_id);
461 while (my $ref = $sth->fetchrow_hashref()) {
462 $self->{SESSION}->{$ref->{sess_key}} = $ref->{sess_value};
463 $form->{$ref->{sess_key}} = $ref->{sess_value} if (!defined $form->{$ref->{sess_key}});
468 $main::lxdebug->leave_sub();
473 sub destroy_session {
474 $main::lxdebug->enter_sub();
479 my $dbh = $self->dbconnect();
481 do_query($main::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
482 do_query($main::form, $dbh, qq|DELETE FROM auth.session WHERE id = ?|, $session_id);
487 $self->{SESSION} = { };
490 $main::lxdebug->leave_sub();
493 sub expire_sessions {
494 $main::lxdebug->enter_sub();
498 my $dbh = $self->dbconnect();
500 qq|DELETE FROM auth.session_content
504 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval)))|;
506 do_query($main::form, $dbh, $query);
509 qq|DELETE FROM auth.session
510 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval))|;
512 do_query($main::form, $dbh, $query);
516 $main::lxdebug->leave_sub();
519 sub _create_session_id {
520 $main::lxdebug->enter_sub();
523 map { push @data, int(rand() * 255); } (1..32);
525 my $id = md5_hex(pack 'C*', @data);
527 $main::lxdebug->leave_sub();
532 sub create_or_refresh_session {
533 $main::lxdebug->enter_sub();
537 $session_id ||= $self->_create_session_id();
539 my ($form, $dbh, $query, $sth, $id);
542 $dbh = $self->dbconnect();
544 $query = qq|SELECT id FROM auth.session WHERE id = ?|;
546 ($id) = selectrow_query($form, $dbh, $query, $session_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);
553 do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
557 $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
558 $sth = prepare_query($form, $dbh, $query);
560 foreach my $key (sort keys %{ $self->{SESSION} }) {
561 do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
567 $main::lxdebug->leave_sub();
570 sub set_session_value {
571 $main::lxdebug->enter_sub();
575 $self->{SESSION} ||= { };
577 while (2 <= scalar @_) {
581 $self->{SESSION}->{$key} = $value;
584 $main::lxdebug->leave_sub();
587 sub set_cookie_environment_variable {
589 $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
592 sub get_session_cookie_name {
595 return $self->{cookie_name} || 'lx_office_erp_session_id';
602 sub session_tables_present {
603 $main::lxdebug->enter_sub();
606 my $dbh = $self->dbconnect(1);
609 $main::lxdebug->leave_sub();
616 WHERE (schemaname = 'auth')
617 AND (tablename IN ('session', 'session_content'))|;
619 my ($count) = selectrow_query($main::form, $dbh, $query);
621 $main::lxdebug->leave_sub();
626 # --------------------------------------
628 sub all_rights_full {
629 my $locale = $main::locale;
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 ["sales_all_edit", $locale->text("View/edit all employees sales documents")],
658 ["--ap", $locale->text("AP")],
659 ["request_quotation_edit", $locale->text("Create and edit RFQs")],
660 ["purchase_order_edit", $locale->text("Create and edit purchase orders")],
661 ["purchase_delivery_order_edit", $locale->text("Create and edit purchase delivery orders")],
662 ["vendor_invoice_edit", $locale->text("Create and edit vendor invoices")],
663 ["--warehouse_management", $locale->text("Warehouse management")],
664 ["warehouse_contents", $locale->text("View warehouse content")],
665 ["warehouse_management", $locale->text("Warehouse management")],
666 ["--general_ledger_cash", $locale->text("General ledger and cash")],
667 ["general_ledger", $locale->text("Transactions, AR transactions, AP transactions")],
668 ["datev_export", $locale->text("DATEV Export")],
669 ["cash", $locale->text("Receipt, payment, reconciliation")],
670 ["--reports", $locale->text('Reports')],
671 ["report", $locale->text('All reports')],
672 ["advance_turnover_tax_return", $locale->text('Advance turnover tax return')],
673 ["--others", $locale->text("Others")],
674 ["email_bcc", $locale->text("May set the BCC field when sending emails")],
675 ["config", $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
682 return grep !/^--/, map { $_->[0] } all_rights_full();
686 $main::lxdebug->enter_sub();
690 my $form = $main::form;
692 my $dbh = $self->dbconnect();
694 my $query = 'SELECT * FROM auth."group"';
695 my $sth = prepare_execute_query($form, $dbh, $query);
699 while ($row = $sth->fetchrow_hashref()) {
700 $groups->{$row->{id}} = $row;
704 $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
705 $sth = prepare_query($form, $dbh, $query);
707 foreach $group (values %{$groups}) {
710 do_statement($form, $sth, $query, $group->{id});
712 while ($row = $sth->fetchrow_hashref()) {
713 push @members, $row->{user_id};
715 $group->{members} = [ uniq @members ];
719 $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
720 $sth = prepare_query($form, $dbh, $query);
722 foreach $group (values %{$groups}) {
723 $group->{rights} = {};
725 do_statement($form, $sth, $query, $group->{id});
727 while ($row = $sth->fetchrow_hashref()) {
728 $group->{rights}->{$row->{right}} |= $row->{granted};
731 map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
735 $main::lxdebug->leave_sub();
741 $main::lxdebug->enter_sub();
746 my $form = $main::form;
747 my $dbh = $self->dbconnect();
749 my ($query, $sth, $row, $rights);
752 ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
754 $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
755 do_query($form, $dbh, $query, $group->{id});
758 do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
760 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
762 $query = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
763 $sth = prepare_query($form, $dbh, $query);
765 foreach my $user_id (uniq @{ $group->{members} }) {
766 do_statement($form, $sth, $query, $user_id, $group->{id});
770 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
772 $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
773 $sth = prepare_query($form, $dbh, $query);
775 foreach my $right (keys %{ $group->{rights} }) {
776 do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
782 $main::lxdebug->leave_sub();
786 $main::lxdebug->enter_sub();
791 my $form = $main::from;
793 my $dbh = $self->dbconnect();
795 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
796 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
797 do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
801 $main::lxdebug->leave_sub();
804 sub evaluate_rights_ary {
805 $main::lxdebug->enter_sub(2);
812 foreach my $el (@{$ary}) {
813 if (ref $el eq "ARRAY") {
814 if ($action eq '|') {
815 $value |= evaluate_rights_ary($el);
817 $value &= evaluate_rights_ary($el);
820 } elsif (($el eq '&') || ($el eq '|')) {
823 } elsif ($action eq '|') {
832 $main::lxdebug->enter_sub(2);
837 sub _parse_rights_string {
838 $main::lxdebug->enter_sub(2);
848 push @stack, $cur_ary;
850 while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
852 substr($access, 0, length $1) = "";
854 next if ($token =~ /\s/);
857 my $new_cur_ary = [];
858 push @stack, $new_cur_ary;
859 push @{$cur_ary}, $new_cur_ary;
860 $cur_ary = $new_cur_ary;
862 } elsif ($token eq ")") {
866 $main::lxdebug->enter_sub(2);
870 $cur_ary = $stack[-1];
872 } elsif (($token eq "|") || ($token eq "&")) {
873 push @{$cur_ary}, $token;
876 push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
880 my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
882 $main::lxdebug->enter_sub(2);
888 $main::lxdebug->enter_sub(2);
895 $self->{FULL_RIGHTS} ||= { };
896 $self->{FULL_RIGHTS}->{$login} ||= { };
898 if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
899 $self->{RIGHTS} ||= { };
900 $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
902 $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
905 my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
906 $granted = $default if (!defined $granted);
908 $main::lxdebug->leave_sub(2);
914 $main::lxdebug->enter_sub(2);
918 my $dont_abort = shift;
920 my $form = $main::form;
922 if ($self->check_right($form->{login}, $right)) {
923 $main::lxdebug->leave_sub(2);
928 delete $form->{title};
929 $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
932 $main::lxdebug->leave_sub(2);
937 sub load_rights_for_user {
938 $main::lxdebug->enter_sub();
943 my $form = $main::form;
944 my $dbh = $self->dbconnect();
946 my ($query, $sth, $row, $rights);
951 qq|SELECT gr."right", gr.granted
952 FROM auth.group_rights gr
955 FROM auth.user_group ug
956 LEFT JOIN auth."user" u ON (ug.user_id = u.id)
959 $sth = prepare_execute_query($form, $dbh, $query, $login);
961 while ($row = $sth->fetchrow_hashref()) {
962 $rights->{$row->{right}} |= $row->{granted};
966 map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
968 $main::lxdebug->leave_sub();