Building Browsergames: forcing users to log in (Perl)

While we’ve been working on building our browsergame, one thing that we haven’t really touched on is making sure that our users are logged in before they try to do anything. Most of the pages that we’ve built rely on the user being logged in so that we can retrieve their User ID and use it for whatever the page does – but none of them force the user to be logged in yet. Today, we’re going to add that piece of functionality to our game.

We already know how to figure out whether or not a user is logged in – all we do is use the values from their cookie, and compare them against the database to see if they match – if they do, we retrieve a User ID. We’ll know a user is logged in when we retrieve something, and we’ll know that they aren’t when we don’t get anything back.

If this sounds familiar, that’s because it is – here’s the code from our index page that does just that:

 

my $query = new CGI;
my $cookie = $query->cookie('username+password');
 
my ($username) = split(/\+/,$cookie);
use DBI;
use config;
my $dbh = DBI->connect("DBI:mysql:$dbname:$dbhost",$dbuser,$dbpass,{RaiseError => 1});
my $sth = $dbh->prepare("SELECT id FROM users WHERE UPPER(username) = UPPER(?)");
$sth->execute($username);
my $userID;
$sth->bind_columns(\$userID);
$sth->fetch;

All we need to do is add a quick conditional check to our code to see what was returned, and modify our code slightly so that it’s re-usable in modular format:

 

package login;
 
use CGI qw(:cgi);
use DBI;
use config;
 
my $query = new CGI;
my $cookie = $query->cookie('username+password');
 
my ($username) = split(/\+/,$cookie);
my $dbh = DBI->connect("DBI:mysql:$dbname:$dbhost",$dbuser,$dbpass,{RaiseError => 1});
my $sth = $dbh->prepare("SELECT id FROM users WHERE UPPER(username) = UPPER(?)");
$sth->execute($username);
my $userID;
$sth->bind_columns(\$userID);
$sth->fetch;
if(!$userID) {
	print $query->redirect('login.cgi');	
}
 
1;

If you save that code as login.pm, you’ll now be able add this line to any file that you want to force users to log in to view:

 

require login;

And if a user attempts to access the page without their cookie set properly, they’ll be automated redirected to the login page. Check out The index page to see it in action.