1 package SL::Controller::Admin;
5 use parent qw(SL::Controller::Base);
8 use List::Util qw(first);
9 use List::UtilsBy qw(sort_by);
13 use SL::DB::AuthGroup;
16 use SL::Helper::Flash;
17 use SL::Locale::String qw(t8);
18 use SL::System::InstallationLock;
21 use SL::Layout::AdminLogin;
23 use Rose::Object::MakeMethods::Generic
25 'scalar --get_set_init' => [ qw(client user group printer db_cfg is_locked
26 all_dateformats all_numberformats all_countrycodes all_stylesheets all_menustyles all_clients all_groups all_users all_rights all_printers
27 all_dbsources all_used_dbsources all_accounting_methods all_inventory_systems all_profit_determinations all_charts) ],
30 __PACKAGE__->run_before(\&setup_layout);
31 __PACKAGE__->run_before(\&setup_client, only => [ qw(list_printers new_printer edit_printer save_printer delete_printer) ]);
33 sub get_auth_level { "admin" };
34 sub keep_auth_vars_in_form {
35 my ($class, %params) = @_;
36 return $params{action} eq 'login';
40 # actions: login, logout
46 return $self->login_form if !$::form->{do_login};
47 return if !$self->authenticate_root;
48 return if !$self->check_auth_db_and_tables;
49 return if $self->apply_dbupgrade_scripts;
51 $self->redirect_to(action => 'show');
56 $::auth->destroy_session;
57 $self->redirect_to(action => 'login');
61 # actions: creating the authentication database & tables, applying database ugprades
64 sub action_apply_dbupgrade_scripts {
67 return if $self->apply_dbupgrade_scripts;
68 $self->redirect_to(action => 'show');
71 sub action_create_auth_db {
74 $::auth->create_database(superuser => $::form->{db_superuser},
75 superuser_password => $::form->{db_superuser_password},
76 template => $::form->{db_template});
77 $self->check_auth_db_and_tables;
80 sub action_create_auth_tables {
83 $::auth->create_tables;
84 $::auth->set_session_value('admin_password', $::lx_office_conf{authentication}->{admin_password});
85 $::auth->create_or_refresh_session;
87 my $scripts_applied = $self->apply_dbupgrade_scripts;
89 if (! SL::DB::Manager::AuthGroup->get_all_count) {
90 SL::DB::AuthGroup->new(
91 name => t8('Full Access'),
92 description => t8('Full access to all functions'),
93 rights => [ map { SL::DB::AuthGroupRight->new(right => $_, granted => 1) } $::auth->all_rights ],
97 $self->action_login unless $scripts_applied;
109 title => "kivitendo " . t8('Administration'),
113 sub action_new_user {
116 my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
117 $self->user(SL::DB::AuthUser->new(
119 countrycode => $defaults->language('de'),
120 numberformat => $defaults->numberformat('1.000,00'),
121 dateformat => $defaults->dateformat('dd.mm.yy'),
122 stylesheet => "design40.css",
127 $self->edit_user_form(title => t8('Create a new user'));
130 sub action_edit_user {
132 $self->edit_user_form(title => t8('Edit User'));
135 sub action_save_user {
137 my $params = delete($::form->{user}) || { };
138 my $props = delete($params->{config_values}) || { };
139 my $is_new = !$params->{id};
140 my $check_previously_used = delete($::form->{check_previously_used}) || 0;
141 my $assign_documents = delete($::form->{assign_documents}) || 0;
143 # Assign empty arrays if the browser doesn't send those controls.
144 $params->{clients} ||= [];
145 $params->{groups} ||= [];
147 $self->user($is_new ? SL::DB::AuthUser->new : SL::DB::AuthUser->new(id => $params->{id})->load)
148 ->assign_attributes(%{ $params })
149 ->config_values({ %{ $self->user->config_values }, %{ $props } });
151 my @errors = $self->user->validate;
154 $self->js->flash('error', $_) foreach @errors;
155 return $self->js->render();
158 # check if given login name was previously used and show a dialog if so
159 if ($is_new && $check_previously_used && $self->check_loginname_previously_used()) {
160 $self->js->run('show_loginname_previously_used_dialog');
161 return $self->js->render();
164 # rename previous usernames in employee table, if not set to assign
165 if ($is_new && !$assign_documents) {
166 my $clients = SL::DB::Manager::AuthClient->get_all_sorted;
167 for my $client (@$clients) {
168 my $now = DateTime->now_local;
169 my $timestamp = $now->format_cldr('yyyyMMddHHmmss');
171 my $dbh = $client->dbconnect(AutoCommit => 1);
173 $dbh->do(qq|UPDATE employee SET login = ? WHERE login = ?;|,undef,
174 $params->{'login'} . $timestamp, $params->{'login'});
181 if ($::auth->can_change_password && $::form->{new_password}) {
182 $::auth->change_password($self->user->login, $::form->{new_password});
185 flash_later('info', $is_new ? t8('The user has been created.') : t8('The user has been saved.'));
186 $self->redirect_to(action => 'show');
189 sub action_delete_user {
192 my @clients = @{ $self->user->clients || [] };
194 # backup user metadata (email, name, etc)
195 my $user_config_values_ref = $self->user->config_values();
196 my $login =$self->user->login;
198 if (!$self->user->delete) {
199 flash('error', t8('The user could not be deleted.'));
200 $self->edit_user_form(title => t8('Edit User'));
204 # Flag corresponding entries in 'employee' as deleted.
205 # and restore the most important user data in employee
206 # TODO try and catch the whole transaction {user->delete; update employee} {exception}
207 foreach my $client (@clients) {
208 my $dbh = $client->dbconnect(AutoCommit => 1) || next;
209 $dbh->do(qq|UPDATE employee SET deleted = TRUE, name = ?, deleted_email = ?,
210 deleted_tel = ?, deleted_fax = ?, deleted_signature = ? WHERE login = ?|,undef,
211 $user_config_values_ref->{name}, $user_config_values_ref->{email},
212 $user_config_values_ref->{tel}, $user_config_values_ref->{fax},
213 $user_config_values_ref->{signature}, $self->user->login);
217 flash_later('info', t8('The user has been deleted.'));
218 $self->redirect_to(action => 'show');
225 sub action_new_client {
228 $self->client(SL::DB::AuthClient->new(
229 dbhost => $::auth->{DB_config}->{host},
230 dbport => $::auth->{DB_config}->{port},
231 dbuser => $::auth->{DB_config}->{user},
232 dbpasswd => $::auth->{DB_config}->{password},
235 $self->edit_client_form(title => t8('Create a new client'));
238 sub action_edit_client {
240 $self->edit_client_form(title => t8('Edit Client'));
243 sub action_save_client {
245 my $params = delete($::form->{client}) || { };
246 my $is_new = !$params->{id};
248 # Assign empty arrays if the browser doesn't send those controls.
249 $params->{groups} ||= [];
250 $params->{users} ||= [];
252 $self->client($is_new ? SL::DB::AuthClient->new : SL::DB::AuthClient->new(id => $params->{id})->load)->assign_attributes(%{ $params });
254 my @errors = $self->client->validate;
257 flash('error', @errors);
258 $self->edit_client_form(title => $is_new ? t8('Create a new client') : t8('Edit Client'));
263 if ($self->client->is_default) {
264 SL::DB::Manager::AuthClient->update_all(set => { is_default => 0 }, where => [ '!id' => $self->client->id ]);
267 flash_later('info', $is_new ? t8('The client has been created.') : t8('The client has been saved.'));
268 $self->redirect_to(action => 'show');
271 sub action_delete_client {
274 if (!$self->client->delete) {
275 flash('error', t8('The client could not be deleted.'));
276 $self->edit_client_form(title => t8('Edit Client'));
280 flash_later('info', t8('The client has been deleted.'));
281 $self->redirect_to(action => 'show');
284 sub action_test_database_connectivity {
287 my %cfg = %{ $::form->{client} || {} };
288 my $dbconnect = 'dbi:Pg:dbname=' . $cfg{dbname} . ';host=' . $cfg{dbhost} . ';port=' . $cfg{dbport};
289 my $dbh = DBI->connect($dbconnect, $cfg{dbuser}, $cfg{dbpasswd});
292 my $error = $DBI::errstr;
294 $dbh->disconnect if $dbh;
296 $self->render('admin/test_db_connection', { layout => 0 },
297 title => t8('Database Connection Test'),
306 sub action_new_group {
309 $self->group(SL::DB::AuthGroup->new);
310 $self->edit_group_form(title => t8('Create a new group'));
313 sub action_edit_group {
315 $self->edit_group_form(title => t8('Edit User Group'));
318 sub action_save_group {
321 my $params = delete($::form->{group}) || { };
322 my $is_new = !$params->{id};
324 # Assign empty arrays if the browser doesn't send those controls.
325 $params->{clients} ||= [];
326 $params->{users} ||= [];
328 $self->group($is_new ? SL::DB::AuthGroup->new : SL::DB::AuthGroup->new(id => $params->{id})->load)->assign_attributes(%{ $params });
330 my @errors = $self->group->validate;
333 flash('error', @errors);
334 $self->edit_group_form(title => $is_new ? t8('Create a new user group') : t8('Edit User Group'));
340 flash_later('info', $is_new ? t8('The user group has been created.') : t8('The user group has been saved.'));
341 $self->redirect_to(action => 'show');
344 sub action_delete_group {
347 if (!$self->group->delete) {
348 flash('error', t8('The user group could not be deleted.'));
349 $self->edit_group_form(title => t8('Edit User Group'));
353 flash_later('info', t8('The user group has been deleted.'));
354 $self->redirect_to(action => 'show');
361 sub action_list_printers {
363 $self->render('admin/list_printers', title => t8('Printer management'));
366 sub action_new_printer {
369 $self->printer(SL::DB::Printer->new);
370 $self->edit_printer_form(title => t8('Create a new printer'));
373 sub action_edit_printer {
375 $self->edit_printer_form(title => t8('Edit Printer'));
378 sub action_save_printer {
380 my $params = delete($::form->{printer}) || { };
381 my $is_new = !$params->{id};
383 $self->printer($is_new ? SL::DB::Printer->new : SL::DB::Printer->new(id => $params->{id})->load)->assign_attributes(%{ $params });
385 my @errors = $self->printer->validate;
388 flash('error', @errors);
389 $self->edit_printer_form(title => $is_new ? t8('Create a new printer') : t8('Edit Printer'));
393 $self->printer->save;
395 flash_later('info', $is_new ? t8('The printer has been created.') : t8('The printer has been saved.'));
396 $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
399 sub action_delete_printer {
402 if (!$self->printer->delete) {
403 flash('error', t8('The printer could not be deleted.'));
404 $self->edit_printer_form(title => t8('Edit Printer'));
408 flash_later('info', t8('The printer has been deleted.'));
409 $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
413 # actions: database administration
416 sub action_create_dataset_login {
419 $self->database_administration_login_form(
420 title => t8('Create Dataset'),
421 next_action => 'create_dataset',
425 sub action_create_dataset {
428 my %superuser = $self->check_database_superuser_privileges(no_credentials_not_an_error => 1);
429 $self->create_dataset_form(superuser => \%superuser);
432 sub action_do_create_dataset {
435 my %superuser = $self->check_database_superuser_privileges;
438 push @errors, t8("Dataset missing!") if !$::form->{db};
439 push @errors, t8("Default currency missing!") if !$::form->{defaultcurrency};
440 push @errors, $superuser{error} if !$superuser{have_privileges} && $superuser{error};
443 flash('error', @errors);
444 return $self->create_dataset_form(superuser => \%superuser);
447 $::form->{encoding} = 'UNICODE';
448 User->new->dbcreate($::form);
450 flash_later('info', t8("The dataset #1 has been created.", $::form->{db}));
451 $self->redirect_to(action => 'show');
454 sub action_delete_dataset_login {
457 $self->database_administration_login_form(
458 title => t8('Delete Dataset'),
459 next_action => 'delete_dataset',
463 sub action_delete_dataset {
465 $self->delete_dataset_form;
468 sub action_do_delete_dataset {
472 push @errors, t8("Dataset missing!") if !$::form->{db};
475 flash('error', @errors);
476 return $self->delete_dataset_form;
479 User->new->dbdelete($::form);
481 flash_later('info', t8("The dataset #1 has been deleted.", $::form->{db}));
482 $self->redirect_to(action => 'show');
486 # actions: locking, unlocking
489 sub action_show_lock {
494 title => "kivitendo " . t8('Administration'),
498 sub action_unlock_system {
501 SL::System::InstallationLock->unlock;
502 flash_later('info', t8('Lockfile removed!'));
503 $self->redirect_to(action => 'show');
506 sub action_lock_system {
509 SL::System::InstallationLock->lock;
510 flash_later('info', t8('Lockfile created!'));
511 $self->redirect_to(action => 'show');
518 sub init_db_cfg { $::lx_office_conf{'authentication/database'} }
519 sub init_is_locked { SL::System::InstallationLock->is_locked }
520 sub init_client { SL::DB::Manager::AuthClient->find_by(id => (($::form->{client} || {})->{id} || $::form->{id})) }
521 sub init_user { SL::DB::AuthUser ->new(id => ($::form->{id} || ($::form->{user} || {})->{id}))->load }
522 sub init_group { SL::DB::AuthGroup ->new(id => ($::form->{id} || ($::form->{group} || {})->{id}))->load }
523 sub init_printer { SL::DB::Printer ->new(id => ($::form->{id} || ($::form->{printer} || {})->{id}))->load }
524 sub init_all_clients { SL::DB::Manager::AuthClient->get_all_sorted }
525 sub init_all_users { SL::DB::Manager::AuthUser ->get_all_sorted }
526 sub init_all_groups { SL::DB::Manager::AuthGroup ->get_all_sorted }
527 sub init_all_printers { SL::DB::Manager::Printer ->get_all_sorted }
528 sub init_all_dateformats { [ qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd) ] }
529 sub init_all_numberformats { [ '1,000.00', '1000.00', '1.000,00', '1000,00', "1'000.00" ] }
530 sub init_all_stylesheets { [ qw(lx-office-erp.css Mobile.css kivitendo.css design40.css) ] }
531 sub init_all_dbsources { [ sort User->dbsources($::form) ] }
532 sub init_all_used_dbsources { { map { (join(':', $_->dbhost || 'localhost', $_->dbport || 5432, $_->dbname) => $_->name) } @{ $_[0]->all_clients } } }
533 sub init_all_accounting_methods { [ { id => 'accrual', name => t8('Accrual accounting') }, { id => 'cash', name => t8('Cash accounting') } ] }
534 sub init_all_inventory_systems { [ { id => 'perpetual', name => t8('Perpetual inventory') }, { id => 'periodic', name => t8('Periodic inventory') } ] }
535 sub init_all_profit_determinations { [ { id => 'balance', name => t8('Balancing') }, { id => 'income', name => t8('Cash basis accounting') } ] }
537 sub init_all_charts {
538 tie my %dir_h, 'IO::Dir', 'sql/';
541 map { s/-chart\.sql$//; +{ id => $_ } }
543 grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ }
548 sub init_all_menustyles {
550 { id => 'old', title => $::locale->text('Old (on the side)') },
551 { id => 'v3', title => $::locale->text('Top (CSS)') },
552 { id => 'neu', title => $::locale->text('Top (Javascript)') },
556 sub init_all_rights {
557 my (@sections, $current_section);
559 foreach my $entry ($::auth->all_rights_full) {
561 push @sections, { description => t8($entry->[1]), rights => [] };
563 } elsif (@sections) {
564 push @{ $sections[-1]->{rights} }, {
566 description => t8($entry->[1]),
570 die "Right without sections: " . join('::', @{ $entry });
577 sub init_all_countrycodes {
578 my %cc = User->country_codes;
579 return [ map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc ];
587 my ($self, $action) = @_;
589 my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
590 $::request->layout(SL::Layout::Dispatcher->new(style => 'admin'));
591 $::form->{favicon} = "favicon.ico";
593 countrycode => $defaults->language('de'),
594 numberformat => $defaults->numberformat('1.000,00'),
595 dateformat => $defaults->dateformat('dd.mm.yy'),
602 $self->client(SL::DB::Manager::AuthClient->get_default || $self->all_clients->[0]) if !$self->client;
603 $::auth->set_client($self->client->id) if $self->client;
610 sub use_multiselect_js {
613 $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
618 my ($self, %params) = @_;
619 $::request->layout(SL::Layout::AdminLogin->new);
620 my $version = SL::Version->get_version;
621 $self->render('admin/adminlogin', title => t8('kivitendo v#1 administration', $version), %params, version => $version );
625 my ($self, %params) = @_;
626 $self->use_multiselect_js->render('admin/edit_user', %params);
629 sub edit_client_form {
630 my ($self, %params) = @_;
631 $self->use_multiselect_js->render('admin/edit_client', %params);
634 sub edit_group_form {
635 my ($self, %params) = @_;
636 $self->use_multiselect_js->render('admin/edit_group', %params);
639 sub edit_printer_form {
640 my ($self, %params) = @_;
641 $self->render('admin/edit_printer', %params);
644 sub database_administration_login_form {
645 my ($self, %params) = @_;
649 dbhost => $::form->{dbhost} || $::auth->{DB_config}->{host} || 'localhost',
650 dbport => $::form->{dbport} || $::auth->{DB_config}->{port} || 5432,
651 dbuser => $::form->{dbuser} || $::auth->{DB_config}->{user} || 'kivitendo',
652 dbpasswd => $::form->{dbpasswd} || $::auth->{DB_config}->{password},
653 dbdefault => $::form->{dbdefault} || 'template1',
658 sub create_dataset_form {
659 my ($self, %params) = @_;
661 my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
662 $::form->{favicon} = "favicon.ico";
663 $::form->{countrymode} = $defaults->country('DE');
664 $::form->{chart} = $defaults->chart_of_accounts('Germany-DATEV-SKR03EU');
665 $::form->{defaultcurrency} = $defaults->currency('EUR');
666 $::form->{precision} = $defaults->precision(0.01);
667 $::form->{accounting_method} = $defaults->accounting_method('cash');
668 $::form->{inventory_system} = $defaults->inventory_system('periodic');
669 $::form->{profit_determination} = $defaults->profit_determination('balance');
670 $::form->{feature_balance} = $defaults->feature_balance(1);
671 $::form->{feature_datev} = $defaults->feature_datev(1);
672 $::form->{feature_erfolgsrechnung} = $defaults->feature_erfolgsrechnung(0);
673 $::form->{feature_eurechnung} = $defaults->feature_eurechnung(1);
674 $::form->{feature_ustva} = $defaults->feature_ustva(1);
676 $self->render('admin/create_dataset', title => (t8('Database Administration') . " / " . t8('Create Dataset')), superuser => $params{superuser});
679 sub delete_dataset_form {
680 my ($self, %params) = @_;
681 $self->render('admin/delete_dataset', title => (t8('Database Administration') . " / " . t8('Delete Dataset')));
688 sub check_auth_db_and_tables {
691 if (!$::auth->check_database) {
692 $self->render('admin/check_auth_database', title => t8('Authentification database creation'));
696 if (!$::auth->check_tables) {
697 $self->render('admin/check_auth_tables', title => t8('Authentification tables creation'));
704 sub apply_dbupgrade_scripts {
705 return SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(1);
708 sub authenticate_root {
711 return 1 if $::auth->authenticate_root($::form->{'{AUTH}admin_password'}) == $::auth->OK();
713 $::auth->punish_wrong_login;
714 $::auth->delete_session_value('admin_password');
716 $self->login_form(error => t8('Incorrect password!'));
721 sub is_user_used_for_task_server {
722 my ($self, $user) = @_;
724 return undef if !$user;
725 return join ', ', sort_by { lc } map { $_->name } @{ SL::DB::Manager::AuthClient->get_all(where => [ task_server_user_id => $user->id ]) };
728 sub check_database_superuser_privileges {
729 my ($self, %params) = @_;
731 my %dbconnect_form = %{ $::form };
733 username => $dbconnect_form{dbuser},
734 password => $dbconnect_form{dbpasswd},
737 my $check_privileges = sub {
738 my $dbh = SL::DBConnect->connect($dbconnect_form{dbconnect}, $result{username}, $result{password}, SL::DBConnect->get_options);
739 return (error => $::locale->text('The credentials (username & password) for connecting database are wrong.')) if !$dbh;
741 my $is_superuser = SL::DBUtils::role_is_superuser($dbh, $result{username});
745 return (have_privileges => $is_superuser);
748 User::dbconnect_vars(\%dbconnect_form, $dbconnect_form{dbdefault});
752 $check_privileges->(),
755 if (!$result{have_privileges}) {
756 $result{username} = $::form->{database_superuser_user};
757 $result{password} = $::form->{database_superuser_password};
759 if ($::form->{database_superuser_user}) {
762 $check_privileges->(),
767 if ($result{have_privileges}) {
768 $::auth->set_session_value(database_superuser_username => $result{username}, database_superuser_password => $result{password});
772 $::auth->delete_session_value(qw(database_superuser_username database_superuser_password));
774 return () if !$::form->{database_superuser_user} && $params{no_credentials_not_an_error};
775 return (%result, error => $::locale->text('No superuser credentials were entered.')) if !$::form->{database_superuser_user};
776 return %result if $result{error};
777 return (%result, error => $::locale->text('The database user \'#1\' does not have superuser privileges.', $result{username}));
780 sub check_loginname_previously_used() {
783 my $clients = SL::DB::Manager::AuthClient->get_all_sorted;
784 for my $client (@$clients) {
785 my $dbh = $client->dbconnect();
787 my ($result) = $dbh->selectrow_array(qq|SELECT login FROM employee WHERE login = ?;|,undef,
788 $self->user->{'login'});