e6200896cb6704d04b44d93a32d671a32cb2cc89
[kivitendo-erp.git] / SL / Controller / Admin.pm
1 package SL::Controller::Admin;
2
3 use strict;
4
5 use parent qw(SL::Controller::Base);
6
7 use IO::Dir;
8 use List::Util qw(first);
9 use List::UtilsBy qw(sort_by);
10
11 use SL::Common ();
12 use SL::DB::AuthUser;
13 use SL::DB::AuthGroup;
14 use SL::DB::Printer;
15 use SL::DBUtils ();
16 use SL::Helper::Flash;
17 use SL::Locale::String qw(t8);
18 use SL::System::InstallationLock;
19 use SL::User;
20 use SL::Version;
21 use SL::Layout::AdminLogin;
22
23 use Rose::Object::MakeMethods::Generic
24 (
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) ],
28 );
29
30 __PACKAGE__->run_before(\&setup_layout);
31 __PACKAGE__->run_before(\&setup_client, only => [ qw(list_printers new_printer edit_printer save_printer delete_printer) ]);
32
33 sub get_auth_level { "admin" };
34 sub keep_auth_vars_in_form {
35   my ($class, %params) = @_;
36   return $params{action} eq 'login';
37 }
38
39 #
40 # actions: login, logout
41 #
42
43 sub action_login {
44   my ($self) = @_;
45
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;
50
51   $self->redirect_to(action => 'show');
52 }
53
54 sub action_logout {
55   my ($self) = @_;
56   $::auth->destroy_session;
57   $self->redirect_to(action => 'login');
58 }
59
60 #
61 # actions: creating the authentication database & tables, applying database ugprades
62 #
63
64 sub action_apply_dbupgrade_scripts {
65   my ($self) = @_;
66
67   return if $self->apply_dbupgrade_scripts;
68   $self->redirect_to(action => 'show');
69 }
70
71 sub action_create_auth_db {
72   my ($self) = @_;
73
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;
78 }
79
80 sub action_create_auth_tables {
81   my ($self) = @_;
82
83   $::auth->create_tables;
84   $::auth->set_session_value('admin_password', $::lx_office_conf{authentication}->{admin_password});
85   $::auth->create_or_refresh_session;
86
87   my $scripts_applied = $self->apply_dbupgrade_scripts;
88
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 ],
94     )->save;
95   }
96
97   $self->action_login unless $scripts_applied;
98 }
99
100 #
101 # actions: users
102 #
103
104 sub action_show {
105   my ($self) = @_;
106
107   $self->render(
108     "admin/show",
109     title => "kivitendo " . t8('Administration'),
110   );
111 }
112
113 sub action_new_user {
114   my ($self) = @_;
115
116   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
117   $self->user(SL::DB::AuthUser->new(
118     config_values => {
119       countrycode  => $defaults->language('de'),
120       numberformat => $defaults->numberformat('1.000,00'),
121       dateformat   => $defaults->dateformat('dd.mm.yy'),
122       stylesheet   => "kivitendo.css",
123       menustyle    => "neu",
124     },
125   ));
126
127   $self->edit_user_form(title => t8('Create a new user'));
128 }
129
130 sub action_edit_user {
131   my ($self) = @_;
132   $self->edit_user_form(title => t8('Edit User'));
133 }
134
135 sub action_save_user {
136   my ($self) = @_;
137   my $params = delete($::form->{user})          || { };
138   my $props  = delete($params->{config_values}) || { };
139   my $is_new = !$params->{id};
140
141   # Assign empty arrays if the browser doesn't send those controls.
142   $params->{clients} ||= [];
143   $params->{groups}  ||= [];
144
145   $self->user($is_new ? SL::DB::AuthUser->new : SL::DB::AuthUser->new(id => $params->{id})->load)
146     ->assign_attributes(%{ $params })
147     ->config_values({ %{ $self->user->config_values }, %{ $props } });
148
149   my @errors = $self->user->validate;
150
151   if (@errors) {
152     flash('error', @errors);
153     $self->edit_user_form(title => $is_new ? t8('Create a new user') : t8('Edit User'));
154     return;
155   }
156
157   $self->user->save;
158
159   if ($::auth->can_change_password && $::form->{new_password}) {
160     $::auth->change_password($self->user->login, $::form->{new_password});
161   }
162
163   flash_later('info', $is_new ? t8('The user has been created.') : t8('The user has been saved.'));
164   $self->redirect_to(action => 'show');
165 }
166
167 sub action_delete_user {
168   my ($self) = @_;
169
170   my @clients = @{ $self->user->clients || [] };
171
172   # backup user metadata (email, name, etc)
173   my $user_config_values_ref = $self->user->config_values();
174   my $login =$self->user->login;
175
176   if (!$self->user->delete) {
177     flash('error', t8('The user could not be deleted.'));
178     $self->edit_user_form(title => t8('Edit User'));
179     return;
180   }
181
182   # Flag corresponding entries in 'employee' as deleted.
183   # and restore the most important user data in employee
184   # TODO try and catch the whole transaction {user->delete; update employee} {exception}
185   foreach my $client (@clients) {
186     my $dbh = $client->dbconnect(AutoCommit => 1) || next;
187     $dbh->do(qq|UPDATE employee SET deleted = TRUE, name = ?, deleted_email = ?,
188                 deleted_tel = ?, deleted_fax = ?, deleted_signature = ? WHERE login = ?|,undef,
189               $user_config_values_ref->{name}, $user_config_values_ref->{email},
190               $user_config_values_ref->{tel}, $user_config_values_ref->{fax},
191               $user_config_values_ref->{signature}, $self->user->login);
192     $dbh->disconnect;
193   }
194
195   flash_later('info', t8('The user has been deleted.'));
196   $self->redirect_to(action => 'show');
197 }
198
199 #
200 # actions: clients
201 #
202
203 sub action_new_client {
204   my ($self) = @_;
205
206   $self->client(SL::DB::AuthClient->new(
207     dbhost   => $::auth->{DB_config}->{host},
208     dbport   => $::auth->{DB_config}->{port},
209     dbuser   => $::auth->{DB_config}->{user},
210     dbpasswd => $::auth->{DB_config}->{password},
211   ));
212
213   $self->edit_client_form(title => t8('Create a new client'));
214 }
215
216 sub action_edit_client {
217   my ($self) = @_;
218   $self->edit_client_form(title => t8('Edit Client'));
219 }
220
221 sub action_save_client {
222   my ($self) = @_;
223   my $params = delete($::form->{client}) || { };
224   my $is_new = !$params->{id};
225
226   # Assign empty arrays if the browser doesn't send those controls.
227   $params->{groups} ||= [];
228   $params->{users}  ||= [];
229
230   $self->client($is_new ? SL::DB::AuthClient->new : SL::DB::AuthClient->new(id => $params->{id})->load)->assign_attributes(%{ $params });
231
232   my @errors = $self->client->validate;
233
234   if (@errors) {
235     flash('error', @errors);
236     $self->edit_client_form(title => $is_new ? t8('Create a new client') : t8('Edit Client'));
237     return;
238   }
239
240   $self->client->save;
241   if ($self->client->is_default) {
242     SL::DB::Manager::AuthClient->update_all(set => { is_default => 0 }, where => [ '!id' => $self->client->id ]);
243   }
244
245   flash_later('info', $is_new ? t8('The client has been created.') : t8('The client has been saved.'));
246   $self->redirect_to(action => 'show');
247 }
248
249 sub action_delete_client {
250   my ($self) = @_;
251
252   if (!$self->client->delete) {
253     flash('error', t8('The client could not be deleted.'));
254     $self->edit_client_form(title => t8('Edit Client'));
255     return;
256   }
257
258   flash_later('info', t8('The client has been deleted.'));
259   $self->redirect_to(action => 'show');
260 }
261
262 sub action_test_database_connectivity {
263   my ($self)    = @_;
264
265   my %cfg       = %{ $::form->{client} || {} };
266   my $dbconnect = 'dbi:Pg:dbname=' . $cfg{dbname} . ';host=' . $cfg{dbhost} . ';port=' . $cfg{dbport};
267   my $dbh       = DBI->connect($dbconnect, $cfg{dbuser}, $cfg{dbpasswd});
268
269   my $ok        = !!$dbh;
270   my $error     = $DBI::errstr;
271
272   $dbh->disconnect if $dbh;
273
274   $self->render('admin/test_db_connection', { layout => 0 },
275                 title => t8('Database Connection Test'),
276                 ok    => $ok,
277                 error => $error);
278 }
279
280 #
281 # actions: groups
282 #
283
284 sub action_new_group {
285   my ($self) = @_;
286
287   $self->group(SL::DB::AuthGroup->new);
288   $self->edit_group_form(title => t8('Create a new group'));
289 }
290
291 sub action_edit_group {
292   my ($self) = @_;
293   $self->edit_group_form(title => t8('Edit User Group'));
294 }
295
296 sub action_save_group {
297   my ($self) = @_;
298
299   my $params = delete($::form->{group}) || { };
300   my $is_new = !$params->{id};
301
302   # Assign empty arrays if the browser doesn't send those controls.
303   $params->{clients} ||= [];
304   $params->{users}   ||= [];
305
306   $self->group($is_new ? SL::DB::AuthGroup->new : SL::DB::AuthGroup->new(id => $params->{id})->load)->assign_attributes(%{ $params });
307
308   my @errors = $self->group->validate;
309
310   if (@errors) {
311     flash('error', @errors);
312     $self->edit_group_form(title => $is_new ? t8('Create a new user group') : t8('Edit User Group'));
313     return;
314   }
315
316   $self->group->save;
317
318   flash_later('info', $is_new ? t8('The user group has been created.') : t8('The user group has been saved.'));
319   $self->redirect_to(action => 'show');
320 }
321
322 sub action_delete_group {
323   my ($self) = @_;
324
325   if (!$self->group->delete) {
326     flash('error', t8('The user group could not be deleted.'));
327     $self->edit_group_form(title => t8('Edit User Group'));
328     return;
329   }
330
331   flash_later('info', t8('The user group has been deleted.'));
332   $self->redirect_to(action => 'show');
333 }
334
335 #
336 # actions: printers
337 #
338
339 sub action_list_printers {
340   my ($self) = @_;
341   $self->render('admin/list_printers', title => t8('Printer management'));
342 }
343
344 sub action_new_printer {
345   my ($self) = @_;
346
347   $self->printer(SL::DB::Printer->new);
348   $self->edit_printer_form(title => t8('Create a new printer'));
349 }
350
351 sub action_edit_printer {
352   my ($self) = @_;
353   $self->edit_printer_form(title => t8('Edit Printer'));
354 }
355
356 sub action_save_printer {
357   my ($self) = @_;
358   my $params = delete($::form->{printer}) || { };
359   my $is_new = !$params->{id};
360
361   $self->printer($is_new ? SL::DB::Printer->new : SL::DB::Printer->new(id => $params->{id})->load)->assign_attributes(%{ $params });
362
363   my @errors = $self->printer->validate;
364
365   if (@errors) {
366     flash('error', @errors);
367     $self->edit_printer_form(title => $is_new ? t8('Create a new printer') : t8('Edit Printer'));
368     return;
369   }
370
371   $self->printer->save;
372
373   flash_later('info', $is_new ? t8('The printer has been created.') : t8('The printer has been saved.'));
374   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
375 }
376
377 sub action_delete_printer {
378   my ($self) = @_;
379
380   if (!$self->printer->delete) {
381     flash('error', t8('The printer could not be deleted.'));
382     $self->edit_printer_form(title => t8('Edit Printer'));
383     return;
384   }
385
386   flash_later('info', t8('The printer has been deleted.'));
387   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
388 }
389
390 #
391 # actions: database administration
392 #
393
394 sub action_create_dataset_login {
395   my ($self) = @_;
396
397   $self->database_administration_login_form(
398     title       => t8('Create Dataset'),
399     next_action => 'create_dataset',
400   );
401 }
402
403 sub action_create_dataset {
404   my ($self) = @_;
405
406   my %superuser = $self->check_database_superuser_privileges(no_credentials_not_an_error => 1);
407   $self->create_dataset_form(superuser => \%superuser);
408 }
409
410 sub action_do_create_dataset {
411   my ($self) = @_;
412
413   my %superuser = $self->check_database_superuser_privileges;
414
415   my @errors;
416   push @errors, t8("Dataset missing!")          if !$::form->{db};
417   push @errors, t8("Default currency missing!") if !$::form->{defaultcurrency};
418   push @errors, $superuser{error}               if !$superuser{have_privileges} && $superuser{error};
419
420   if (@errors) {
421     flash('error', @errors);
422     return $self->create_dataset_form(superuser => \%superuser);
423   }
424
425   $::form->{encoding} = 'UNICODE';
426   User->new->dbcreate($::form);
427
428   flash_later('info', t8("The dataset #1 has been created.", $::form->{db}));
429   $self->redirect_to(action => 'show');
430 }
431
432 sub action_delete_dataset_login {
433   my ($self) = @_;
434
435   $self->database_administration_login_form(
436     title       => t8('Delete Dataset'),
437     next_action => 'delete_dataset',
438   );
439 }
440
441 sub action_delete_dataset {
442   my ($self) = @_;
443   $self->delete_dataset_form;
444 }
445
446 sub action_do_delete_dataset {
447   my ($self) = @_;
448
449   my @errors;
450   push @errors, t8("Dataset missing!") if !$::form->{db};
451
452   if (@errors) {
453     flash('error', @errors);
454     return $self->delete_dataset_form;
455   }
456
457   User->new->dbdelete($::form);
458
459   flash_later('info', t8("The dataset #1 has been deleted.", $::form->{db}));
460   $self->redirect_to(action => 'show');
461 }
462
463 #
464 # actions: locking, unlocking
465 #
466
467 sub action_show_lock {
468   my ($self) = @_;
469
470   $self->render(
471     "admin/show_lock",
472     title => "kivitendo " . t8('Administration'),
473   );
474 }
475
476 sub action_unlock_system {
477   my ($self) = @_;
478
479   SL::System::InstallationLock->unlock;
480   flash_later('info', t8('Lockfile removed!'));
481   $self->redirect_to(action => 'show');
482 }
483
484 sub action_lock_system {
485   my ($self) = @_;
486
487   SL::System::InstallationLock->lock;
488   flash_later('info', t8('Lockfile created!'));
489   $self->redirect_to(action => 'show');
490 }
491
492 #
493 # initializers
494 #
495
496 sub init_db_cfg            { $::lx_office_conf{'authentication/database'}                                                    }
497 sub init_is_locked         { SL::System::InstallationLock->is_locked                                                         }
498 sub init_client            { SL::DB::Manager::AuthClient->find_by(id => (($::form->{client} || {})->{id} || $::form->{id}))  }
499 sub init_user              { SL::DB::AuthUser  ->new(id => ($::form->{id} || ($::form->{user}    || {})->{id}))->load        }
500 sub init_group             { SL::DB::AuthGroup ->new(id => ($::form->{id} || ($::form->{group}   || {})->{id}))->load        }
501 sub init_printer           { SL::DB::Printer   ->new(id => ($::form->{id} || ($::form->{printer} || {})->{id}))->load        }
502 sub init_all_clients       { SL::DB::Manager::AuthClient->get_all_sorted                                                     }
503 sub init_all_users         { SL::DB::Manager::AuthUser  ->get_all_sorted                                                     }
504 sub init_all_groups        { SL::DB::Manager::AuthGroup ->get_all_sorted                                                     }
505 sub init_all_printers      { SL::DB::Manager::Printer   ->get_all_sorted                                                     }
506 sub init_all_dateformats   { [ qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd)      ]                                              }
507 sub init_all_numberformats { [ '1,000.00', '1000.00', '1.000,00', '1000,00', "1'000.00" ]                                    }
508 sub init_all_stylesheets   { [ qw(lx-office-erp.css Mobile.css kivitendo.css) ]                                              }
509 sub init_all_dbsources             { [ sort User->dbsources($::form)                               ] }
510 sub init_all_used_dbsources        { { map { (join(':', $_->dbhost || 'localhost', $_->dbport || 5432, $_->dbname) => $_->name) } @{ $_[0]->all_clients }  } }
511 sub init_all_accounting_methods    { [ { id => 'accrual',   name => t8('Accrual accounting')  }, { id => 'cash',     name => t8('Cash accounting')       } ] }
512 sub init_all_inventory_systems     { [ { id => 'perpetual', name => t8('Perpetual inventory') }, { id => 'periodic', name => t8('Periodic inventory')    } ] }
513 sub init_all_profit_determinations { [ { id => 'balance',   name => t8('Balancing')           }, { id => 'income',   name => t8('Cash basis accounting') } ] }
514
515 sub init_all_charts {
516   tie my %dir_h, 'IO::Dir', 'sql/';
517
518   return [
519     map { s/-chart\.sql$//; +{ id => $_ } }
520     sort
521     grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ }
522     keys %dir_h
523   ];
524 }
525
526 sub init_all_menustyles    {
527   return [
528     { id => 'old', title => $::locale->text('Old (on the side)') },
529     { id => 'v3',  title => $::locale->text('Top (CSS)') },
530     { id => 'neu', title => $::locale->text('Top (Javascript)') },
531   ];
532 }
533
534 sub init_all_rights {
535   my (@sections, $current_section);
536
537   foreach my $entry ($::auth->all_rights_full) {
538     if ($entry->[2]) {
539       push @sections, { description => t8($entry->[1]), rights => [] };
540
541     } elsif (@sections) {
542       push @{ $sections[-1]->{rights} }, {
543         name        => $entry->[0],
544         description => t8($entry->[1]),
545       };
546
547     } else {
548       die "Right without sections: " . join('::', @{ $entry });
549     }
550   }
551
552   return \@sections;
553 }
554
555 sub init_all_countrycodes {
556   my %cc = User->country_codes;
557   return [ map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc ];
558 }
559
560 #
561 # filters
562 #
563
564 sub setup_layout {
565   my ($self, $action) = @_;
566
567   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
568   $::request->layout(SL::Layout::Dispatcher->new(style => 'admin'));
569   $::form->{favicon} = "favicon.ico";
570   %::myconfig        = (
571     countrycode      => $defaults->language('de'),
572     numberformat     => $defaults->numberformat('1.000,00'),
573     dateformat       => $defaults->dateformat('dd.mm.yy'),
574   ) if !%::myconfig;
575 }
576
577 sub setup_client {
578   my ($self) = @_;
579
580   $self->client(SL::DB::Manager::AuthClient->get_default || $self->all_clients->[0]) if !$self->client;
581   $::auth->set_client($self->client->id) if $self->client;
582 }
583
584 #
585 # displaying forms
586 #
587
588 sub use_multiselect_js {
589   my ($self) = @_;
590
591   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
592   return $self;
593 }
594
595 sub login_form {
596   my ($self, %params) = @_;
597   $::request->layout(SL::Layout::AdminLogin->new);
598   my $version         = SL::Version->get_version;
599   $self->render('admin/adminlogin', title => t8('kivitendo v#1 administration', $version), %params, version => $version );
600 }
601
602 sub edit_user_form {
603   my ($self, %params) = @_;
604   $self->use_multiselect_js->render('admin/edit_user', %params);
605 }
606
607 sub edit_client_form {
608   my ($self, %params) = @_;
609   $self->use_multiselect_js->render('admin/edit_client', %params);
610 }
611
612 sub edit_group_form {
613   my ($self, %params) = @_;
614   $self->use_multiselect_js->render('admin/edit_group', %params);
615 }
616
617 sub edit_printer_form {
618   my ($self, %params) = @_;
619   $self->render('admin/edit_printer', %params);
620 }
621
622 sub database_administration_login_form {
623   my ($self, %params) = @_;
624
625   $self->render(
626     'admin/dbadmin',
627     dbhost    => $::form->{dbhost}    || $::auth->{DB_config}->{host} || 'localhost',
628     dbport    => $::form->{dbport}    || $::auth->{DB_config}->{port} || 5432,
629     dbuser    => $::form->{dbuser}    || $::auth->{DB_config}->{user} || 'kivitendo',
630     dbpasswd  => $::form->{dbpasswd}  || $::auth->{DB_config}->{password},
631     dbdefault => $::form->{dbdefault} || 'template1',
632     %params,
633   );
634 }
635
636 sub create_dataset_form {
637   my ($self, %params) = @_;
638
639   my $defaults = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
640   $::form->{favicon} = "favicon.ico";
641   $::form->{countrymode}             = $defaults->country('DE');
642   $::form->{chart}                   = $defaults->chart_of_accounts('Germany-DATEV-SKR03EU');
643   $::form->{defaultcurrency}         = $defaults->currency('EUR');
644   $::form->{precision}               = $defaults->precision(0.01);
645   $::form->{accounting_method}       = $defaults->accounting_method('cash');
646   $::form->{inventory_system}        = $defaults->inventory_system('periodic');
647   $::form->{profit_determination}    = $defaults->profit_determination('balance');
648   $::form->{feature_balance}         = $defaults->feature_balance(1);
649   $::form->{feature_datev}           = $defaults->feature_datev(1);
650   $::form->{feature_erfolgsrechnung} = $defaults->feature_erfolgsrechnung(0);
651   $::form->{feature_eurechnung}      = $defaults->feature_eurechnung(1);
652   $::form->{feature_ustva}           = $defaults->feature_ustva(1);
653
654   $self->render('admin/create_dataset', title => (t8('Database Administration') . " / " . t8('Create Dataset')), superuser => $params{superuser});
655 }
656
657 sub delete_dataset_form {
658   my ($self, %params) = @_;
659   $self->render('admin/delete_dataset', title => (t8('Database Administration') . " / " . t8('Delete Dataset')));
660 }
661
662 #
663 # helpers
664 #
665
666 sub check_auth_db_and_tables {
667   my ($self) = @_;
668
669   if (!$::auth->check_database) {
670     $self->render('admin/check_auth_database', title => t8('Authentification database creation'));
671     return 0;
672   }
673
674   if (!$::auth->check_tables) {
675     $self->render('admin/check_auth_tables', title => t8('Authentification tables creation'));
676     return 0;
677   }
678
679   return 1;
680 }
681
682 sub apply_dbupgrade_scripts {
683   return SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(1);
684 }
685
686 sub authenticate_root {
687   my ($self) = @_;
688
689   return 1 if $::auth->authenticate_root($::form->{'{AUTH}admin_password'}) == $::auth->OK();
690
691   $::auth->punish_wrong_login;
692   $::auth->delete_session_value('admin_password');
693
694   $self->login_form(error => t8('Incorrect password!'));
695
696   return undef;
697 }
698
699 sub is_user_used_for_task_server {
700   my ($self, $user) = @_;
701
702   return undef if !$user;
703   return join ', ', sort_by { lc } map { $_->name } @{ SL::DB::Manager::AuthClient->get_all(where => [ task_server_user_id => $user->id ]) };
704 }
705
706 sub check_database_superuser_privileges {
707   my ($self, %params) = @_;
708
709   my %dbconnect_form = %{ $::form };
710   my %result         = (
711     username => $dbconnect_form{dbuser},
712     password => $dbconnect_form{dbpasswd},
713   );
714
715   my $check_privileges = sub {
716     my $dbh = SL::DBConnect->connect($dbconnect_form{dbconnect}, $result{username}, $result{password}, SL::DBConnect->get_options);
717     return (error => $::locale->text('The credentials (username & password) for connecting database are wrong.')) if !$dbh;
718
719     my $is_superuser = SL::DBUtils::role_is_superuser($dbh, $result{username});
720
721     $dbh->disconnect;
722
723     return (have_privileges => $is_superuser);
724   };
725
726   User::dbconnect_vars(\%dbconnect_form, $dbconnect_form{dbdefault});
727
728   %result = (
729     %result,
730     $check_privileges->(),
731   );
732
733   if (!$result{have_privileges}) {
734     $result{username} = $::form->{database_superuser_user};
735     $result{password} = $::form->{database_superuser_password};
736
737     if ($::form->{database_superuser_user}) {
738       %result = (
739         %result,
740         $check_privileges->(),
741       );
742     }
743   }
744
745   if ($result{have_privileges}) {
746     $::auth->set_session_value(database_superuser_username => $result{username}, database_superuser_password => $result{password});
747     return %result;
748   }
749
750   $::auth->delete_session_value(qw(database_superuser_username database_superuser_password));
751
752   return ()                                                                            if !$::form->{database_superuser_user} && $params{no_credentials_not_an_error};
753   return (%result, error => $::locale->text('No superuser credentials were entered.')) if !$::form->{database_superuser_user};
754   return %result                                                                       if $result{error};
755   return (%result, error => $::locale->text('The database user \'#1\' does not have superuser privileges.', $result{username}));
756 }
757
758 1;