Im attempting a very simple login screen, It's all written and works, It just doesn't remember that they are logged in. I have a login form that on submit reloads the page and loads a subroutine to check if the username/password are correct.
Right, there are a couple of number of ways to handle the details,
but it boils down to this: you have to remember somewhere not only
that the user is logged in, but _who_ they're logged in as. If you
put this information in a cookie, and then _trust_ the cookie, anyone
will be able to fake being logged in as any user, just by creating
a fake cookie (which is easy to do with most browsers), so you
don't want to do it that way. You could cryptographically sign
the cookie, but that starts to get complicated, and you'd have to
verify the signature on every page load. You could put the password
into the cookie, but then the password gets passed, in cleartext,
with each and every page load, which is not ideal. So the best
solution is to store the session information on the _server_
someplace, and just put a unique session-ID number in the cookie
that can be used to look up the session information (such as which
user is logged in).
I usually store the session info in a database, but if you aren't
prepared to set up a database you could store it in flat files
easily enough, and use the session-ID number as the filename.
Then to verify that the user is logged in, you take the session
ID number from the cookie that the browser sends you, and you
open that file and read the session information (such as the
logged-in username) out of it.
To create the cookie, you can just do something like this:
# Create a random session ID number:
my $sessionid = join "", map { int rand 100 } 1..20;
# Send the session id to the browser:
print "Content-type: text/html\nSet-Cookie: session=$sessionid\n\n"
+;
# And remember on the server which session that is:
storesessioninfo($sessionid, $username, %other_session_info);
However, any script that wants to "remember" later whether the user
is logged in or not will need to check the cookie:
if ($ENV{HTTP_COOKIE} =~ /sessionid=(\w+)/) {
# Call the routine that reads the server-side session info:
($username, %other_session_info) = getsessioninfo($1);
}
Once you get it working, you can decide how long you want to
keep the things before expiring them, and create a cron job
to clean up the old leftover ones.
The storesessioninfo and getsessioninfo routines just need to
store and retrieve (respectively) the session information,
either in the filesystem, or a database, or in some other way.
Sanity? Oh, yeah, I've got all kinds of sanity. In fact, I've developed whole new kinds of sanity. Why, I've got so much sanity it's driving me crazy.
|