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();
39 $self->{dbh}->disconnect() if ($self->{dbh});
42 sub _read_auth_config {
43 $main::lxdebug->enter_sub();
47 my $form = $main::form;
48 my $locale = $main::locale;
51 my $in = IO::File->new('config/authentication.pl', 'r');
54 $form->error($locale->text('The config file "config/authentication.pl" was not found.'));
65 $form->error($locale->text('The config file "config/authentication.pl" contained invalid Perl code:') . "\n" . $@);
68 if ($self->{module} eq 'DB') {
69 $self->{authenticator} = SL::Auth::DB->new($self);
71 } elsif ($self->{module} eq 'LDAP') {
72 $self->{authenticator} = SL::Auth::LDAP->new($self);
75 if (!$self->{authenticator}) {
76 $form->error($locale->text('No or an unknown authenticantion module specified in "config/authentication.pl".'));
79 my $cfg = $self->{DB_config};
82 $form->error($locale->text('config/authentication.pl: Key "DB_config" is missing.'));
85 if (!$cfg->{host} || !$cfg->{db} || !$cfg->{user}) {
86 $form->error($locale->text('config/authentication.pl: Missing parameters in "DB_config". Required parameters are "host", "db" and "user".'));
89 $self->{authenticator}->verify_config();
91 $self->{session_timeout} *= 1;
92 $self->{session_timeout} = 8 * 60 if (!$self->{session_timeout});
94 $main::lxdebug->leave_sub();
97 sub authenticate_root {
98 $main::lxdebug->enter_sub();
101 my $password = shift;
102 my $is_crypted = shift;
104 $password = crypt $password, 'ro' if (!$password || !$is_crypted);
105 my $admin_password = crypt "$self->{admin_password}", 'ro';
107 $main::lxdebug->leave_sub();
109 return $password eq $admin_password ? OK : ERR_PASSWORD;
113 $main::lxdebug->enter_sub();
117 $main::lxdebug->leave_sub();
119 return $self->{authenticator}->authenticate(@_);
123 $main::lxdebug->enter_sub(2);
126 my $may_fail = shift;
129 $main::lxdebug->leave_sub(2);
133 my $cfg = $self->{DB_config};
134 my $dsn = 'dbi:Pg:dbname=' . $cfg->{db} . ';host=' . $cfg->{host};
137 $dsn .= ';port=' . $cfg->{port};
140 $main::lxdebug->message(LXDebug->DEBUG1, "Auth::dbconnect DSN: $dsn");
142 $self->{dbh} = DBI->connect($dsn, $cfg->{user}, $cfg->{password}, { 'AutoCommit' => 0 });
144 if (!$may_fail && !$self->{dbh}) {
145 $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr);
148 $main::lxdebug->leave_sub();
154 $main::lxdebug->enter_sub();
159 $self->{dbh}->disconnect();
163 $main::lxdebug->leave_sub();
167 $main::lxdebug->enter_sub();
171 my $dbh = $self->dbconnect();
172 my $query = qq|SELECT COUNT(*) FROM pg_tables WHERE (schemaname = 'auth') AND (tablename = 'user')|;
174 my ($count) = $dbh->selectrow_array($query);
176 $main::lxdebug->leave_sub();
182 $main::lxdebug->enter_sub();
186 my $dbh = $self->dbconnect(1);
188 $main::lxdebug->leave_sub();
193 sub create_database {
194 $main::lxdebug->enter_sub();
199 my $cfg = $self->{DB_config};
201 if (!$params{superuser}) {
202 $params{superuser} = $cfg->{user};
203 $params{superuser_password} = $cfg->{password};
206 $params{template} ||= 'template0';
207 $params{template} =~ s|[^a-zA-Z0-9_\-]||g;
209 my $dsn = 'dbi:Pg:dbname=template1;host=' . $cfg->{host};
212 $dsn .= ';port=' . $cfg->{port};
215 $main::lxdebug->message(LXDebug->DEBUG1(), "Auth::create_database DSN: $dsn");
217 my $dbh = DBI->connect($dsn, $params{superuser}, $params{superuser_password});
220 $main::form->error($main::locale->text('The connection to the template database failed:') . "\n" . $DBI::errstr);
223 my $charset = $main::dbcharset;
224 $charset ||= Common::DEFAULT_CHARSET;
225 my $encoding = $Common::charset_to_db_encoding{$charset};
226 $encoding ||= 'UNICODE';
228 my $query = qq|CREATE DATABASE "$cfg->{db}" OWNER "$cfg->{user}" TEMPLATE "$params{template}" ENCODING '$encoding'|;
230 $main::lxdebug->message(LXDebug->DEBUG1(), "Auth::create_database query: $query");
235 my $error = $dbh->errstr();
237 $query = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
238 my ($cluster_encoding) = $dbh->selectrow_array($query);
240 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i) && ($encoding !~ m/^(?:UTF-?8|UNICODE)$/i)) {
241 $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.');
246 $main::form->error($main::locale->text('The creation of the authentication database failed:') . "\n" . $error);
251 $main::lxdebug->leave_sub();
255 $main::lxdebug->enter_sub();
258 my $dbh = $self->dbconnect();
260 my $charset = $main::dbcharset;
261 $charset ||= Common::DEFAULT_CHARSET;
264 User->process_query($main::form, $dbh, 'sql/auth_db.sql', undef, $charset);
266 $main::lxdebug->leave_sub();
270 $main::lxdebug->enter_sub();
276 my $form = $main::form;
278 my $dbh = $self->dbconnect();
280 my ($sth, $query, $user_id);
282 $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
283 ($user_id) = selectrow_query($form, $dbh, $query, $login);
286 $query = qq|SELECT nextval('auth.user_id_seq')|;
287 ($user_id) = selectrow_query($form, $dbh, $query);
289 $query = qq|INSERT INTO auth."user" (id, login) VALUES (?, ?)|;
290 do_query($form, $dbh, $query, $user_id, $login);
293 $query = qq|DELETE FROM auth.user_config WHERE (user_id = ?)|;
294 do_query($form, $dbh, $query, $user_id);
296 $query = qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (?, ?, ?)|;
297 $sth = prepare_query($form, $dbh, $query);
299 while (my ($cfg_key, $cfg_value) = each %params) {
300 next if ($cfg_key eq 'password');
302 do_statement($form, $sth, $query, $user_id, $cfg_key, $cfg_value);
307 $main::lxdebug->leave_sub();
310 sub can_change_password {
313 return $self->{authenticator}->can_change_password();
316 sub change_password {
317 $main::lxdebug->enter_sub();
320 my $result = $self->{authenticator}->change_password(@_);
322 $main::lxdebug->leave_sub();
328 $main::lxdebug->enter_sub();
332 my $dbh = $self->dbconnect();
333 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
334 FROM auth.user_config cfg
335 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)|;
336 my $sth = prepare_execute_query($main::form, $dbh, $query);
340 while (my $ref = $sth->fetchrow_hashref()) {
341 $users{$ref->{login}} ||= { 'login' => $ref->{login}, 'id' => $ref->{id} };
342 $users{$ref->{login}}->{$ref->{cfg_key}} = $ref->{cfg_value} if (($ref->{cfg_key} ne 'login') && ($ref->{cfg_key} ne 'id'));
347 $main::lxdebug->leave_sub();
353 $main::lxdebug->enter_sub();
358 my $dbh = $self->dbconnect();
359 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
360 FROM auth.user_config cfg
361 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)
362 WHERE (u.login = ?)|;
363 my $sth = prepare_execute_query($main::form, $dbh, $query, $login);
367 while (my $ref = $sth->fetchrow_hashref()) {
368 $user_data{$ref->{cfg_key}} = $ref->{cfg_value};
369 @user_data{qw(id login)} = @{$ref}{qw(id login)};
374 $main::lxdebug->leave_sub();
380 $main::lxdebug->enter_sub();
385 my $dbh = $self->dbconnect();
386 my ($id) = selectrow_query($main::form, $dbh, qq|SELECT id FROM auth."user" WHERE login = ?|, $login);
388 $main::lxdebug->leave_sub();
394 $main::lxdebug->enter_sub();
399 my $form = $main::form;
401 my $dbh = $self->dbconnect();
402 my $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
404 my ($id) = selectrow_query($form, $dbh, $query, $login);
406 return $main::lxdebug->leave_sub() if (!$id);
408 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE user_id = ?|, $id);
409 do_query($form, $dbh, qq|DELETE FROM auth.user_config WHERE user_id = ?|, $id);
413 $main::lxdebug->leave_sub();
416 # --------------------------------------
420 sub restore_session {
421 $main::lxdebug->enter_sub();
425 my $cgi = $main::cgi;
426 $cgi ||= CGI->new('');
428 $session_id = $cgi->cookie($self->get_session_cookie_name());
429 $session_id =~ s|[^0-9a-f]||g;
431 $self->{SESSION} = { };
434 $main::lxdebug->leave_sub();
438 my ($dbh, $query, $sth, $cookie, $ref, $form);
442 $dbh = $self->dbconnect();
443 $query = qq|SELECT *, (mtime < (now() - '$self->{session_timeout}m'::interval)) AS is_expired FROM auth.session WHERE id = ?|;
445 $cookie = selectfirst_hashref_query($form, $dbh, $query, $session_id);
447 if (!$cookie || $cookie->{is_expired} || ($cookie->{ip_address} ne $ENV{REMOTE_ADDR})) {
448 $self->destroy_session();
449 $main::lxdebug->leave_sub();
450 return SESSION_EXPIRED;
453 $query = qq|SELECT sess_key, sess_value FROM auth.session_content WHERE session_id = ?|;
454 $sth = prepare_execute_query($form, $dbh, $query, $session_id);
456 while (my $ref = $sth->fetchrow_hashref()) {
457 $self->{SESSION}->{$ref->{sess_key}} = $ref->{sess_value};
458 $form->{$ref->{sess_key}} = $ref->{sess_value} if (!defined $form->{$ref->{sess_key}});
463 $main::lxdebug->leave_sub();
468 sub destroy_session {
469 $main::lxdebug->enter_sub();
474 my $dbh = $self->dbconnect();
476 do_query($main::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
477 do_query($main::form, $dbh, qq|DELETE FROM auth.session WHERE id = ?|, $session_id);
482 $self->{SESSION} = { };
485 $main::lxdebug->leave_sub();
488 sub expire_sessions {
489 $main::lxdebug->enter_sub();
493 my $dbh = $self->dbconnect();
495 qq|DELETE FROM auth.session_content
499 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval)))|;
501 do_query($main::form, $dbh, $query);
504 qq|DELETE FROM auth.session
505 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval))|;
507 do_query($main::form, $dbh, $query);
511 $main::lxdebug->leave_sub();
514 sub _create_session_id {
515 $main::lxdebug->enter_sub();
518 map { push @data, int(rand() * 255); } (1..32);
520 my $id = md5_hex(pack 'C*', @data);
522 $main::lxdebug->leave_sub();
527 sub create_or_refresh_session {
528 $main::lxdebug->enter_sub();
532 $session_id ||= $self->_create_session_id();
534 my ($form, $dbh, $query, $sth, $id);
537 $dbh = $self->dbconnect();
539 $query = qq|SELECT id FROM auth.session WHERE id = ?|;
541 ($id) = selectrow_query($form, $dbh, $query, $session_id);
544 do_query($form, $dbh, qq|UPDATE auth.session SET mtime = now() WHERE id = ?|, $session_id);
545 do_query($form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
548 do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
552 $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
553 $sth = prepare_query($form, $dbh, $query);
555 foreach my $key (sort keys %{ $self->{SESSION} }) {
556 do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
562 $main::lxdebug->leave_sub();
565 sub set_session_value {
566 $main::lxdebug->enter_sub();
570 $self->{SESSION} ||= { };
572 while (2 <= scalar @_) {
576 $self->{SESSION}->{$key} = $value;
579 $main::lxdebug->leave_sub();
582 sub set_cookie_environment_variable {
584 $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
587 sub get_session_cookie_name {
590 return $self->{cookie_name} || 'lx_office_erp_session_id';
597 sub session_tables_present {
598 $main::lxdebug->enter_sub();
601 my $dbh = $self->dbconnect(1);
604 $main::lxdebug->leave_sub();
611 WHERE (schemaname = 'auth')
612 AND (tablename IN ('session', 'session_content'))|;
614 my ($count) = selectrow_query($main::form, $dbh, $query);
616 $main::lxdebug->leave_sub();
621 # --------------------------------------
623 sub all_rights_full {
624 my $locale = $main::locale;
627 ["--crm", $locale->text("CRM optional software")],
628 ["crm_search", $locale->text("CRM search")],
629 ["crm_new", $locale->text("CRM create customers, vendors and contacts")],
630 ["crm_service", $locale->text("CRM services")],
631 ["crm_admin", $locale->text("CRM admin")],
632 ["crm_adminuser", $locale->text("CRM user")],
633 ["crm_adminstatus", $locale->text("CRM status")],
634 ["crm_email", $locale->text("CRM send email")],
635 ["crm_termin", $locale->text("CRM termin")],
636 ["crm_opportunity", $locale->text("CRM opportunity")],
637 ["crm_knowhow", $locale->text("CRM know how")],
638 ["crm_follow", $locale->text("CRM follow up")],
639 ["crm_notices", $locale->text("CRM notices")],
640 ["crm_other", $locale->text("CRM other")],
641 ["--master_data", $locale->text("Master Data")],
642 ["customer_vendor_edit", $locale->text("Create and edit customers and vendors")],
643 ["part_service_assembly_edit", $locale->text("Create and edit parts, services, assemblies")],
644 ["project_edit", $locale->text("Create and edit projects")],
645 ["license_edit", $locale->text("Manage license keys")],
646 ["--ar", $locale->text("AR")],
647 ["sales_quotation_edit", $locale->text("Create and edit sales quotations")],
648 ["sales_order_edit", $locale->text("Create and edit sales orders")],
649 ["sales_delivery_order_edit", $locale->text("Create and edit sales delivery orders")],
650 ["invoice_edit", $locale->text("Create and edit invoices and credit notes")],
651 ["dunning_edit", $locale->text("Create and edit dunnings")],
652 ["sales_all_edit", $locale->text("View/edit all employees sales documents")],
653 ["--ap", $locale->text("AP")],
654 ["request_quotation_edit", $locale->text("Create and edit RFQs")],
655 ["purchase_order_edit", $locale->text("Create and edit purchase orders")],
656 ["purchase_delivery_order_edit", $locale->text("Create and edit purchase delivery orders")],
657 ["vendor_invoice_edit", $locale->text("Create and edit vendor invoices")],
658 ["--warehouse_management", $locale->text("Warehouse management")],
659 ["warehouse_contents", $locale->text("View warehouse content")],
660 ["warehouse_management", $locale->text("Warehouse management")],
661 ["--general_ledger_cash", $locale->text("General ledger and cash")],
662 ["general_ledger", $locale->text("Transactions, AR transactions, AP transactions")],
663 ["datev_export", $locale->text("DATEV Export")],
664 ["cash", $locale->text("Receipt, payment, reconciliation")],
665 ["--reports", $locale->text('Reports')],
666 ["report", $locale->text('All reports')],
667 ["advance_turnover_tax_return", $locale->text('Advance turnover tax return')],
668 ["--others", $locale->text("Others")],
669 ["email_bcc", $locale->text("May set the BCC field when sending emails")],
670 ["config", $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
677 return grep !/^--/, map { $_->[0] } all_rights_full();
681 $main::lxdebug->enter_sub();
685 my $form = $main::form;
687 my $dbh = $self->dbconnect();
689 my $query = 'SELECT * FROM auth."group"';
690 my $sth = prepare_execute_query($form, $dbh, $query);
694 while ($row = $sth->fetchrow_hashref()) {
695 $groups->{$row->{id}} = $row;
699 $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
700 $sth = prepare_query($form, $dbh, $query);
702 foreach $group (values %{$groups}) {
705 do_statement($form, $sth, $query, $group->{id});
707 while ($row = $sth->fetchrow_hashref()) {
708 push @members, $row->{user_id};
710 $group->{members} = [ uniq @members ];
714 $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
715 $sth = prepare_query($form, $dbh, $query);
717 foreach $group (values %{$groups}) {
718 $group->{rights} = {};
720 do_statement($form, $sth, $query, $group->{id});
722 while ($row = $sth->fetchrow_hashref()) {
723 $group->{rights}->{$row->{right}} |= $row->{granted};
726 map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
730 $main::lxdebug->leave_sub();
736 $main::lxdebug->enter_sub();
741 my $form = $main::form;
742 my $dbh = $self->dbconnect();
744 my ($query, $sth, $row, $rights);
747 ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
749 $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
750 do_query($form, $dbh, $query, $group->{id});
753 do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
755 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
757 $query = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
758 $sth = prepare_query($form, $dbh, $query);
760 foreach my $user_id (uniq @{ $group->{members} }) {
761 do_statement($form, $sth, $query, $user_id, $group->{id});
765 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
767 $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
768 $sth = prepare_query($form, $dbh, $query);
770 foreach my $right (keys %{ $group->{rights} }) {
771 do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
777 $main::lxdebug->leave_sub();
781 $main::lxdebug->enter_sub();
786 my $form = $main::from;
788 my $dbh = $self->dbconnect();
790 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
791 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
792 do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
796 $main::lxdebug->leave_sub();
799 sub evaluate_rights_ary {
800 $main::lxdebug->enter_sub(2);
807 foreach my $el (@{$ary}) {
808 if (ref $el eq "ARRAY") {
809 if ($action eq '|') {
810 $value |= evaluate_rights_ary($el);
812 $value &= evaluate_rights_ary($el);
815 } elsif (($el eq '&') || ($el eq '|')) {
818 } elsif ($action eq '|') {
827 $main::lxdebug->enter_sub(2);
832 sub _parse_rights_string {
833 $main::lxdebug->enter_sub(2);
843 push @stack, $cur_ary;
845 while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
847 substr($access, 0, length $1) = "";
849 next if ($token =~ /\s/);
852 my $new_cur_ary = [];
853 push @stack, $new_cur_ary;
854 push @{$cur_ary}, $new_cur_ary;
855 $cur_ary = $new_cur_ary;
857 } elsif ($token eq ")") {
861 $main::lxdebug->enter_sub(2);
865 $cur_ary = $stack[-1];
867 } elsif (($token eq "|") || ($token eq "&")) {
868 push @{$cur_ary}, $token;
871 push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
875 my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
877 $main::lxdebug->enter_sub(2);
883 $main::lxdebug->enter_sub(2);
890 $self->{FULL_RIGHTS} ||= { };
891 $self->{FULL_RIGHTS}->{$login} ||= { };
893 if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
894 $self->{RIGHTS} ||= { };
895 $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
897 $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
900 my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
901 $granted = $default if (!defined $granted);
903 $main::lxdebug->leave_sub(2);
909 $main::lxdebug->enter_sub(2);
913 my $dont_abort = shift;
915 my $form = $main::form;
917 if ($self->check_right($form->{login}, $right)) {
918 $main::lxdebug->leave_sub(2);
923 delete $form->{title};
924 $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
927 $main::lxdebug->leave_sub(2);
932 sub load_rights_for_user {
933 $main::lxdebug->enter_sub();
938 my $form = $main::form;
939 my $dbh = $self->dbconnect();
941 my ($query, $sth, $row, $rights);
946 qq|SELECT gr."right", gr.granted
947 FROM auth.group_rights gr
950 FROM auth.user_group ug
951 LEFT JOIN auth."user" u ON (ug.user_id = u.id)
954 $sth = prepare_execute_query($form, $dbh, $query, $login);
956 while ($row = $sth->fetchrow_hashref()) {
957 $rights->{$row->{right}} |= $row->{granted};
961 map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
963 $main::lxdebug->leave_sub();