# FILE: emergpw.pl
# DESCRIPTION: Emergency Password access
#-------------------------------------------------------------------------------
# DISCUS COPYRIGHT NOTICE
#
# Discus is copyright (c) 2002 by DiscusWare, LLC, all rights reserved.
# The use of Discus is governed by the Discus License Agreement which is
# available from the Discus WWW site at:
#    http://www.discusware.com/discus/license
#
# Pursuant to the Discus License Agreement, this copyright notice may not be
# removed or altered in any way.
#-------------------------------------------------------------------------------

use strict;
use vars qw($GLOBAL_OPTIONS $DCONF $PARAMS);

###
### make_emergency_password
###
### Generates a random "emergency" password and associated text file
###

sub make_emergency_password {
	my $FORMref = $_[0];
	if (! defined $FORMref->{encpw}) {
		dreq("fcn-acct", "authpass");
		my ($pass, $salt);
		while ($pass =~ /[0o]/i || $pass !~ /\d[a-z]+\d/i || $pass =~ /\d\d\d/i) {
			($pass, $salt) = pick_random_password();
		}
		my $subst = {};
		$subst->{general}->{plainpass} = $pass;
		$pass = prepare_userpass_p($pass);
		$subst->{general}->{password} = crypt($pass, $salt);
		screen_out("emerg", $subst);
	} else {
		header(undef, "text/plain", "emergency.txt");
		print "\r\n:::$FORMref->{encpw}:::\r\n";	
		program_exit(0);
	}	
}

###
### validate_emergency_password
###
### Checks to see if an emergency password is correct
###

sub validate_emergency_password {
	my ($password, $cookies, $args) = @_;
	my $file_mtime = (stat "$DCONF->{admin_dir}/data/emergency.txt")[9];
	if (time - $file_mtime > 3600) {
		unlink "$DCONF->{admin_dir}/data/emergency.txt";
		return "";
	}
	my @z = grep { /:::/ } @{readfile("$DCONF->{admin_dir}/data/emergency.txt","validate_emergency_password",{no_lock=>1,no_unlock=>1,zero_ok=>1})};
	return "" if ! scalar @z;
	return "" if $z[0] !~ /:::(.*?):::/;
	my $pwcrypt = $1;
	if (defined $password) {
		dreq("authpass");
		return $pwcrypt if crypt($password, $pwcrypt) eq $pwcrypt;
		return "" if $password ne "" && $password ne "adminlogin";		
	}
	if (defined $cookies->{pass}) {
		return $pwcrypt if $cookies->{pass} eq crypt($pwcrypt, "cookie")
	}
	return "";	
}

1;
