X-Git-Url: http://wagnertech.de/git?a=blobdiff_plain;f=SL%2FAuth.pm;h=6be693382b0e2c44dfa34f8605ddd8480a41801d;hb=713de5ed35a8a1faea940354254c4e781631c495;hp=bb7ae00513627ca471c7c2ca178c57fbae658de3;hpb=7ed4b336b89b861479a1fc2670b9456334b0d1be;p=kivitendo-erp.git diff --git a/SL/Auth.pm b/SL/Auth.pm index bb7ae0051..6be693382 100644 --- a/SL/Auth.pm +++ b/SL/Auth.pm @@ -5,8 +5,9 @@ use DBI; use Digest::MD5 qw(md5_hex); use IO::File; use Time::HiRes qw(gettimeofday); -use List::MoreUtils qw(uniq); +use List::MoreUtils qw(any uniq); use YAML; +use Regexp::IPv6 qw($IPv6_re); use SL::Auth::ColumnInformation; use SL::Auth::Constants qw(:all); @@ -19,7 +20,7 @@ use SL::SessionFile; use SL::User; use SL::DBConnect; use SL::DBUpgrade2; -use SL::DBUtils; +use SL::DBUtils qw(do_query do_statement prepare_execute_query prepare_query selectall_array_query selectrow_query selectall_ids); use strict; @@ -36,21 +37,42 @@ sub new { my $self = bless {}, $type; $self->_read_auth_config(%params); - $self->reset; + $self->init; return $self; } -sub reset { +sub init { my ($self, %params) = @_; - delete $self->{dbh}; $self->{SESSION} = { }; $self->{FULL_RIGHTS} = { }; $self->{RIGHTS} = { }; $self->{unique_counter} = 0; $self->{column_information} = SL::Auth::ColumnInformation->new(auth => $self); - $self->{authenticator}->reset; +} + +sub reset { + my ($self, %params) = @_; + + $self->{SESSION} = { }; + $self->{FULL_RIGHTS} = { }; + $self->{RIGHTS} = { }; + $self->{unique_counter} = 0; + + if ($self->is_db_connected) { + # reset is called during request shutdown already. In case of a + # completely new auth DB this would fail and generate an error + # message even if the user is currently trying to create said auth + # DB. Therefore only fetch the column information if a connection + # has been established. + $self->{column_information} = SL::Auth::ColumnInformation->new(auth => $self); + $self->{column_information}->_fetch; + } else { + delete $self->{column_information}; + } + + $_->reset for @{ $self->{authenticators} }; $self->client(undef); } @@ -72,6 +94,18 @@ sub set_client { return $self->client; } +sub get_default_client_id { + my ($self) = @_; + + my $dbh = $self->dbconnect; + + return unless $dbh; + + my $row = $dbh->selectrow_hashref(qq|SELECT id FROM auth.clients WHERE is_default = TRUE LIMIT 1|); + + return $row->{id} if $row; +} + sub DESTROY { my $self = shift; @@ -84,12 +118,15 @@ sub mini_error { my ($self, @msg) = @_; if ($ENV{HTTP_USER_AGENT}) { - print Form->create_http_response(content_type => 'text/html'); + # $::form might not be initialized yet at this point — therefore + # we cannot use "create_http_response" yet. + my $cgi = CGI->new(''); + print $cgi->header('-type' => 'text/html', '-charset' => 'UTF-8'); print "
", join ('
', @msg), "
"; } else { print STDERR "Error: @msg\n"; } - ::end_of_request(); + $::dispatcher->end_request; } sub _read_auth_config { @@ -106,19 +143,33 @@ sub _read_auth_config { } else { $self->{DB_config} = $::lx_office_conf{'authentication/database'}; - $self->{LDAP_config} = $::lx_office_conf{'authentication/ldap'}; } - if ($self->{module} eq 'DB') { - $self->{authenticator} = SL::Auth::DB->new($self); + $self->{authenticators} = []; + $self->{module} ||= 'DB'; + $self->{module} =~ s{^ +| +$}{}g; - } elsif ($self->{module} eq 'LDAP') { - $self->{authenticator} = SL::Auth::LDAP->new($self); - } + foreach my $module (split m{ +}, $self->{module}) { + my $config_name; + ($module, $config_name) = split m{:}, $module, 2; + $config_name ||= $module eq 'DB' ? 'database' : lc($module); + my $config = $::lx_office_conf{'authentication/' . $config_name}; - if (!$self->{authenticator}) { - my $locale = Locale->new('en'); - $self->mini_error($locale->text('No or an unknown authenticantion module specified in "config/kivitendo.conf".')); + if (!$config) { + my $locale = Locale->new('en'); + $self->mini_error($locale->text('Missing configuration section "authentication/#1" in "config/kivitendo.conf".', $config_name)); + } + + if ($module eq 'DB') { + push @{ $self->{authenticators} }, SL::Auth::DB->new($self); + + } elsif ($module eq 'LDAP') { + push @{ $self->{authenticators} }, SL::Auth::LDAP->new($config); + + } else { + my $locale = Locale->new('en'); + $self->mini_error($locale->text('Unknown authenticantion module #1 specified in "config/kivitendo.conf".', $module)); + } } my $cfg = $self->{DB_config}; @@ -133,7 +184,7 @@ sub _read_auth_config { $self->mini_error($locale->text('config/kivitendo.conf: Missing parameters in "authentication/database". Required parameters are "host", "db" and "user".')); } - $self->{authenticator}->verify_config(); + $_->verify_config for @{ $self->{authenticators} }; $self->{session_timeout} *= 1; $self->{session_timeout} = 8 * 60 if (!$self->{session_timeout}); @@ -168,8 +219,8 @@ sub authenticate_root { return ERR_PASSWORD; } - $password = SL::Auth::Password->hash(login => 'root', password => $password); my $admin_password = SL::Auth::Password->hash_if_unhashed(login => 'root', password => $self->{admin_password}->()); + $password = SL::Auth::Password->hash(login => 'root', password => $password, stored_password => $admin_password); my $result = $password eq $admin_password ? OK : ERR_PASSWORD; $self->set_session_value(SESSION_KEY_ROOT_AUTH() => $result); @@ -193,7 +244,14 @@ sub authenticate { return ERR_PASSWORD; } - my $result = $login ? $self->{authenticator}->authenticate($login, $password) : ERR_USER; + my $result = ERR_USER; + if ($login) { + foreach my $authenticator (@{ $self->{authenticators} }) { + $result = $authenticator->authenticate($login, $password); + last if $result == OK; + } + } + $self->set_session_value(SESSION_KEY_USER_AUTH() => $result, login => $login, client_id => $self->client->{id}); return $result; } @@ -236,6 +294,7 @@ sub dbconnect { $self->{dbh} = SL::DBConnect->connect($dsn, $cfg->{user}, $cfg->{password}, { pg_enable_utf8 => 1, AutoCommit => 1 }); if (!$may_fail && !$self->{dbh}) { + delete $self->{dbh}; $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr); } @@ -251,6 +310,11 @@ sub dbdisconnect { } } +sub is_db_connected { + my ($self) = @_; + return !!$self->{dbh}; +} + sub check_tables { my ($self, $dbh) = @_; @@ -372,15 +436,22 @@ sub save_user { sub can_change_password { my $self = shift; - return $self->{authenticator}->can_change_password(); + return any { $_->can_change_password } @{ $self->{authenticators} }; } sub change_password { my ($self, $login, $new_password) = @_; - my $result = $self->{authenticator}->change_password($login, $new_password); + my $overall_result = OK; - return $result; + foreach my $authenticator (@{ $self->{authenticators} }) { + next unless $authenticator->can_change_password; + + my $result = $authenticator->change_password($login, $new_password); + $overall_result = $result if $result != OK; + } + + return $overall_result; } sub read_all_users { @@ -516,7 +587,7 @@ sub restore_session { $form = $main::form; - # Don't fail if the auth DB doesn't yet. + # Don't fail if the auth DB doesn't exist yet. if (!( $dbh = $self->dbconnect(1) )) { return $self->session_restore_result(SESSION_NONE()); } @@ -537,12 +608,10 @@ sub restore_session { # 1. session ID exists in the database # 2. hasn't expired yet # 3. if cookie for the API token is given: the cookie's value equal database column 'auth.session.api_token' for the session ID - # 4. if cookie for the API token is NOT given then: the requestee's IP address must match the stored IP address $self->{api_token} = $cookie->{api_token} if $cookie; my $api_token_cookie = $self->get_api_token_cookie; my $cookie_is_bad = !$cookie || $cookie->{is_expired}; $cookie_is_bad ||= $api_token_cookie && ($api_token_cookie ne $cookie->{api_token}) if $api_token_cookie; - $cookie_is_bad ||= $cookie->{ip_address} ne $ENV{REMOTE_ADDR} if !$api_token_cookie; if ($cookie_is_bad) { $self->destroy_session(); return $self->session_restore_result($cookie ? SESSION_EXPIRED() : SESSION_NONE()); @@ -592,18 +661,18 @@ SQL sub _load_with_auto_restore_column { my ($self, $dbh, $session_id) = @_; - my $auto_restore_keys = join ', ', map { "'${_}'" } qw(login password rpw); + my %auto_restore_keys = map { $_ => 1 } qw(login password rpw client_id), SESSION_KEY_ROOT_AUTH, SESSION_KEY_USER_AUTH; my $query = <fetchrow_hashref) { + $need_delete = 1 if $ref->{auto_restore}; my $value = SL::Auth::SessionValue->new(auth => $self, key => $ref->{sess_key}, value => $ref->{sess_value}, @@ -619,19 +688,8 @@ SQL $sth->finish; - $query = <fetchrow_hashref) { - my $value = SL::Auth::SessionValue->new(auth => $self, - key => $ref->{sess_key}); - $self->{SESSION}->{ $ref->{sess_key} } = $value; + if ($need_delete) { + do_query($::form, $dbh, 'DELETE FROM auth.session_content WHERE auto_restore AND session_id = ?', $session_id); } } @@ -726,16 +784,6 @@ sub save_session { return; } - my @unfetched_keys = map { $_->{key} } - grep { ! $_->{fetched} } - values %{ $self->{SESSION} }; - # $::lxdebug->dump(0, "unfetched_keys", [ sort @unfetched_keys ]); - # $::lxdebug->dump(0, "all keys", [ sort map { $_->{key} } values %{ $self->{SESSION} } ]); - my $query = qq|DELETE FROM auth.session_content WHERE (session_id = ?)|; - $query .= qq| AND (sess_key NOT IN (| . join(', ', ('?') x scalar @unfetched_keys) . qq|))| if @unfetched_keys; - - do_query($::form, $dbh, $query, $session_id, @unfetched_keys); - my ($id) = selectrow_query($::form, $dbh, qq|SELECT id FROM auth.session WHERE id = ?|, $session_id); if ($id) { @@ -749,28 +797,40 @@ sub save_session { do_query($::form, $dbh, qq|UPDATE auth.session SET api_token = ? WHERE id = ?|, $self->_create_session_id, $session_id) unless $stored_api_token; } - my @values_to_save = grep { $_->{fetched} } + my @values_to_save = grep { $_->{modified} } values %{ $self->{SESSION} }; if (@values_to_save) { - my ($columns, $placeholders) = ('', ''); + my %known_keys = map { $_ => 1 } + selectall_ids($::form, $dbh, qq|SELECT sess_key FROM auth.session_content WHERE session_id = ?|, 'sess_key', $session_id); my $auto_restore = $self->{column_information}->has('auto_restore'); - if ($auto_restore) { - $columns .= ', auto_restore'; - $placeholders .= ', ?'; - } + my $insert_query = $auto_restore + ? "INSERT INTO auth.session_content (session_id, sess_key, sess_value, auto_restore) VALUES (?, ?, ?, ?)" + : "INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)"; + my $insert_sth = prepare_query($::form, $dbh, $insert_query); - $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value ${columns}) VALUES (?, ?, ? ${placeholders})|; - my $sth = prepare_query($::form, $dbh, $query); + my $update_query = $auto_restore + ? "UPDATE auth.session_content SET sess_value = ?, auto_restore = ? WHERE session_id = ? AND sess_key = ?" + : "UPDATE auth.session_content SET sess_value = ? WHERE session_id = ? AND sess_key = ?"; + my $update_sth = prepare_query($::form, $dbh, $update_query); foreach my $value (@values_to_save) { my @values = ($value->{key}, $value->get_dumped); push @values, $value->{auto_restore} if $auto_restore; - do_statement($::form, $sth, $query, $session_id, @values); + if ($known_keys{$value->{key}}) { + do_statement($::form, $update_sth, $update_query, + $value->get_dumped, ( $value->{auto_restore} )x!!$auto_restore, $session_id, $value->{key} + ); + } else { + do_statement($::form, $insert_sth, $insert_query, + $session_id, $value->{key}, $value->get_dumped, ( $value->{auto_restore} )x!!$auto_restore + ); + } } - $sth->finish(); + $insert_sth->finish; + $update_sth->finish; } $dbh->commit() unless $provided_dbh; @@ -788,12 +848,14 @@ sub set_session_value { if (ref $key eq 'HASH') { $self->{SESSION}->{ $key->{key} } = SL::Auth::SessionValue->new(key => $key->{key}, value => $key->{value}, + modified => 1, auto_restore => $key->{auto_restore}); } else { my $value = shift @params; $self->{SESSION}->{ $key } = SL::Auth::SessionValue->new(key => $key, - value => $value); + value => $value, + modified => 1); } } @@ -810,13 +872,14 @@ sub delete_session_value { } sub get_session_value { - my $self = shift; - my $data = $self->{SESSION} && $self->{SESSION}->{ $_[0] } ? $self->{SESSION}->{ $_[0] }->get : undef; + my ($self, $key) = @_; + + return if !$self->{SESSION}; - return $data; + ($self->{SESSION}{$key} //= SL::Auth::SessionValue->new(auth => $self, key => $key))->get } -sub create_unique_sesion_value { +sub create_unique_session_value { my ($self, $value, %params) = @_; $self->{SESSION} ||= { }; @@ -849,7 +912,7 @@ sub save_form_in_session { $data->{$key} = $form->{$key} if !ref($form->{$key}) || $non_scalars; } - return $self->create_unique_sesion_value($data, %params); + return $self->create_unique_session_value($data, %params); } sub restore_form_from_session { @@ -897,104 +960,52 @@ sub is_api_token_cookie_valid { return $self->{api_token} && $provided_api_token && ($self->{api_token} eq $provided_api_token); } -sub session_tables_present { - my $self = shift; +sub _tables_present { + my ($self, @tables) = @_; + my $cache_key = join '_', @tables; # Only re-check for the presence of auth tables if either the check # hasn't been done before of if they weren't present. - if ($self->{session_tables_present}) { - return $self->{session_tables_present}; - } + return $self->{"$cache_key\_tables_present"} ||= do { + my $dbh = $self->dbconnect(1); - my $dbh = $self->dbconnect(1); + if (!$dbh) { + return 0; + } - if (!$dbh) { - return 0; - } + my $query = + qq|SELECT COUNT(*) + FROM pg_tables + WHERE (schemaname = 'auth') + AND (tablename IN (@{[ join ', ', ('?') x @tables ]}))|; - my $query = - qq|SELECT COUNT(*) - FROM pg_tables - WHERE (schemaname = 'auth') - AND (tablename IN ('session', 'session_content'))|; + my ($count) = selectrow_query($main::form, $dbh, $query, @tables); - my ($count) = selectrow_query($main::form, $dbh, $query); + scalar @tables == $count; + } +} - $self->{session_tables_present} = 2 == $count; +sub session_tables_present { + $_[0]->_tables_present('session', 'session_content'); +} - return $self->{session_tables_present}; +sub master_rights_present { + $_[0]->_tables_present('master_rights'); } # -------------------------------------- sub all_rights_full { - my $locale = $main::locale; - - my @all_rights = ( - ["--crm", $locale->text("CRM optional software")], - ["crm_search", $locale->text("CRM search")], - ["crm_new", $locale->text("CRM create customers, vendors and contacts")], - ["crm_service", $locale->text("CRM services")], - ["crm_admin", $locale->text("CRM admin")], - ["crm_adminuser", $locale->text("CRM user")], - ["crm_adminstatus", $locale->text("CRM status")], - ["crm_email", $locale->text("CRM send email")], - ["crm_termin", $locale->text("CRM termin")], - ["crm_opportunity", $locale->text("CRM opportunity")], - ["crm_knowhow", $locale->text("CRM know how")], - ["crm_follow", $locale->text("CRM follow up")], - ["crm_notices", $locale->text("CRM notices")], - ["crm_other", $locale->text("CRM other")], - ["--master_data", $locale->text("Master Data")], - ["customer_vendor_edit", $locale->text("Create customers and vendors. Edit all vendors. Edit only customers where salesman equals employee (login)")], - ["customer_vendor_all_edit", $locale->text("Create customers and vendors. Edit all vendors. Edit all customers")], - ["part_service_assembly_edit", $locale->text("Create and edit parts, services, assemblies")], - ["part_service_assembly_details", $locale->text("Show details and reports of parts, services, assemblies")], - ["project_edit", $locale->text("Create and edit projects")], - ["--ar", $locale->text("AR")], - ["requirement_spec_edit", $locale->text("Create and edit requirement specs")], - ["sales_quotation_edit", $locale->text("Create and edit sales quotations")], - ["sales_order_edit", $locale->text("Create and edit sales orders")], - ["sales_delivery_order_edit", $locale->text("Create and edit sales delivery orders")], - ["invoice_edit", $locale->text("Create and edit invoices and credit notes")], - ["dunning_edit", $locale->text("Create and edit dunnings")], - ["sales_all_edit", $locale->text("View/edit all employees sales documents")], - ["edit_prices", $locale->text("Edit prices and discount (if not used, textfield is ONLY set readonly)")], - ["show_ar_transactions", $locale->text("Show AR transactions as part of AR invoice report")], - ["delivery_plan", $locale->text("Show delivery plan")], - ["delivery_value_report", $locale->text("Show delivery value report")], - ["--ap", $locale->text("AP")], - ["request_quotation_edit", $locale->text("Create and edit RFQs")], - ["purchase_order_edit", $locale->text("Create and edit purchase orders")], - ["purchase_delivery_order_edit", $locale->text("Create and edit purchase delivery orders")], - ["vendor_invoice_edit", $locale->text("Create and edit vendor invoices")], - ["show_ap_transactions", $locale->text("Show AP transactions as part of AP invoice report")], - ["--warehouse_management", $locale->text("Warehouse management")], - ["warehouse_contents", $locale->text("View warehouse content")], - ["warehouse_management", $locale->text("Warehouse management")], - ["--general_ledger_cash", $locale->text("General ledger and cash")], - ["general_ledger", $locale->text("Transactions, AR transactions, AP transactions")], - ["datev_export", $locale->text("DATEV Export")], - ["cash", $locale->text("Receipt, payment, reconciliation")], - ["--reports", $locale->text('Reports')], - ["report", $locale->text('All reports')], - ["advance_turnover_tax_return", $locale->text('Advance turnover tax return')], - ["--batch_printing", $locale->text("Batch Printing")], - ["batch_printing", $locale->text("Batch Printing")], - ["--configuration", $locale->text("Configuration")], - ["config", $locale->text("Change kivitendo installation settings (most entries in the 'System' menu)")], - ["admin", $locale->text("Client administration: configuration, editing templates, task server control, background jobs (remaining entries in the 'System' menu)")], - ["--others", $locale->text("Others")], - ["email_bcc", $locale->text("May set the BCC field when sending emails")], - ["productivity", $locale->text("Productivity")], - ["display_admin_link", $locale->text("Show administration link")], - ); - - return @all_rights; + my ($self) = @_; + + @{ $self->{master_rights} ||= do { + $self->dbconnect->selectall_arrayref("SELECT name, description, category FROM auth.master_rights ORDER BY position"); + } + } } sub all_rights { - return grep !/^--/, map { $_->[0] } all_rights_full(); + return map { $_->[0] } grep { !$_->[2] } $_[0]->all_rights_full; } sub read_groups { @@ -1041,7 +1052,7 @@ sub read_groups { $group->{rights}->{$row->{right}} |= $row->{granted}; } - map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights(); + map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } $self->all_rights; } $sth->finish(); @@ -1112,23 +1123,38 @@ sub evaluate_rights_ary { my $value = 0; my $action = '|'; + my $negate = 0; foreach my $el (@{$ary}) { + next unless defined $el; + if (ref $el eq "ARRAY") { + my $val = evaluate_rights_ary($el); + $val = !$val if $negate; + $negate = 0; if ($action eq '|') { - $value |= evaluate_rights_ary($el); + $value |= $val; } else { - $value &= evaluate_rights_ary($el); + $value &= $val; } } elsif (($el eq '&') || ($el eq '|')) { $action = $el; + } elsif ($el eq '!') { + $negate = !$negate; + } elsif ($action eq '|') { - $value |= $el; + my $val = $el; + $val = !$val if $negate; + $negate = 0; + $value |= $val; } else { - $value &= $el; + my $val = $el; + $val = !$val if $negate; + $negate = 0; + $value &= $val; } } @@ -1172,7 +1198,7 @@ sub _parse_rights_string { push @{$cur_ary}, $token; } else { - push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1; + push @{$cur_ary}, ($self->{RIGHTS}->{$login}->{$token} // 0) * 1; } } @@ -1203,6 +1229,15 @@ sub check_right { return $granted; } +sub deny_access { + my ($self) = @_; + + $::dispatcher->reply_with_json_error(error => 'access') if $::request->type eq 'json'; + + delete $::form->{title}; + $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")); +} + sub assert { my ($self, $right, $dont_abort) = @_; @@ -1211,8 +1246,7 @@ sub assert { } if (!$dont_abort) { - delete $::form->{title}; - $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")); + $self->deny_access; } return 0; @@ -1223,7 +1257,9 @@ sub load_rights_for_user { my $dbh = $self->dbconnect; my ($query, $sth, $row, $rights); - $rights = { map { $_ => 0 } all_rights() }; + $rights = { map { $_ => 0 } $self->all_rights }; + + return $rights if !$self->client || !$login; $query = qq|SELECT gr."right", gr.granted @@ -1259,7 +1295,7 @@ __END__ SL::Auth - Authentication and session handling -=head1 FUNCTIONS +=head1 METHODS =over 4 @@ -1296,7 +1332,7 @@ The values can be any Perl structure. They are stored as YAML dumps. Retrieve a value from the session. Returns C if the value doesn't exist. -=item C +=item C Create a unique key in the session and store C<$value> there. @@ -1309,10 +1345,10 @@ Stores the session values in the database. This is the only function that actually stores stuff in the database. Neither the various setters nor the deleter access the database. -=item +=item C Stores the content of C<$params{form}> (default: C<$::form>) in the -session using L. +session using L. If C<$params{non_scalars}> is trueish then non-scalar values will be stored as well. Default is to only store scalar values. @@ -1323,7 +1359,7 @@ can be given as an array ref in C<$params{skip_keys}>. Returns the unique key under which the form is stored. -=item +=item C Restores the form from the session into C<$params{form}> (default: C<$::form>). @@ -1334,6 +1370,19 @@ is on by default. Returns C<$self>. +=item C + +C deletes every state information from previous requests, but does not +close the database connection. + +Creating a new database handle on each request can take up to 30% of the +pre-request startup time, so we want to avoid that for fast ajax calls. + +=item C + +Checks if current user has the C<$right>. If C<$dont_abort> is falsish +the request dies with a access denied error, otherwise returns true or false. + =back =head1 BUGS