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);
23 $main::lxdebug->enter_sub();
30 $self->{SESSION} = { };
32 $self->_read_auth_config();
34 $main::lxdebug->leave_sub();
42 $self->{dbh}->disconnect() if ($self->{dbh});
45 sub _read_auth_config {
46 $main::lxdebug->enter_sub();
50 my $form = $main::form;
51 my $locale = $main::locale;
54 my $in = IO::File->new('config/authentication.pl', 'r');
57 $form->error($locale->text('The config file "config/authentication.pl" was not found.'));
68 $form->error($locale->text('The config file "config/authentication.pl" contained invalid Perl code:') . "\n" . $@);
71 if ($self->{module} eq 'DB') {
72 $self->{authenticator} = SL::Auth::DB->new($self);
74 } elsif ($self->{module} eq 'LDAP') {
75 $self->{authenticator} = SL::Auth::LDAP->new($self);
78 if (!$self->{authenticator}) {
79 $form->error($locale->text('No or an unknown authenticantion module specified in "config/authentication.pl".'));
82 my $cfg = $self->{DB_config};
85 $form->error($locale->text('config/authentication.pl: Key "DB_config" is missing.'));
88 if (!$cfg->{host} || !$cfg->{db} || !$cfg->{user}) {
89 $form->error($locale->text('config/authentication.pl: Missing parameters in "DB_config". Required parameters are "host", "db" and "user".'));
92 $self->{authenticator}->verify_config();
94 $self->{session_timeout} *= 1;
95 $self->{session_timeout} = 8 * 60 if (!$self->{session_timeout});
97 $main::lxdebug->leave_sub();
100 sub authenticate_root {
101 $main::lxdebug->enter_sub();
104 my $password = shift;
105 my $is_crypted = shift;
107 $password = crypt $password, 'ro' if (!$password || !$is_crypted);
108 my $admin_password = crypt "$self->{admin_password}", 'ro';
110 $main::lxdebug->leave_sub();
112 return $password eq $admin_password ? OK : ERR_PASSWORD;
116 $main::lxdebug->enter_sub();
120 $main::lxdebug->leave_sub();
122 return $self->{authenticator}->authenticate(@_);
126 $main::lxdebug->enter_sub(2);
129 my $may_fail = shift;
132 $main::lxdebug->leave_sub(2);
136 my $cfg = $self->{DB_config};
137 my $dsn = 'dbi:Pg:dbname=' . $cfg->{db} . ';host=' . $cfg->{host};
140 $dsn .= ';port=' . $cfg->{port};
143 $main::lxdebug->message(LXDebug::DEBUG1, "Auth::dbconnect DSN: $dsn");
145 $self->{dbh} = DBI->connect($dsn, $cfg->{user}, $cfg->{password}, { 'AutoCommit' => 0 });
147 if (!$may_fail && !$self->{dbh}) {
148 $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr);
151 $main::lxdebug->leave_sub();
157 $main::lxdebug->enter_sub();
162 $self->{dbh}->disconnect();
166 $main::lxdebug->leave_sub();
170 $main::lxdebug->enter_sub();
174 my $dbh = $self->dbconnect();
175 my $query = qq|SELECT COUNT(*) FROM pg_tables WHERE (schemaname = 'auth') AND (tablename = 'user')|;
177 my ($count) = $dbh->selectrow_array($query);
179 $main::lxdebug->leave_sub();
185 $main::lxdebug->enter_sub();
189 my $dbh = $self->dbconnect(1);
191 $main::lxdebug->leave_sub();
196 sub create_database {
197 $main::lxdebug->enter_sub();
202 my $cfg = $self->{DB_config};
204 if (!$params{superuser}) {
205 $params{superuser} = $cfg->{user};
206 $params{superuser_password} = $cfg->{password};
209 $params{template} ||= 'template0';
210 $params{template} =~ s|[^a-zA-Z0-9_\-]||g;
212 my $dsn = 'dbi:Pg:dbname=template1;host=' . $cfg->{host};
215 $dsn .= ';port=' . $cfg->{port};
218 $main::lxdebug->message(LXDebug::DEBUG1, "Auth::create_database DSN: $dsn");
220 my $dbh = DBI->connect($dsn, $params{superuser}, $params{superuser_password});
223 $main::form->error($main::locale->text('The connection to the template database failed:') . "\n" . $DBI::errstr);
226 my $charset = $main::dbcharset;
227 $charset ||= Common::DEFAULT_CHARSET;
228 my $encoding = $Common::charset_to_db_encoding{$charset};
229 $encoding ||= 'UNICODE';
231 my $query = qq|CREATE DATABASE "$cfg->{db}" OWNER "$cfg->{user}" TEMPLATE "$params{template}" ENCODING '$encoding'|;
233 $main::lxdebug->message(LXDebug::DEBUG1, "Auth::create_database query: $query");
238 my $error = $dbh->errstr();
240 $query = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
241 my ($cluster_encoding) = $dbh->selectrow_array($query);
243 if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i) && ($encoding !~ m/^(?:UTF-?8|UNICODE)$/i)) {
244 $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.');
249 $main::form->error($main::locale->text('The creation of the authentication database failed:') . "\n" . $error);
254 $main::lxdebug->leave_sub();
258 $main::lxdebug->enter_sub();
261 my $dbh = $self->dbconnect();
263 my $charset = $main::dbcharset;
264 $charset ||= Common::DEFAULT_CHARSET;
267 User->process_query($main::form, $dbh, 'sql/auth_db.sql', undef, $charset);
269 $main::lxdebug->leave_sub();
273 $main::lxdebug->enter_sub();
279 my $form = $main::form;
281 my $dbh = $self->dbconnect();
283 my ($sth, $query, $user_id);
285 $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
286 ($user_id) = selectrow_query($form, $dbh, $query, $login);
289 $query = qq|SELECT nextval('auth.user_id_seq')|;
290 ($user_id) = selectrow_query($form, $dbh, $query);
292 $query = qq|INSERT INTO auth."user" (id, login) VALUES (?, ?)|;
293 do_query($form, $dbh, $query, $user_id, $login);
296 $query = qq|DELETE FROM auth.user_config WHERE (user_id = ?)|;
297 do_query($form, $dbh, $query, $user_id);
299 $query = qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (?, ?, ?)|;
300 $sth = prepare_query($form, $dbh, $query);
302 while (my ($cfg_key, $cfg_value) = each %params) {
303 next if ($cfg_key eq 'password');
305 do_statement($form, $sth, $query, $user_id, $cfg_key, $cfg_value);
310 $main::lxdebug->leave_sub();
313 sub can_change_password {
316 return $self->{authenticator}->can_change_password();
319 sub change_password {
320 $main::lxdebug->enter_sub();
323 my $result = $self->{authenticator}->change_password(@_);
325 $main::lxdebug->leave_sub();
331 $main::lxdebug->enter_sub();
335 my $dbh = $self->dbconnect();
336 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
337 FROM auth.user_config cfg
338 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)|;
339 my $sth = prepare_execute_query($main::form, $dbh, $query);
343 while (my $ref = $sth->fetchrow_hashref()) {
344 $users{$ref->{login}} ||= { 'login' => $ref->{login}, 'id' => $ref->{id} };
345 $users{$ref->{login}}->{$ref->{cfg_key}} = $ref->{cfg_value} if (($ref->{cfg_key} ne 'login') && ($ref->{cfg_key} ne 'id'));
350 $main::lxdebug->leave_sub();
356 $main::lxdebug->enter_sub();
361 my $dbh = $self->dbconnect();
362 my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
363 FROM auth.user_config cfg
364 LEFT JOIN auth."user" u ON (cfg.user_id = u.id)
365 WHERE (u.login = ?)|;
366 my $sth = prepare_execute_query($main::form, $dbh, $query, $login);
370 while (my $ref = $sth->fetchrow_hashref()) {
371 $user_data{$ref->{cfg_key}} = $ref->{cfg_value};
372 @user_data{qw(id login)} = @{$ref}{qw(id login)};
377 $main::lxdebug->leave_sub();
383 $main::lxdebug->enter_sub();
388 my $dbh = $self->dbconnect();
389 my ($id) = selectrow_query($main::form, $dbh, qq|SELECT id FROM auth."user" WHERE login = ?|, $login);
391 $main::lxdebug->leave_sub();
397 $main::lxdebug->enter_sub();
402 my $form = $main::form;
404 my $dbh = $self->dbconnect();
405 my $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
407 my ($id) = selectrow_query($form, $dbh, $query, $login);
409 return $main::lxdebug->leave_sub() if (!$id);
411 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE user_id = ?|, $id);
412 do_query($form, $dbh, qq|DELETE FROM auth.user_config WHERE user_id = ?|, $id);
416 $main::lxdebug->leave_sub();
419 # --------------------------------------
423 sub restore_session {
424 $main::lxdebug->enter_sub();
428 my $cgi = $main::cgi;
429 $cgi ||= CGI->new('');
431 $session_id = $cgi->cookie($self->get_session_cookie_name());
432 $session_id =~ s|[^0-9a-f]||g;
434 $self->{SESSION} = { };
437 $main::lxdebug->leave_sub();
441 my ($dbh, $query, $sth, $cookie, $ref, $form);
445 $dbh = $self->dbconnect();
446 $query = qq|SELECT *, (mtime < (now() - '$self->{session_timeout}m'::interval)) AS is_expired FROM auth.session WHERE id = ?|;
448 $cookie = selectfirst_hashref_query($form, $dbh, $query, $session_id);
450 if (!$cookie || $cookie->{is_expired} || ($cookie->{ip_address} ne $ENV{REMOTE_ADDR})) {
451 $self->destroy_session();
452 $main::lxdebug->leave_sub();
453 return SESSION_EXPIRED;
456 $query = qq|SELECT sess_key, sess_value FROM auth.session_content WHERE session_id = ?|;
457 $sth = prepare_execute_query($form, $dbh, $query, $session_id);
459 while (my $ref = $sth->fetchrow_hashref()) {
460 $self->{SESSION}->{$ref->{sess_key}} = $ref->{sess_value};
461 $form->{$ref->{sess_key}} = $ref->{sess_value} if (!defined $form->{$ref->{sess_key}});
466 $main::lxdebug->leave_sub();
471 sub destroy_session {
472 $main::lxdebug->enter_sub();
477 my $dbh = $self->dbconnect();
479 do_query($main::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
480 do_query($main::form, $dbh, qq|DELETE FROM auth.session WHERE id = ?|, $session_id);
485 $self->{SESSION} = { };
488 $main::lxdebug->leave_sub();
491 sub expire_sessions {
492 $main::lxdebug->enter_sub();
496 my $dbh = $self->dbconnect();
498 qq|DELETE FROM auth.session_content
502 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval)))|;
504 do_query($main::form, $dbh, $query);
507 qq|DELETE FROM auth.session
508 WHERE (mtime < (now() - '$self->{session_timeout}m'::interval))|;
510 do_query($main::form, $dbh, $query);
514 $main::lxdebug->leave_sub();
517 sub _create_session_id {
518 $main::lxdebug->enter_sub();
521 map { push @data, int(rand() * 255); } (1..32);
523 my $id = md5_hex(pack 'C*', @data);
525 $main::lxdebug->leave_sub();
530 sub create_or_refresh_session {
531 $main::lxdebug->enter_sub();
535 $session_id ||= $self->_create_session_id();
537 my ($form, $dbh, $query, $sth, $id);
540 $dbh = $self->dbconnect();
542 $query = qq|SELECT id FROM auth.session WHERE id = ?|;
544 ($id) = selectrow_query($form, $dbh, $query, $session_id);
547 do_query($form, $dbh, qq|UPDATE auth.session SET mtime = now() WHERE id = ?|, $session_id);
548 do_query($form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
551 do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
555 $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
556 $sth = prepare_query($form, $dbh, $query);
558 foreach my $key (sort keys %{ $self->{SESSION} }) {
559 do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
565 $main::lxdebug->leave_sub();
568 sub set_session_value {
569 $main::lxdebug->enter_sub();
573 $self->{SESSION} ||= { };
575 while (2 <= scalar @_) {
579 $self->{SESSION}->{$key} = $value;
582 $main::lxdebug->leave_sub();
585 sub set_cookie_environment_variable {
587 $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
590 sub get_session_cookie_name {
593 return $self->{cookie_name} || 'lx_office_erp_session_id';
600 sub session_tables_present {
601 $main::lxdebug->enter_sub();
604 my $dbh = $self->dbconnect(1);
607 $main::lxdebug->leave_sub();
614 WHERE (schemaname = 'auth')
615 AND (tablename IN ('session', 'session_content'))|;
617 my ($count) = selectrow_query($main::form, $dbh, $query);
619 $main::lxdebug->leave_sub();
624 # --------------------------------------
626 sub all_rights_full {
627 my $locale = $main::locale;
630 ["--crm", $locale->text("CRM optional software")],
631 ["crm_search", $locale->text("CRM search")],
632 ["crm_new", $locale->text("CRM create customers, vendors and contacts")],
633 ["crm_service", $locale->text("CRM services")],
634 ["crm_admin", $locale->text("CRM admin")],
635 ["crm_adminuser", $locale->text("CRM user")],
636 ["crm_adminstatus", $locale->text("CRM status")],
637 ["crm_email", $locale->text("CRM send email")],
638 ["crm_termin", $locale->text("CRM termin")],
639 ["crm_opportunity", $locale->text("CRM opportunity")],
640 ["crm_knowhow", $locale->text("CRM know how")],
641 ["crm_follow", $locale->text("CRM follow up")],
642 ["crm_notices", $locale->text("CRM notices")],
643 ["crm_other", $locale->text("CRM other")],
644 ["--master_data", $locale->text("Master Data")],
645 ["customer_vendor_edit", $locale->text("Create and edit customers and vendors")],
646 ["part_service_assembly_edit", $locale->text("Create and edit parts, services, assemblies")],
647 ["project_edit", $locale->text("Create and edit projects")],
648 ["license_edit", $locale->text("Manage license keys")],
649 ["--ar", $locale->text("AR")],
650 ["sales_quotation_edit", $locale->text("Create and edit sales quotations")],
651 ["sales_order_edit", $locale->text("Create and edit sales orders")],
652 ["sales_delivery_order_edit", $locale->text("Create and edit sales delivery orders")],
653 ["invoice_edit", $locale->text("Create and edit invoices and credit notes")],
654 ["dunning_edit", $locale->text("Create and edit dunnings")],
655 ["--ap", $locale->text("AP")],
656 ["request_quotation_edit", $locale->text("Create and edit RFQs")],
657 ["purchase_order_edit", $locale->text("Create and edit purchase orders")],
658 ["purchase_delivery_order_edit", $locale->text("Create and edit purchase delivery orders")],
659 ["vendor_invoice_edit", $locale->text("Create and edit vendor invoices")],
660 ["--warehouse_management", $locale->text("Warehouse management")],
661 ["warehouse_contents", $locale->text("View warehouse content")],
662 ["warehouse_management", $locale->text("Warehouse management")],
663 ["--general_ledger_cash", $locale->text("General ledger and cash")],
664 ["general_ledger", $locale->text("Transactions, AR transactions, AP transactions")],
665 ["datev_export", $locale->text("DATEV Export")],
666 ["cash", $locale->text("Receipt, payment, reconciliation")],
667 ["--reports", $locale->text('Reports')],
668 ["report", $locale->text('All reports')],
669 ["advance_turnover_tax_return", $locale->text('Advance turnover tax return')],
670 ["--others", $locale->text("Others")],
671 ["email_bcc", $locale->text("May set the BCC field when sending emails")],
672 ["config", $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
679 return grep !/^--/, map { $_->[0] } all_rights_full();
683 $main::lxdebug->enter_sub();
687 my $form = $main::form;
689 my $dbh = $self->dbconnect();
691 my $query = 'SELECT * FROM auth."group"';
692 my $sth = prepare_execute_query($form, $dbh, $query);
696 while ($row = $sth->fetchrow_hashref()) {
697 $groups->{$row->{id}} = $row;
701 $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
702 $sth = prepare_query($form, $dbh, $query);
704 foreach $group (values %{$groups}) {
707 do_statement($form, $sth, $query, $group->{id});
709 while ($row = $sth->fetchrow_hashref()) {
710 push @members, $row->{user_id};
712 $group->{members} = [ uniq @members ];
716 $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
717 $sth = prepare_query($form, $dbh, $query);
719 foreach $group (values %{$groups}) {
720 $group->{rights} = {};
722 do_statement($form, $sth, $query, $group->{id});
724 while ($row = $sth->fetchrow_hashref()) {
725 $group->{rights}->{$row->{right}} |= $row->{granted};
728 map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
732 $main::lxdebug->leave_sub();
738 $main::lxdebug->enter_sub();
743 my $form = $main::form;
744 my $dbh = $self->dbconnect();
746 my ($query, $sth, $row, $rights);
749 ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
751 $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
752 do_query($form, $dbh, $query, $group->{id});
755 do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
757 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
759 $query = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
760 $sth = prepare_query($form, $dbh, $query);
762 foreach my $user_id (uniq @{ $group->{members} }) {
763 do_statement($form, $sth, $query, $user_id, $group->{id});
767 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
769 $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
770 $sth = prepare_query($form, $dbh, $query);
772 foreach my $right (keys %{ $group->{rights} }) {
773 do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
779 $main::lxdebug->leave_sub();
783 $main::lxdebug->enter_sub();
788 my $form = $main::from;
790 my $dbh = $self->dbconnect();
792 do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
793 do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
794 do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
798 $main::lxdebug->leave_sub();
801 sub evaluate_rights_ary {
802 $main::lxdebug->enter_sub(2);
809 foreach my $el (@{$ary}) {
810 if (ref $el eq "ARRAY") {
811 if ($action eq '|') {
812 $value |= evaluate_rights_ary($el);
814 $value &= evaluate_rights_ary($el);
817 } elsif (($el eq '&') || ($el eq '|')) {
820 } elsif ($action eq '|') {
829 $main::lxdebug->enter_sub(2);
834 sub _parse_rights_string {
835 $main::lxdebug->enter_sub(2);
845 push @stack, $cur_ary;
847 while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
849 substr($access, 0, length $1) = "";
851 next if ($token =~ /\s/);
854 my $new_cur_ary = [];
855 push @stack, $new_cur_ary;
856 push @{$cur_ary}, $new_cur_ary;
857 $cur_ary = $new_cur_ary;
859 } elsif ($token eq ")") {
863 $main::lxdebug->enter_sub(2);
867 $cur_ary = $stack[-1];
869 } elsif (($token eq "|") || ($token eq "&")) {
870 push @{$cur_ary}, $token;
873 push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
877 my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
879 $main::lxdebug->enter_sub(2);
885 $main::lxdebug->enter_sub(2);
892 $self->{FULL_RIGHTS} ||= { };
893 $self->{FULL_RIGHTS}->{$login} ||= { };
895 if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
896 $self->{RIGHTS} ||= { };
897 $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
899 $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
902 my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
903 $granted = $default if (!defined $granted);
905 $main::lxdebug->leave_sub(2);
911 $main::lxdebug->enter_sub(2);
915 my $dont_abort = shift;
917 my $form = $main::form;
919 if ($self->check_right($form->{login}, $right)) {
920 $main::lxdebug->leave_sub(2);
925 delete $form->{title};
926 $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
929 $main::lxdebug->leave_sub(2);
934 sub load_rights_for_user {
935 $main::lxdebug->enter_sub();
940 my $form = $main::form;
941 my $dbh = $self->dbconnect();
943 my ($query, $sth, $row, $rights);
948 qq|SELECT gr."right", gr.granted
949 FROM auth.group_rights gr
952 FROM auth.user_group ug
953 LEFT JOIN auth."user" u ON (ug.user_id = u.id)
956 $sth = prepare_execute_query($form, $dbh, $query, $login);
958 while ($row = $sth->fetchrow_hashref()) {
959 $rights->{$row->{right}} |= $row->{granted};
963 map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
965 $main::lxdebug->leave_sub();