5 use Digest::MD5 qw(md5_hex);
7 use Time::HiRes qw(gettimeofday);
8 use List::MoreUtils qw(uniq);
10 use SL::Auth::Constants qw(:all);
20 $main::lxdebug->enter_sub();
27 $self->{SESSION} = { };
29 $self->_read_auth_config();
31 $main::lxdebug->leave_sub();
37 my ($self, $login) = @_;
38 my %user = $self->read_user($login);
39 my $dbh = DBI->connect(
44 pg_enable_utf8 => $::locale->is_utf8,
47 ) or $::form->dberror;
49 if ($user{dboptions}) {
50 $dbh->do($user{dboptions}) or $::form->dberror($user{dboptions});
59 $self->{dbh}->disconnect() if ($self->{dbh});
62 sub _read_auth_config {
63 $main::lxdebug->enter_sub();
67 my $form = $main::form;
68 my $locale = $main::locale;
71 my $in = IO::File->new('config/authentication.pl', 'r');
74 $form->error($locale->text('The config file "config/authentication.pl" was not found.'));
85 $form->error($locale->text('The config file "config/authentication.pl" contained invalid Perl code:') . "\n" . $@);
88 if ($self->{module} eq 'DB') {
89 $self->{authenticator} = SL::Auth::DB->new($self);
91 } elsif ($self->{module} eq 'LDAP') {
92 $self->{authenticator} = SL::Auth::LDAP->new($self);
95 if (!$self->{authenticator}) {
96 $form->error($locale->text('No or an unknown authenticantion module specified in "config/authentication.pl".'));
99 my $cfg = $self->{DB_config};
102 $form->error($locale->text('config/authentication.pl: Key "DB_config" is missing.'));
105 if (!$cfg->{host} || !$cfg->{db} || !$cfg->{user}) {
106 $form->error($locale->text('config/authentication.pl: Missing parameters in "DB_config". Required parameters are "host", "db" and "user".'));
109 $self->{authenticator}->verify_config();
111 $self->{session_timeout} *= 1;
112 $self->{session_timeout} = 8 * 60 if (!$self->{session_timeout});
114 $main::lxdebug->leave_sub();
117 sub authenticate_root {
118 $main::lxdebug->enter_sub();
121 my $password = shift;
122 my $is_crypted = shift;
124 $password = crypt $password, 'ro' if (!$password || !$is_crypted);
125 my $admin_password = crypt "$self->{admin_password}", 'ro';
127 $main::lxdebug->leave_sub();
129 return $password eq $admin_password ? OK : ERR_PASSWORD;
133 $main::lxdebug->enter_sub();
137 $main::lxdebug->leave_sub();
139 return $self->{authenticator}->authenticate(@_);
143 $main::lxdebug->enter_sub(2);
146 my $may_fail = shift;
149 $main::lxdebug->leave_sub(2);
153 my $cfg = $self->{DB_config};
154 my $dsn = 'dbi:Pg:dbname=' . $cfg->{db} . ';host=' . $cfg->{host};
157 $dsn .= ';port=' . $cfg->{port};
160 $main::lxdebug->message(LXDebug->DEBUG1, "Auth::dbconnect DSN: $dsn");
162 $self->{dbh} = DBI->connect($dsn, $cfg->{user}, $cfg->{password}, { pg_enable_utf8 => $::locale->is_utf8, AutoCommit => 0 });
164 if (!$may_fail && !$self->{dbh}) {
165 $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr);
168 $main::lxdebug->leave_sub();
174 $main::lxdebug->enter_sub();
179 $self->{dbh}->disconnect();
183 $main::lxdebug->leave_sub();
187 $main::lxdebug->enter_sub();
191 my $dbh = $self->dbconnect();
192 my $query = qq|SELECT COUNT(*) FROM pg_tables WHERE (schemaname = 'auth') AND (tablename = 'user')|;
194 my ($count) = $dbh->selectrow_array($query);
196 $main::lxdebug->leave_sub();
202 $main::lxdebug->enter_sub();
206 my $dbh = $self->dbconnect(1);
208 $main::lxdebug->leave_sub();
213 sub create_database {
214 $main::lxdebug->enter_sub();
219 my $cfg = $self->{DB_config};
221 if (!$params{superuser}) {
222 $params{superuser} = $cfg->{user};
223 $params{superuser_password} = $cfg->{password};
226 $params{template} ||= 'template0';
227 $params{template} =~ s|[^a-zA-Z0-9_\-]||g;
229 my $dsn = 'dbi:Pg:dbname=template1;host=' . $cfg->{host};
232 $dsn .= ';port=' . $cfg->{port};
235 $main::lxdebug->message(LXDebug->DEBUG1(), "Auth::create_database DSN: $dsn");
237 my $charset = $main::dbcharset;
238 $charset ||= Common::DEFAULT_CHARSET;
239 my $encoding = $Common::charset_to_db_encoding{$charset};
240 $encoding ||= 'UNICODE';
242 my $dbh = DBI->connect($dsn, $params{superuser}, $params{superuser_password}, { pg_enable_utf8 => $charset =~ m/^utf-?8$/i });
245 $main::form->error($main::locale->text('The connection to the template database failed:') . "\n" . $DBI::errstr);
248 my $query = qq|CREATE DATABASE "$cfg->{db}" OWNER "$cfg->{user}" TEMPLATE "$params{template}" ENCODING '$encoding'|;
250 $main::lxdebug->message(LXDebug->DEBUG1(), "Auth::create_database query: $query");
255 my $error = $dbh->errstr();
257 $query = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
258 my ($cluster_encoding) = $dbh->selectrow_array($query);
260 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i) && ($encoding !~ m/^(?:UTF-?8|UNICODE)$/i)) {
261 $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.');
266 $main::form->error($main::locale->text('The creation of the authentication database failed:') . "\n" . $error);
271 $main::lxdebug->leave_sub();
275 $main::lxdebug->enter_sub();
278 my $dbh = $self->dbconnect();
280 my $charset = $main::dbcharset;
281 $charset ||= Common::DEFAULT_CHARSET;
284 User->process_query($main::form, $dbh, 'sql/auth_db.sql', undef, $charset);
286 $main::lxdebug->leave_sub();
290 $main::lxdebug->enter_sub();
296 my $form = $main::form;
298 my $dbh = $self->dbconnect();
300 my ($sth, $query, $user_id);
302 $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
303 ($user_id) = selectrow_query($form, $dbh, $query, $login);
306 $query = qq|SELECT nextval('auth.user_id_seq')|;
307 ($user_id) = selectrow_query($form, $dbh, $query);
309 $query = qq|INSERT INTO auth."user" (id, login) VALUES (?, ?)|;
310 do_query($form, $dbh, $query, $user_id, $login);
313 $query = qq|DELETE FROM auth.user_config WHERE (user_id = ?)|;
314 do_query($form, $dbh, $query, $user_id);
316 $query = qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (?, ?, ?)|;
317 $sth = prepare_query($form, $dbh, $query);
319 while (my ($cfg_key, $cfg_value) = each %params) {
320 next if ($cfg_key eq 'password');
322 do_statement($form, $sth, $query, $user_id, $cfg_key, $cfg_value);
327 $main::lxdebug->leave_sub();
330 sub can_change_password {
333 return $self->{authenticator}->can_change_password();
336 sub change_password {
337 $main::lxdebug->enter_sub();
340 my $result = $self->{authenticator}->change_password(@_);
342 $main::lxdebug->leave_sub();
348 $main::lxdebug->enter_sub();
352 my $dbh = $self->dbconnect();
353 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
354 FROM auth.user_config cfg
355 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)|;
356 my $sth = prepare_execute_query($main::form, $dbh, $query);
360 while (my $ref = $sth->fetchrow_hashref()) {
361 $users{$ref->{login}} ||= { 'login' => $ref->{login}, 'id' => $ref->{id} };
362 $users{$ref->{login}}->{$ref->{cfg_key}} = $ref->{cfg_value} if (($ref->{cfg_key} ne 'login') && ($ref->{cfg_key} ne 'id'));
367 $main::lxdebug->leave_sub();
373 $main::lxdebug->enter_sub();
378 my $dbh = $self->dbconnect();
379 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
380 FROM auth.user_config cfg
381 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)
382 WHERE (u.login = ?)|;
383 my $sth = prepare_execute_query($main::form, $dbh, $query, $login);
387 while (my $ref = $sth->fetchrow_hashref()) {
388 $user_data{$ref->{cfg_key}} = $ref->{cfg_value};
389 @user_data{qw(id login)} = @{$ref}{qw(id login)};
394 $main::lxdebug->leave_sub();
400 $main::lxdebug->enter_sub();
405 my $dbh = $self->dbconnect();
406 my ($id) = selectrow_query($main::form, $dbh, qq|SELECT id FROM auth."user" WHERE login = ?|, $login);
408 $main::lxdebug->leave_sub();
414 $main::lxdebug->enter_sub();
419 my $form = $main::form;
421 my $dbh = $self->dbconnect();
422 my $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
424 my ($id) = selectrow_query($form, $dbh, $query, $login);
426 return $main::lxdebug->leave_sub() if (!$id);
428 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE user_id = ?|, $id);
429 do_query($form, $dbh, qq|DELETE FROM auth.user_config WHERE user_id = ?|, $id);
433 $main::lxdebug->leave_sub();
436 # --------------------------------------
440 sub restore_session {
441 $main::lxdebug->enter_sub();
445 my $cgi = $main::cgi;
446 $cgi ||= CGI->new('');
448 $session_id = $cgi->cookie($self->get_session_cookie_name());
449 $session_id =~ s|[^0-9a-f]||g;
451 $self->{SESSION} = { };
454 $main::lxdebug->leave_sub();
458 my ($dbh, $query, $sth, $cookie, $ref, $form);
462 $dbh = $self->dbconnect();
463 $query = qq|SELECT *, (mtime < (now() - '$self->{session_timeout}m'::interval)) AS is_expired FROM auth.session WHERE id = ?|;
465 $cookie = selectfirst_hashref_query($form, $dbh, $query, $session_id);
467 if (!$cookie || $cookie->{is_expired} || ($cookie->{ip_address} ne $ENV{REMOTE_ADDR})) {
468 $self->destroy_session();
469 $main::lxdebug->leave_sub();
470 return SESSION_EXPIRED;
473 $query = qq|SELECT sess_key, sess_value FROM auth.session_content WHERE session_id = ?|;
474 $sth = prepare_execute_query($form, $dbh, $query, $session_id);
476 while (my $ref = $sth->fetchrow_hashref()) {
477 $self->{SESSION}->{$ref->{sess_key}} = $ref->{sess_value};
478 $form->{$ref->{sess_key}} = $ref->{sess_value} if (!defined $form->{$ref->{sess_key}});
483 $main::lxdebug->leave_sub();
488 sub destroy_session {
489 $main::lxdebug->enter_sub();
494 my $dbh = $self->dbconnect();
496 do_query($main::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
497 do_query($main::form, $dbh, qq|DELETE FROM auth.session WHERE id = ?|, $session_id);
502 $self->{SESSION} = { };
505 $main::lxdebug->leave_sub();
508 sub expire_sessions {
509 $main::lxdebug->enter_sub();
513 my $dbh = $self->dbconnect();
515 qq|DELETE FROM auth.session_content
519 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval)))|;
521 do_query($main::form, $dbh, $query);
524 qq|DELETE FROM auth.session
525 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval))|;
527 do_query($main::form, $dbh, $query);
531 $main::lxdebug->leave_sub();
534 sub _create_session_id {
535 $main::lxdebug->enter_sub();
538 map { push @data, int(rand() * 255); } (1..32);
540 my $id = md5_hex(pack 'C*', @data);
542 $main::lxdebug->leave_sub();
547 sub create_or_refresh_session {
548 $main::lxdebug->enter_sub();
552 $session_id ||= $self->_create_session_id();
554 my ($form, $dbh, $query, $sth, $id);
557 $dbh = $self->dbconnect();
559 $query = qq|SELECT id FROM auth.session WHERE id = ?|;
561 ($id) = selectrow_query($form, $dbh, $query, $session_id);
564 do_query($form, $dbh, qq|UPDATE auth.session SET mtime = now() WHERE id = ?|, $session_id);
565 do_query($form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
568 do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
572 $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
573 $sth = prepare_query($form, $dbh, $query);
575 foreach my $key (sort keys %{ $self->{SESSION} }) {
576 do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
582 $main::lxdebug->leave_sub();
585 sub set_session_value {
586 $main::lxdebug->enter_sub();
590 $self->{SESSION} ||= { };
592 while (2 <= scalar @_) {
596 $self->{SESSION}->{$key} = $value;
599 $main::lxdebug->leave_sub();
602 sub set_cookie_environment_variable {
604 $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
607 sub get_session_cookie_name {
610 return $self->{cookie_name} || 'lx_office_erp_session_id';
617 sub session_tables_present {
618 $main::lxdebug->enter_sub();
621 my $dbh = $self->dbconnect(1);
624 $main::lxdebug->leave_sub();
631 WHERE (schemaname = 'auth')
632 AND (tablename IN ('session', 'session_content'))|;
634 my ($count) = selectrow_query($main::form, $dbh, $query);
636 $main::lxdebug->leave_sub();
641 # --------------------------------------
643 sub all_rights_full {
644 my $locale = $main::locale;
647 ["--crm", $locale->text("CRM optional software")],
648 ["crm_search", $locale->text("CRM search")],
649 ["crm_new", $locale->text("CRM create customers, vendors and contacts")],
650 ["crm_service", $locale->text("CRM services")],
651 ["crm_admin", $locale->text("CRM admin")],
652 ["crm_adminuser", $locale->text("CRM user")],
653 ["crm_adminstatus", $locale->text("CRM status")],
654 ["crm_email", $locale->text("CRM send email")],
655 ["crm_termin", $locale->text("CRM termin")],
656 ["crm_opportunity", $locale->text("CRM opportunity")],
657 ["crm_knowhow", $locale->text("CRM know how")],
658 ["crm_follow", $locale->text("CRM follow up")],
659 ["crm_notices", $locale->text("CRM notices")],
660 ["crm_other", $locale->text("CRM other")],
661 ["--master_data", $locale->text("Master Data")],
662 ["customer_vendor_edit", $locale->text("Create and edit customers and vendors")],
663 ["part_service_assembly_edit", $locale->text("Create and edit parts, services, assemblies")],
664 ["project_edit", $locale->text("Create and edit projects")],
665 ["license_edit", $locale->text("Manage license keys")],
666 ["--ar", $locale->text("AR")],
667 ["sales_quotation_edit", $locale->text("Create and edit sales quotations")],
668 ["sales_order_edit", $locale->text("Create and edit sales orders")],
669 ["sales_delivery_order_edit", $locale->text("Create and edit sales delivery orders")],
670 ["invoice_edit", $locale->text("Create and edit invoices and credit notes")],
671 ["dunning_edit", $locale->text("Create and edit dunnings")],
672 ["sales_all_edit", $locale->text("View/edit all employees sales documents")],
673 ["--ap", $locale->text("AP")],
674 ["request_quotation_edit", $locale->text("Create and edit RFQs")],
675 ["purchase_order_edit", $locale->text("Create and edit purchase orders")],
676 ["purchase_delivery_order_edit", $locale->text("Create and edit purchase delivery orders")],
677 ["vendor_invoice_edit", $locale->text("Create and edit vendor invoices")],
678 ["--warehouse_management", $locale->text("Warehouse management")],
679 ["warehouse_contents", $locale->text("View warehouse content")],
680 ["warehouse_management", $locale->text("Warehouse management")],
681 ["--general_ledger_cash", $locale->text("General ledger and cash")],
682 ["general_ledger", $locale->text("Transactions, AR transactions, AP transactions")],
683 ["datev_export", $locale->text("DATEV Export")],
684 ["cash", $locale->text("Receipt, payment, reconciliation")],
685 ["--reports", $locale->text('Reports')],
686 ["report", $locale->text('All reports')],
687 ["advance_turnover_tax_return", $locale->text('Advance turnover tax return')],
688 ["--others", $locale->text("Others")],
689 ["email_bcc", $locale->text("May set the BCC field when sending emails")],
690 ["config", $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
697 return grep !/^--/, map { $_->[0] } all_rights_full();
701 $main::lxdebug->enter_sub();
705 my $form = $main::form;
707 my $dbh = $self->dbconnect();
709 my $query = 'SELECT * FROM auth."group"';
710 my $sth = prepare_execute_query($form, $dbh, $query);
714 while ($row = $sth->fetchrow_hashref()) {
715 $groups->{$row->{id}} = $row;
719 $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
720 $sth = prepare_query($form, $dbh, $query);
722 foreach $group (values %{$groups}) {
725 do_statement($form, $sth, $query, $group->{id});
727 while ($row = $sth->fetchrow_hashref()) {
728 push @members, $row->{user_id};
730 $group->{members} = [ uniq @members ];
734 $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
735 $sth = prepare_query($form, $dbh, $query);
737 foreach $group (values %{$groups}) {
738 $group->{rights} = {};
740 do_statement($form, $sth, $query, $group->{id});
742 while ($row = $sth->fetchrow_hashref()) {
743 $group->{rights}->{$row->{right}} |= $row->{granted};
746 map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
750 $main::lxdebug->leave_sub();
756 $main::lxdebug->enter_sub();
761 my $form = $main::form;
762 my $dbh = $self->dbconnect();
764 my ($query, $sth, $row, $rights);
767 ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
769 $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
770 do_query($form, $dbh, $query, $group->{id});
773 do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
775 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
777 $query = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
778 $sth = prepare_query($form, $dbh, $query);
780 foreach my $user_id (uniq @{ $group->{members} }) {
781 do_statement($form, $sth, $query, $user_id, $group->{id});
785 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
787 $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
788 $sth = prepare_query($form, $dbh, $query);
790 foreach my $right (keys %{ $group->{rights} }) {
791 do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
797 $main::lxdebug->leave_sub();
801 $main::lxdebug->enter_sub();
806 my $form = $main::from;
808 my $dbh = $self->dbconnect();
810 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
811 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
812 do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
816 $main::lxdebug->leave_sub();
819 sub evaluate_rights_ary {
820 $main::lxdebug->enter_sub(2);
827 foreach my $el (@{$ary}) {
828 if (ref $el eq "ARRAY") {
829 if ($action eq '|') {
830 $value |= evaluate_rights_ary($el);
832 $value &= evaluate_rights_ary($el);
835 } elsif (($el eq '&') || ($el eq '|')) {
838 } elsif ($action eq '|') {
847 $main::lxdebug->leave_sub(2);
852 sub _parse_rights_string {
853 $main::lxdebug->enter_sub(2);
863 push @stack, $cur_ary;
865 while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
867 substr($access, 0, length $1) = "";
869 next if ($token =~ /\s/);
872 my $new_cur_ary = [];
873 push @stack, $new_cur_ary;
874 push @{$cur_ary}, $new_cur_ary;
875 $cur_ary = $new_cur_ary;
877 } elsif ($token eq ")") {
881 $main::lxdebug->leave_sub(2);
885 $cur_ary = $stack[-1];
887 } elsif (($token eq "|") || ($token eq "&")) {
888 push @{$cur_ary}, $token;
891 push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
895 my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
897 $main::lxdebug->leave_sub(2);
903 $main::lxdebug->enter_sub(2);
910 $self->{FULL_RIGHTS} ||= { };
911 $self->{FULL_RIGHTS}->{$login} ||= { };
913 if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
914 $self->{RIGHTS} ||= { };
915 $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
917 $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
920 my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
921 $granted = $default if (!defined $granted);
923 $main::lxdebug->leave_sub(2);
929 $main::lxdebug->enter_sub(2);
933 my $dont_abort = shift;
935 my $form = $main::form;
937 if ($self->check_right($form->{login}, $right)) {
938 $main::lxdebug->leave_sub(2);
943 delete $form->{title};
944 $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
947 $main::lxdebug->leave_sub(2);
952 sub load_rights_for_user {
953 $main::lxdebug->enter_sub();
958 my $form = $main::form;
959 my $dbh = $self->dbconnect();
961 my ($query, $sth, $row, $rights);
966 qq|SELECT gr."right", gr.granted
967 FROM auth.group_rights gr
970 FROM auth.user_group ug
971 LEFT JOIN auth."user" u ON (ug.user_id = u.id)
974 $sth = prepare_execute_query($form, $dbh, $query, $login);
976 while ($row = $sth->fetchrow_hashref()) {
977 $rights->{$row->{right}} |= $row->{granted};
981 map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
983 $main::lxdebug->leave_sub();