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();
520 my @secs = gettimeofday();
524 map { push @data, int(rand() * 255); } (1..32);
526 my $id = md5_hex(pack 'C*', @data);
528 $main::lxdebug->leave_sub();
533 sub create_or_refresh_session {
534 $main::lxdebug->enter_sub();
538 $session_id ||= $self->_create_session_id();
540 my ($form, $dbh, $query, $sth, $id);
543 $dbh = $self->dbconnect();
545 $query = qq|SELECT id FROM auth.session WHERE id = ?|;
547 ($id) = selectrow_query($form, $dbh, $query, $session_id);
550 do_query($form, $dbh, qq|UPDATE auth.session SET mtime = now() WHERE id = ?|, $session_id);
551 do_query($form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
554 do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
558 $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
559 $sth = prepare_query($form, $dbh, $query);
561 foreach my $key (sort keys %{ $self->{SESSION} }) {
562 do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
568 $main::lxdebug->leave_sub();
571 sub set_session_value {
572 $main::lxdebug->enter_sub();
576 $self->{SESSION} ||= { };
578 while (2 <= scalar @_) {
582 $self->{SESSION}->{$key} = $value;
585 $main::lxdebug->leave_sub();
588 sub set_cookie_environment_variable {
590 $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
593 sub get_session_cookie_name {
596 return $self->{cookie_name} || 'lx_office_erp_session_id';
603 sub session_tables_present {
604 $main::lxdebug->enter_sub();
607 my $dbh = $self->dbconnect(1);
610 $main::lxdebug->leave_sub();
617 WHERE (schemaname = 'auth')
618 AND (tablename IN ('session', 'session_content'))|;
620 my ($count) = selectrow_query($main::form, $dbh, $query);
622 $main::lxdebug->leave_sub();
627 # --------------------------------------
629 sub all_rights_full {
630 my $locale = $main::locale;
633 ["--crm", $locale->text("CRM optional software")],
634 ["crm_search", $locale->text("CRM search")],
635 ["crm_new", $locale->text("CRM create customers, vendors and contacts")],
636 ["crm_service", $locale->text("CRM services")],
637 ["crm_admin", $locale->text("CRM admin")],
638 ["crm_adminuser", $locale->text("CRM user")],
639 ["crm_adminstatus", $locale->text("CRM status")],
640 ["crm_email", $locale->text("CRM send email")],
641 ["crm_termin", $locale->text("CRM termin")],
642 ["crm_opportunity", $locale->text("CRM opportunity")],
643 ["crm_knowhow", $locale->text("CRM know how")],
644 ["crm_follow", $locale->text("CRM follow up")],
645 ["crm_notices", $locale->text("CRM notices")],
646 ["crm_other", $locale->text("CRM other")],
647 ["--master_data", $locale->text("Master Data")],
648 ["customer_vendor_edit", $locale->text("Create and edit customers and vendors")],
649 ["part_service_assembly_edit", $locale->text("Create and edit parts, services, assemblies")],
650 ["project_edit", $locale->text("Create and edit projects")],
651 ["license_edit", $locale->text("Manage license keys")],
652 ["--ar", $locale->text("AR")],
653 ["sales_quotation_edit", $locale->text("Create and edit sales quotations")],
654 ["sales_order_edit", $locale->text("Create and edit sales orders")],
655 ["sales_delivery_order_edit", $locale->text("Create and edit sales delivery orders")],
656 ["invoice_edit", $locale->text("Create and edit invoices and credit notes")],
657 ["dunning_edit", $locale->text("Create and edit dunnings")],
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();