#!/usr/bin/perl use DBI; use CGI::Carp qw(fatalsToBrowser); print "Content-type:text/html\n\n"; $dbh = DBI->connect( "dbi:mysql:usertable", "usertable", "jutedi2") or &dienice("Can't connect to db: ",$dbh->errstr); read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); @pairs = split(/&/, $buffer); @keys = (); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; push(@keys, $name); $FORM{$name} = $value; } $username = $FORM{'username'}; $email = $FORM{'email'}; $sth = $dbh->prepare("select * from users where username = ?") or &dienice("Can't select from table: ",$dbh->errmsg); $sth->execute($username); $hashref = $sth->fetchrow_hashref; %uinfo = %{$hashref}; if (!(scalar %uinfo)) { &dienice("Username '$username' is not registered. Register today!"); } # even if the username is valid, we want to check and be sure the email # address matches. if ($uinfo{email} !~ /$email/i) { &dienice("The email address '$email' does not match what's stored in the user database."); } # ok, it's a valid user. First, we create a random password. This uses # the random password code from chapter 10. $randpass = &random_password(); # now we encrypt it: $encpass = &encrypt($randpass); # now store it in the database... $sth = $dbh->prepare("update users set password=? where username=?") or &dienice("Can't add data to user table: ",$dbh->errmsg); $sth->execute($encpass, $username); # ...and send email to the person telling them their new password. # be sure to send them the un-encrypted version! $mailprog = "/usr/sbin/sendmail"; open(MAIL,"|$mailprog -t"); print MAIL "To: $email\n"; print MAIL "From: webmaster\n"; print MAIL "Subject: Your FooWeb Password\n\n"; print MAIL <Password Reset

Success!

Your password has been changed! A new password has been e-mailed to you.

EndHTML sub encrypt { my($plain) = @_; my(@salt); @salt = ('a'..'z', 'A'..'Z', '0'..'9', '.', '/'); srand(time() ^ ($$ + ($$ << 15)) ); return crypt($plain, $salt[int(rand(@salt))] . $salt[int(rand(@salt))] ); } sub random_password { my($length, $vowels, $consonants, $alt, $s, $newchar, $i); ($length) = @_; if ($length eq "" or $length < 3) { $length = 6; # make it at least 6 chars long. } $vowels = "aeiouyAEUY"; $consonants = "bdghjmnpqrstvwxzBDGHJLMNPQRSTVWXZ12345678"; srand(time() ^ ($$ + ($$ << 15)) ); $alt = int(rand(2)) - 1; $s = ""; $newchar = ""; foreach $i (0..$length-1) { if ($alt == 1) { $newchar = substr($vowels,rand(length($vowels)),1); } else { $newchar = substr($consonants, rand(length($consonants)),1); } $s .= $newchar; $alt = !$alt; } return $s; } sub dienice { my($msg) = @_; print "

Error

\n"; print $msg; exit; }