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