source: main/trunk/greenstone2/perllib/cgiactions/baseaction.pm@ 27349

Last change on this file since 27349 was 27349, checked in by ak19, 11 years ago
  1. Updated timestamp for a key that has been reused should not have a newline at its end. 2. Changed baseaction::authenticate_user() to go through dbutil to read users.gdb and key.gdb rather than directly using db2txt, since it makes the code easier to understand.
File size: 17.6 KB
Line 
1###########################################################################
2#
3# baseaction.pm --
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 2009 New Zealand Digital Library Project
9#
10# This program is free software; you can redistr te it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26
27package baseaction;
28
29use strict;
30use util;
31use inexport;
32
33# for time conversion and formatting functions
34use Time::Local;
35use POSIX;
36
37our $authentication_enabled = 1; # debugging flag (can debug without authentication when set to 0)
38our $mail_enabled = 0;
39
40
41# change this to get these values from a config file
42my $mail_to_address = "user\@server"; # Set this appropriately
43my $mail_from_address = "user\@server"; # Set this appropriately
44my $mail_smtp_server = "smtp.server"; # Set this appropriately
45
46
47
48# Required CGI arguments: "a" for action
49# "c" for collection
50# Optional CGI arguemnts: "ts" for timestamp (auto generated is missing)
51# "site" (used by Greenstone3)
52
53# allow "un" for username to be optional for now
54
55sub new
56{
57 my $class = shift (@_);
58 my ($action_table,$gsdl_cgi,$iis6_mode) = @_;
59
60 my $self = { 'gsdl_cgi' => $gsdl_cgi,
61 'iis6_mode' => $iis6_mode,
62 'gsdlhome' => $ENV{'GSDLHOME'} };
63
64 # Retrieve the (required) command CGI argument
65 my $action = $gsdl_cgi->clean_param("a");
66
67 if (!defined $action) {
68 my $err_mess = "No action (a=...) specified.\n";
69 $err_mess .= "\nPossible actions are:\n";
70
71 $err_mess .= " check-installation\n\n";
72
73 foreach my $a (sort keys %$action_table) {
74 $err_mess .= " $a:\n";
75 $err_mess .= " Compulsory args: ";
76 my @comp_args = ("c");
77 push(@comp_args,"un") if ($authentication_enabled);
78 push(@comp_args,@{$action_table->{$a}->{'compulsory-args'}});
79 $err_mess .= join(", ", @comp_args);
80
81 $err_mess .= "\n";
82
83 my @opt_args = ();
84 push(@opt_args,"un") if (!$authentication_enabled);
85 push(@opt_args,@{$action_table->{$a}->{'optional-args'}});
86
87 if (scalar(@opt_args)>0) {
88
89 $err_mess .= " Optional args : ";
90 $err_mess .= join(", ", @opt_args);
91 $err_mess .= "\n";
92 }
93
94 my @help_examples = ();
95 if(defined $action_table->{$a}->{'help-string'}) {
96 push(@help_examples, @{$action_table->{$a}->{'help-string'}});
97 }
98 if (scalar(@help_examples)>0) {
99
100 if (scalar(@help_examples)>1) {
101 $err_mess .= " Example(s) :\n";
102 } else {
103 $err_mess .= " Example :\n";
104 }
105 $err_mess .= join(", \n\n", @help_examples);
106 $err_mess .= "\n\nTo be strictly CGI-compliant special chars like double-quotes,&,?,<,> must be URL encoded.\n";
107 }
108
109 $err_mess .= "\n";
110 }
111
112 $gsdl_cgi->generate_message($err_mess);
113 exit(-1);
114
115 }
116 $gsdl_cgi->delete("a");
117
118 $self = bless $self, $class;
119
120 # The check-installation command has no arguments
121 if ($action eq "check-installation") {
122 $self->check_installation($gsdl_cgi,$iis6_mode);
123 exit 0;
124 }
125
126
127 if (!defined $action_table->{$action}) {
128 my $valid_actions = join(", ", keys %$action_table);
129
130 my $err_mess = "Unrecognised action (a=$action) specified.\n";
131 $err_mess .= "Valid actions are: $valid_actions\n";
132
133 $gsdl_cgi->generate_error($err_mess);
134 }
135
136
137 my $collect = $gsdl_cgi->clean_param("c");
138 if ((!defined $collect) || ($collect =~ m/^\s*$/)) {
139 $gsdl_cgi->generate_error("No collection specified.");
140 }
141 $gsdl_cgi->delete("c");
142
143 # allow un to be optional for now
144 my $username = $gsdl_cgi->clean_param("un");
145
146
147 # Get then remove the ts (timestamp) argument (since this can mess up
148 # other scripts)
149 my $timestamp = $gsdl_cgi->clean_param("ts");
150 if ((!defined $timestamp) || ($timestamp =~ m/^\s*$/)) {
151 # Fall back to using the Perl time() function to generate a timestamp
152 $timestamp = time();
153 }
154 $gsdl_cgi->delete("ts");
155
156 my $site = undef;
157 if($gsdl_cgi->greenstone_version() != 2) {
158 # all GS versions after 2 may define site
159 $site = $gsdl_cgi->clean_param("site");
160 if (!defined $site) {
161 $gsdl_cgi->generate_error("No site specified.");
162 }
163 $gsdl_cgi->delete("site");
164 }
165
166
167 $self->{'action'} = $action;
168 $self->{'collect'} = $collect;
169 $self->{'username'} = $username;
170 $self->{'timestamp'} = $timestamp;
171 $self->{'site'} = $site;
172
173 # Locate and store compulsory arguments
174 my $comp_args = $action_table->{$action}->{'compulsory-args'};
175 foreach my $ca (@$comp_args) {
176 if (!defined $gsdl_cgi->param($ca)) {
177 $gsdl_cgi->generate_error("Compulsory argument '$ca' missing");
178 }
179 else {
180 $self->{$ca} = $gsdl_cgi->clean_param($ca);
181 $gsdl_cgi->delete($ca);
182 }
183 }
184
185 # Locate and store optional args if present
186 my $opt_args = $action_table->{$action}->{'optional-args'};
187 foreach my $oa (@$opt_args) {
188 if (defined $gsdl_cgi->param($oa)) {
189 $self->{$oa} = $gsdl_cgi->clean_param($oa);
190 $gsdl_cgi->delete($oa);
191 }
192 }
193
194
195
196 # Retrieve infodb-type
197 if (defined $collect) {
198
199 my $opt_site = $self->{'site'} || "";
200
201 my $inexport = newCGI inexport(ref $self,$collect,$gsdl_cgi,$opt_site);
202 my ($config_filename,$collect_cfg) = $inexport->read_collection_cfg($collect);
203 $self->{'infodbtype'} = $collect_cfg->{'infodbtype'};
204
205 }
206
207
208 return $self;
209}
210
211
212sub do_action
213{
214 my $self = shift @_;
215 my $action = $self->{'action'};
216
217 $action =~ s/-/_/g;
218
219
220 $self->$action();
221
222}
223
224
225sub authenticate_user
226{
227 my $self = shift @_;
228 my $username = shift(@_);
229 my $collection = shift(@_);
230
231 my $keydecay = 1800; # 30 mins same as in runtime-src/recpt/authentication.cpp
232
233 my $gsdl_cgi = $self->{'gsdl_cgi'};
234
235 # Remove the pw argument (since this can mess up other scripts)
236 my $user_password = $gsdl_cgi->clean_param("pw");
237 my $user_key = $gsdl_cgi->clean_param("ky");
238
239 $gsdl_cgi->delete("pw");
240 $gsdl_cgi->delete("ky");
241
242 if ((!defined $user_password || $user_password =~ m/^\s*$/) && (!defined $user_key || $user_key =~ m/^\s*$/)) {
243 $gsdl_cgi->generate_error("Authentication failed: no password or key specified.");
244 }
245
246 my $gsdlhome = $ENV{'GSDLHOME'};
247 my $etc_directory = &util::filename_cat($gsdlhome, "etc");
248 my $users_db_file_path = &util::filename_cat($etc_directory, "users.gdb");
249
250 # Use dbutil to get the user accounts information
251 # infodbtype can be different for different collections, but the userDB and keyDB are gdbm
252
253 my $user_rec = &dbutil::read_infodb_entry("gdbm", $users_db_file_path, $username);
254 # Check username
255 if (!defined $user_rec) {
256 $gsdl_cgi->generate_error("Authentication failed: no account for user '$username'.");
257 }
258
259 # Check password
260 if(defined $user_password) {
261 my $valid_user_password = $user_rec->{"password"}->[0];
262 if ($user_password ne $valid_user_password) {
263 $gsdl_cgi->generate_error("Authentication failed: incorrect password.");
264 }
265 }
266 else { # check $user_key #if(!defined $user_password && defined $user_key) {
267
268 # check to see if there is a key for this particular user in the database that hasn't decayed.
269 # if the key validates, refresh the key again by setting its timestamp to the present time.
270
271 # Use dbutil to get the key accounts information
272 my $key_db_file_path = &util::filename_cat($etc_directory, "key.gdb");
273 my $key_rec = &dbutil::read_infodb_entry("gdbm", $key_db_file_path, $user_key);
274
275 if (!defined $key_rec) {
276
277 #$gsdl_cgi->generate_error("Authentication failed: invalid key $user_key. Does not exist.");
278 $gsdl_cgi->generate_error("Authentication failed: invalid key. No entry for the given key.");
279 }
280 else {
281 my $valid_username = $key_rec->{"user"}->[0];
282 if ($username ne $valid_username) {
283 $gsdl_cgi->generate_error("Authentication failed: key does not belong to user.");
284 }
285
286 # http://stackoverflow.com/questions/12644322/how-to-write-the-current-timestamp-in-a-file-perl
287 # http://stackoverflow.com/questions/2149532/how-can-i-format-a-timestamp-in-perl
288 # http://stackoverflow.com/questions/7726514/how-to-convert-text-date-to-timestamp
289
290 my $current_timestamp = time; #localtime(time);
291
292 my $keycreation_time = $key_rec->{"time"}->[0]; # of the form: 2013/05/06 14:39:23
293 if ($keycreation_time !~ m/^\s*$/) { # not empty
294
295 my ($year,$mon,$mday,$hour,$min,$sec) = split(/[\s\/:]+/, $keycreation_time); # split by space, /, :
296 my $key_timestamp = timelocal($sec,$min,$hour,$mday,$mon-1,$year);
297
298 if(($current_timestamp - $key_timestamp) > $keydecay) {
299 $gsdl_cgi->generate_error("Authentication failed: key has expired.");
300 } else {
301 # succeeded, update the key's time in the database
302
303 # beware http://community.activestate.com/forum/posixstrftime-problem-e-numeric-day-month
304 my $current_time = strftime("%Y/%m/%d %H:%M:%S", localtime($current_timestamp)); # POSIX
305
306 # infodbtype can be different for different collections, but the key DB is gdbm
307 my $key_rec = &dbutil::read_infodb_entry("gdbm", $key_db_file_path, $user_key);
308 $key_rec->{"time"}->[0] = $current_time;
309 my $status = &dbutil::set_infodb_entry("gdbm", $key_db_file_path, $user_key, $key_rec);
310
311 if ($status != 0) {
312 $gsdl_cgi->generate_error("Error updating authentication key.");
313 }
314 }
315 } else {
316 $gsdl_cgi->generate_error("Authentication failed: Invalid key entry. No time stored for key.");
317 }
318 }
319 }
320
321 # The following code which tests whether the user is in the required group
322 # seems to have been copied over from gliserver.pl.
323 # But for metadata-server.pl, when user comments are added through the set-metadata functions,
324 # the user doesn't need to be a specific collection's editor in order to add comments to that collection.
325 # So we no longer check the user is in the group here.
326# $self->check_group($collection, $username, $user_data);
327}
328
329
330sub check_group
331{
332 my $self = shift @_;
333 my $collection = shift @_;
334 my $username = shift @_;
335 my $user_data = shift @_;
336
337
338 my $gsdl_cgi = $self->{'gsdl_cgi'};
339
340 # Check group
341 my ($user_groups) = ($user_data =~ /\<groups\>(.*)/);
342 if ($collection eq "") {
343 # If we're not editing a collection then the user doesn't need to be in a particular group
344 return $user_groups; # Authentication successful
345 }
346 foreach my $user_group (split(/\,/, $user_groups)) {
347 # Does this user have access to all collections?
348 if ($user_group eq "all-collections-editor") {
349 return $user_groups; # Authentication successful
350 }
351 # Does this user have access to personal collections, and is this one?
352 if ($user_group eq "personal-collections-editor" && $collection =~ /^$username\-/) {
353 return $user_groups; # Authentication successful
354 }
355 # Does this user have access to this collection
356 if ($user_group eq "$collection-collection-editor") {
357 return $user_groups; # Authentication successful
358 }
359 }
360
361 $gsdl_cgi->generate_error("Authentication failed: user is not in the required group.");
362}
363
364sub check_installation
365{
366 my $self = shift @_;
367 my $iis6_mode = shift(@_);
368
369 my $gsdl_cgi = $self->{'gsdl_cgi'};
370
371 my $installation_ok = 1;
372 my $installation_status = "";
373
374 print STDOUT "Content-type:text/plain\n\n";
375
376 # Check that Java is installed and accessible
377 my $java = $gsdl_cgi->get_java_path();
378 my $java_command = "$java -version 2>&1";
379
380 # IIS 6: redirecting output from STDERR to STDOUT just doesn't work, so we have to let it go
381 # directly out to the page
382 if ($iis6_mode)
383 {
384 $java_command = "java -version";
385 }
386
387 my $java_output = `$java_command`;
388 my $java_status = $?;
389 if ($java_status < 0) {
390 # The Java command failed
391 $installation_status = "Java failed -- do you have the Java run-time installed?\n" . $gsdl_cgi->check_java_home() . "\n";
392 $installation_ok = 0;
393 }
394 else {
395 $installation_status = "Java found: $java_output";
396 }
397
398 # Show the values of some important environment variables
399 $installation_status .= "\n";
400 $installation_status .= "GSDLHOME: " . $ENV{'GSDLHOME'} . "\n";
401 $installation_status .= "GSDLOS: " . $ENV{'GSDLOS'} . "\n";
402 $installation_status .= "PATH: " . $ENV{'PATH'} . "\n";
403
404 if ($installation_ok) {
405 print STDOUT $installation_status . "\nInstallation OK!";
406 }
407 else {
408 print STDOUT $installation_status;
409 }
410}
411
412sub lock_collection
413{
414 my $self = shift @_;
415 my $username = shift(@_);
416 my $collection = shift(@_);
417
418 my $gsdl_cgi = $self->{'gsdl_cgi'};
419
420 my $steal_lock = $gsdl_cgi->clean_param("steal_lock");
421 $gsdl_cgi->delete("steal_lock");
422
423 if (!defined $username) {
424 # don't have any user details for current user to compare with
425 # even if there is a lock file
426 # For now, allow the current user access. Might want to
427 # revisit this in the future.
428 return;
429 }
430
431 #my $gsdlhome = $ENV{'GSDLHOME'};
432 #my $collection_directory = &util::filename_cat($gsdlhome, "collect", $collection);
433 my $site = $self->{'site'};
434 my $collection_directory = $gsdl_cgi->get_collection_dir($site, $collection);
435 $gsdl_cgi->checked_chdir($collection_directory);
436
437 # Check if a lock file already exists for this collection
438 my $lock_file_name = "gli.lck";
439 if (-e $lock_file_name) {
440 # A lock file already exists... check if it's ours
441 my $lock_file_content = "";
442 open(LOCK_FILE, "<$lock_file_name");
443 while (<LOCK_FILE>) {
444 $lock_file_content .= $_;
445 }
446 close(LOCK_FILE);
447
448 # Pick out the owner of the lock file
449 $lock_file_content =~ /\<User\>(.*?)\<\/User\>/;
450 my $lock_file_owner = $1;
451
452 # The lock file is ours, so there is no problem
453 if ($lock_file_owner eq $username) {
454 return;
455 }
456
457 # The lock file is not ours, so throw an error unless "steal_lock" is set
458 unless (defined $steal_lock) {
459 $gsdl_cgi->generate_error("Collection is locked by: $lock_file_owner");
460 }
461 }
462
463 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
464 my $current_time = sprintf("%02d/%02d/%d %02d:%02d:%02d", $mday, $mon + 1, $year + 1900, $hour, $min, $sec);
465
466 # Create a lock file for us (in the same format as the GLI) and we're done
467 open(LOCK_FILE, ">$lock_file_name");
468 print LOCK_FILE "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
469 print LOCK_FILE "<LockFile>\n";
470 print LOCK_FILE " <User>" . $username . "</User>\n";
471 print LOCK_FILE " <Machine>(Remote)</Machine>\n";
472 print LOCK_FILE " <Date>" . $current_time . "</Date>\n";
473 print LOCK_FILE "</LockFile>\n";
474 close(LOCK_FILE);
475}
476
477
478# Release the gli.lck otherwise no one else will be able to use the collection again.
479sub unlock_collection
480{
481 my $self = shift @_;
482 my ($username, $collection) = @_;
483 my $gsdl_cgi = $self->{'gsdl_cgi'};
484
485 # Obtain the path to the collection GLI lock file
486 my $lock_file_path = &util::filename_cat($ENV{'GSDLHOME'}, "collect", $collection, "gli.lck");
487
488 # If the lock file does exist, check if it is ours
489 if (-e $lock_file_path)
490 {
491 my $lock_file_content = "";
492 open(LOCK_FILE, "<$lock_file_path");
493 while (<LOCK_FILE>) {
494 $lock_file_content .= $_;
495 }
496 close(LOCK_FILE);
497
498 # Pick out the owner of the lock file
499 $lock_file_content =~ /\<User\>(.*?)\<\/User\>/;
500 my $lock_file_owner = $1;
501
502 # If we are the owner of this lock, we have the right to delete it
503 if ($lock_file_owner eq $username) {
504 unlink($lock_file_path );
505 }
506 else {
507 $gsdl_cgi->generate_error("Collection is locked by: $lock_file_owner. Cannot be unlocked");
508 }
509 }
510}
511
512
513sub send_mail
514{
515 my $self = shift @_;
516
517 my ($mail_subject,$mail_content) = @_;
518
519 my $gsdl_cgi = $self->{'gsdl_cgi'};
520
521 my $sendmail_command = "\"".&util::get_perl_exec()."\" -S sendmail.pl";
522 $sendmail_command .= " -to \"" . $mail_to_address . "\"";
523 $sendmail_command .= " -from \"" . $mail_from_address . "\"";
524 $sendmail_command .= " -smtp \"" . $mail_smtp_server . "\"";
525 $sendmail_command .= " -subject \"" . $mail_subject . "\"";
526
527 if (!open(POUT, "| $sendmail_command")) {
528 $gsdl_cgi->generate_error("Unable to execute command: $sendmail_command");
529 }
530 print POUT $mail_content . "\n";
531 close(POUT);
532}
533
534
535sub run_script
536{
537 my $self = shift @_;
538
539 my ($collect, $site, $script) = @_;
540
541 my $gsdl_cgi = $self->{'gsdl_cgi'};
542
543 my $perl_args = $collect;
544
545 my $collect_dir = $gsdl_cgi->get_collection_dir($site);
546 $perl_args = "-collectdir \"$collect_dir\" " . $perl_args;
547
548 my $perl_command = "\"".&util::get_perl_exec()."\" -S $script $perl_args";
549
550
551 # IIS 6: redirecting output from STDERR to STDOUT just doesn't work, so
552 # we have to let it go directly out to the page
553
554 if (!$self->{'iis6_mode'})
555 {
556 $perl_command .= " 2>&1";
557 }
558
559 if (!open(PIN, "$perl_command |")) {
560 $gsdl_cgi->generate_error("Unable to execute command: $perl_command");
561 }
562
563 print STDOUT "Content-type:text/plain\n\n";
564 print "$perl_command \n";
565
566 while (defined (my $perl_output_line = <PIN>)) {
567 print STDOUT $perl_output_line;
568 }
569 close(PIN);
570
571 my $perl_status = $?;
572 if ($perl_status > 0) {
573 $gsdl_cgi->generate_error("Perl failed: $perl_command\n--\nExit status: " . ($perl_status / 256));
574 }
575}
576
5771;
Note: See TracBrowser for help on using the repository browser.