4e46e9879c36c918b8ab819cfb8f43cb363cccf7
[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::File;
8 use List::Util qw(first);
9
10 use SL::DB::AuthUser;
11 use SL::DB::AuthGroup;
12 use SL::DB::Printer;
13 use SL::Helper::Flash;
14 use SL::Locale::String qw(t8);
15 use SL::System::InstallationLock;
16 use SL::User;
17
18 use Rose::Object::MakeMethods::Generic
19 (
20   'scalar --get_set_init' => [ qw(client user group printer db_cfg is_locked
21                                   all_dateformats all_numberformats all_countrycodes all_stylesheets all_menustyles all_clients all_groups all_users all_rights all_printers) ],
22 );
23
24 __PACKAGE__->run_before(\&setup_layout);
25 __PACKAGE__->run_before(\&setup_client, only => [ qw(list_printers new_printer edit_printer save_printer delete_printer) ]);
26
27 sub get_auth_level { "admin" };
28 sub keep_auth_vars {
29   my ($class, %params) = @_;
30   return $params{action} eq 'login';
31 }
32
33 #
34 # actions: login, logout
35 #
36
37 sub action_login {
38   my ($self) = @_;
39
40   return $self->login_form if !$::form->{do_login};
41   return                   if !$self->authenticate_root;
42   return                   if !$self->check_auth_db_and_tables;
43   return                   if  $self->apply_dbupgrade_scripts;
44
45   $self->redirect_to(action => 'show');
46 }
47
48 sub action_logout {
49   my ($self) = @_;
50   $::auth->destroy_session;
51   $self->redirect_to(action => 'login');
52 }
53
54 #
55 # actions: creating the authentication database & tables, applying database ugprades
56 #
57
58 sub action_apply_dbupgrade_scripts {
59   my ($self) = @_;
60
61   return if $self->apply_dbupgrade_scripts;
62   $self->redirect_to(action => 'show');
63 }
64
65 sub action_create_auth_db {
66   my ($self) = @_;
67
68   $::auth->create_database(superuser          => $::form->{db_superuser},
69                            superuser_password => $::form->{db_superuser_password},
70                            template           => $::form->{db_template});
71   $self->check_auth_db_and_tables;
72 }
73
74 sub action_create_auth_tables {
75   my ($self) = @_;
76
77   $::auth->create_tables;
78   $::auth->set_session_value('admin_password', $::lx_office_conf{authentication}->{admin_password});
79   $::auth->create_or_refresh_session;
80
81   my $group = (SL::DB::Manager::AuthGroup->get_all(limit => 1))[0];
82   if (!$group) {
83     SL::DB::AuthGroup->new(
84       name        => t8('Full Access'),
85       description => t8('Full access to all functions'),
86       rights      => [ map { SL::DB::AuthGroupRight->new(right => $_, granted => 1) } SL::Auth::all_rights() ],
87     )->save;
88   }
89
90   if (!$self->apply_dbupgrade_scripts) {
91     $self->action_login;
92   }
93 }
94
95 #
96 # actions: users
97 #
98
99 sub action_show {
100   my ($self) = @_;
101
102   $self->render(
103     "admin/show",
104     title => "kivitendo " . t8('Administration'),
105   );
106 }
107
108 sub action_new_user {
109   my ($self) = @_;
110
111   $self->user(SL::DB::AuthUser->new(
112     config_values => {
113       vclimit      => 200,
114       countrycode  => "de",
115       numberformat => "1.000,00",
116       dateformat   => "dd.mm.yy",
117       stylesheet   => "kivitendo.css",
118       menustyle    => "neu",
119     },
120   ));
121
122   $self->edit_user_form(title => t8('Create a new user'));
123 }
124
125 sub action_edit_user {
126   my ($self) = @_;
127   $self->edit_user_form(title => t8('Edit User'));
128 }
129
130 sub action_save_user {
131   my ($self) = @_;
132   my $params = delete($::form->{user})          || { };
133   my $props  = delete($params->{config_values}) || { };
134   my $is_new = !$params->{id};
135
136   $self->user($is_new ? SL::DB::AuthUser->new : SL::DB::AuthUser->new(id => $params->{id})->load)
137     ->assign_attributes(%{ $params })
138     ->config_values({ %{ $self->user->config_values }, %{ $props } });
139
140   my @errors = $self->user->validate;
141
142   if (@errors) {
143     flash('error', @errors);
144     $self->edit_user_form(title => $is_new ? t8('Create a new user') : t8('Edit User'));
145     return;
146   }
147
148   $self->user->save;
149
150   if ($::auth->can_change_password && $::form->{new_password}) {
151     $::auth->change_password($self->user->login, $::form->{new_password});
152   }
153
154   flash_later('info', $is_new ? t8('The user has been created.') : t8('The user has been saved.'));
155   $self->redirect_to(action => 'show');
156 }
157
158 sub action_delete_user {
159   my ($self) = @_;
160
161   my @clients = @{ $self->user->clients || [] };
162
163   if (!$self->user->delete) {
164     flash('error', t8('The user could not be deleted.'));
165     $self->edit_user_form(title => t8('Edit User'));
166     return;
167   }
168
169   # Flag corresponding entries in 'employee' as deleted.
170   foreach my $client (@clients) {
171     my $dbh = $client->dbconnect(AutoCommit => 1) || next;
172     $dbh->do(qq|UPDATE employee SET deleted = TRUE WHERE login = ?|, undef, $self->user->login);
173     $dbh->disconnect;
174   }
175
176   flash_later('info', t8('The user has been deleted.'));
177   $self->redirect_to(action => 'show');
178 }
179
180 #
181 # actions: clients
182 #
183
184 sub action_new_client {
185   my ($self) = @_;
186
187   $self->client(SL::DB::AuthClient->new(
188     dbhost   => $::auth->{DB_config}->{host},
189     dbport   => $::auth->{DB_config}->{port},
190     dbuser   => $::auth->{DB_config}->{user},
191     dbpasswd => $::auth->{DB_config}->{password},
192   ));
193
194   $self->edit_client_form(title => t8('Create a new client'));
195 }
196
197 sub action_edit_client {
198   my ($self) = @_;
199   $self->edit_client_form(title => t8('Edit Client'));
200 }
201
202 sub action_save_client {
203   my ($self) = @_;
204   my $params = delete($::form->{client}) || { };
205   my $is_new = !$params->{id};
206
207   $self->client($is_new ? SL::DB::AuthClient->new : SL::DB::AuthClient->new(id => $params->{id})->load)->assign_attributes(%{ $params });
208
209   my @errors = $self->client->validate;
210
211   if (@errors) {
212     flash('error', @errors);
213     $self->edit_client_form(title => $is_new ? t8('Create a new client') : t8('Edit Client'));
214     return;
215   }
216
217   $self->client->save;
218   if ($self->client->is_default) {
219     SL::DB::Manager::AuthClient->update_all(set => { is_default => 0 }, where => [ '!id' => $self->client->id ]);
220   }
221
222   flash_later('info', $is_new ? t8('The client has been created.') : t8('The client has been saved.'));
223   $self->redirect_to(action => 'show');
224 }
225
226 sub action_delete_client {
227   my ($self) = @_;
228
229   if (!$self->client->delete) {
230     flash('error', t8('The client could not be deleted.'));
231     $self->edit_client_form(title => t8('Edit Client'));
232     return;
233   }
234
235   flash_later('info', t8('The client has been deleted.'));
236   $self->redirect_to(action => 'show');
237 }
238
239 sub action_test_database_connectivity {
240   my ($self)    = @_;
241
242   my %cfg       = %{ $::form->{client} || {} };
243   my $dbconnect = 'dbi:Pg:dbname=' . $cfg{dbname} . ';host=' . $cfg{dbhost} . ';port=' . $cfg{dbport};
244   my $dbh       = DBI->connect($dbconnect, $cfg{dbuser}, $cfg{dbpasswd});
245
246   my $ok        = !!$dbh;
247   my $error     = $DBI::errstr;
248
249   $dbh->disconnect if $dbh;
250
251   $self->render('admin/test_db_connection',
252                 title => t8('Database Connection Test'),
253                 ok    => $ok,
254                 error => $error);
255 }
256
257 #
258 # actions: groups
259 #
260
261 sub action_new_group {
262   my ($self) = @_;
263
264   $self->group(SL::DB::AuthGroup->new);
265   $self->edit_group_form(title => t8('Create a new group'));
266 }
267
268 sub action_edit_group {
269   my ($self) = @_;
270   $self->edit_group_form(title => t8('Edit User Group'));
271 }
272
273 sub action_save_group {
274   my ($self) = @_;
275
276   my $params = delete($::form->{group}) || { };
277   my $is_new = !$params->{id};
278
279   $self->group($is_new ? SL::DB::AuthGroup->new : SL::DB::AuthGroup->new(id => $params->{id})->load)->assign_attributes(%{ $params });
280
281   my @errors = $self->group->validate;
282
283   if (@errors) {
284     flash('error', @errors);
285     $self->edit_group_form(title => $is_new ? t8('Create a new user group') : t8('Edit User Group'));
286     return;
287   }
288
289   $self->group->save;
290
291   flash_later('info', $is_new ? t8('The user group has been created.') : t8('The user group has been saved.'));
292   $self->redirect_to(action => 'show');
293 }
294
295 sub action_delete_group {
296   my ($self) = @_;
297
298   if (!$self->group->delete) {
299     flash('error', t8('The user group could not be deleted.'));
300     $self->edit_group_form(title => t8('Edit User Group'));
301     return;
302   }
303
304   flash_later('info', t8('The user group has been deleted.'));
305   $self->redirect_to(action => 'show');
306 }
307
308 #
309 # actions: printers
310 #
311
312 sub action_list_printers {
313   my ($self) = @_;
314   $self->render('admin/list_printers', title => t8('Printer management'));
315 }
316
317 sub action_new_printer {
318   my ($self) = @_;
319
320   $self->printer(SL::DB::Printer->new);
321   $self->edit_printer_form(title => t8('Create a new printer'));
322 }
323
324 sub action_edit_printer {
325   my ($self) = @_;
326   $self->edit_printer_form(title => t8('Edit Printer'));
327 }
328
329 sub action_save_printer {
330   my ($self) = @_;
331   my $params = delete($::form->{printer}) || { };
332   my $is_new = !$params->{id};
333
334   $self->printer($is_new ? SL::DB::Printer->new : SL::DB::Printer->new(id => $params->{id})->load)->assign_attributes(%{ $params });
335
336   my @errors = $self->printer->validate;
337
338   if (@errors) {
339     flash('error', @errors);
340     $self->edit_printer_form(title => $is_new ? t8('Create a new printer') : t8('Edit Printer'));
341     return;
342   }
343
344   $self->printer->save;
345
346   flash_later('info', $is_new ? t8('The printer has been created.') : t8('The printer has been saved.'));
347   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
348 }
349
350 sub action_delete_printer {
351   my ($self) = @_;
352
353   if (!$self->printer->delete) {
354     flash('error', t8('The printer could not be deleted.'));
355     $self->edit_printer_form(title => t8('Edit Printer'));
356     return;
357   }
358
359   flash_later('info', t8('The printer has been deleted.'));
360   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
361 }
362
363 #
364 # actions: locking, unlocking
365 #
366
367 sub action_unlock_system {
368   my ($self) = @_;
369
370   SL::System::InstallationLock->unlock;
371   flash_later('info', t8('Lockfile removed!'));
372   $self->redirect_to(action => 'show');
373 }
374
375 sub action_lock_system {
376   my ($self) = @_;
377
378   SL::System::InstallationLock->unlock;
379   flash_later('info', t8('Lockfile created!'));
380   $self->redirect_to(action => 'show');
381 }
382
383 #
384 # initializers
385 #
386
387 sub init_db_cfg            { $::lx_office_conf{'authentication/database'}                                                    }
388 sub init_is_locked         { SL::System::InstallationLock->is_locked                                                         }
389 sub init_client            { SL::DB::Manager::AuthClient->find_by(id => ($::form->{id} || ($::form->{client}  || {})->{id})) }
390 sub init_user              { SL::DB::AuthUser  ->new(id => ($::form->{id} || ($::form->{user}    || {})->{id}))->load        }
391 sub init_group             { SL::DB::AuthGroup ->new(id => ($::form->{id} || ($::form->{group}   || {})->{id}))->load        }
392 sub init_printer           { SL::DB::Printer   ->new(id => ($::form->{id} || ($::form->{printer} || {})->{id}))->load        }
393 sub init_all_clients       { SL::DB::Manager::AuthClient->get_all_sorted                                                     }
394 sub init_all_users         { SL::DB::Manager::AuthUser  ->get_all_sorted                                                     }
395 sub init_all_groups        { SL::DB::Manager::AuthGroup ->get_all_sorted                                                     }
396 sub init_all_printers      { SL::DB::Manager::Printer   ->get_all_sorted                                                     }
397 sub init_all_dateformats   { [ qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd)      ]                                              }
398 sub init_all_numberformats { [ qw(1,000.00 1000.00 1.000,00 1000,00)          ]                                              }
399 sub init_all_stylesheets   { [ qw(lx-office-erp.css Mobile.css kivitendo.css) ]                                              }
400 sub init_all_menustyles    {
401   return [
402     { id => 'old', title => $::locale->text('Old (on the side)') },
403     { id => 'v3',  title => $::locale->text('Top (CSS)') },
404     { id => 'neu', title => $::locale->text('Top (Javascript)') },
405   ];
406 }
407
408 sub init_all_rights {
409   my (@sections, $current_section);
410
411   foreach my $entry ($::auth->all_rights_full) {
412     if ($entry->[0] =~ m/^--/) {
413       push @sections, { description => $entry->[1], rights => [] };
414
415     } elsif (@sections) {
416       push @{ $sections[-1]->{rights} }, {
417         name        => $entry->[0],
418         description => $entry->[1],
419       };
420
421     } else {
422       die "Right without sections: " . join('::', @{ $entry });
423     }
424   }
425
426   return \@sections;
427 }
428
429 sub init_all_countrycodes {
430   my %cc = User->country_codes;
431   return [ map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc ];
432 }
433
434 #
435 # filters
436 #
437
438 sub setup_layout {
439   my ($self, $action) = @_;
440
441   $::request->layout(SL::Layout::Dispatcher->new(style => 'admin'));
442   $::request->layout->use_stylesheet("lx-office-erp.css");
443   $::form->{favicon} = "favicon.ico";
444 }
445
446 sub setup_client {
447   my ($self) = @_;
448
449   $self->client((first { $_->is_default } @{ $self->all_clients }) || $self->all_clients->[0]) if !$self->client;
450   $::auth->set_client($self->client->id);
451 }
452
453
454 #
455 # displaying forms
456 #
457
458 sub use_multiselect_js {
459   my ($self) = @_;
460
461   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
462   return $self;
463 }
464
465 sub login_form {
466   my ($self, %params) = @_;
467   $::request->layout->focus('#admin_password');
468   $self->render('admin/adminlogin', title => t8('kivitendo v#1 administration', $::form->read_version), %params);
469 }
470
471 sub edit_user_form {
472   my ($self, %params) = @_;
473   $self->use_multiselect_js->render('admin/edit_user', %params);
474 }
475
476 sub edit_client_form {
477   my ($self, %params) = @_;
478   $self->use_multiselect_js->render('admin/edit_client', %params);
479 }
480
481 sub edit_group_form {
482   my ($self, %params) = @_;
483   $self->use_multiselect_js->render('admin/edit_group', %params);
484 }
485
486 sub edit_printer_form {
487   my ($self, %params) = @_;
488   $self->render('admin/edit_printer', %params);
489 }
490
491 #
492 # helpers
493 #
494
495 sub check_auth_db_and_tables {
496   my ($self) = @_;
497
498   if (!$::auth->check_database) {
499     $self->render('admin/check_auth_database', title => t8('Authentification database creation'));
500     return 0;
501   }
502
503   if (!$::auth->check_tables) {
504     $self->render('admin/check_auth_tables', title => t8('Authentification tables creation'));
505     return 0;
506   }
507
508   return 1;
509 }
510
511 sub apply_dbupgrade_scripts {
512   return SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(1);
513 }
514
515 sub authenticate_root {
516   my ($self) = @_;
517
518   return 1 if $::auth->authenticate_root($::form->{'{AUTH}admin_password'}) == $::auth->OK();
519
520   $::auth->punish_wrong_login;
521   $::auth->delete_session_value('admin_password');
522
523   $self->login_form(error => t8('Incorrect password!'));
524
525   return undef;
526 }
527
528 1;