[SmartFox] Custom login
[ April 14, 2005 ] by Marco Lapi, a.k.a Lapo
Article 14: how to implement a custom login system that can be integrated seamlessly with SmartFoxServer BASIC


[ Introduction ]

In this tutorial we will learn how to implement a custom login system that can be integrated seamlessly with SmartFoxServer BASIC.
While the PRO edition is designed to directly connect to many database engines, with the BASIC edition you can use any server side language to create a custom login system for your multiplayer applications.

This article provides a simple login example based on the PHP language, but you could easily translate it to ASP/ASP.Net, JSP, Coldfusion etc...

[ Requirements ]

To complete this tutorial you should already be familiar with the "Simple Chat" example and you should have some basic knowledge of server-side Flash integration.

[ Objectives ]

The tutorial is based on the previous "Simple Chat" application to which we have added a PHP-based login system. The purpose of this example is to show you how easily a login system can be created using your existent server side technology and integrating it with the multiplayer side handled by SmartFoxServer. Also we'll have a look at how you can use moderator priviliges in your applications.

[ The server side ]

In all the previous examples we have implemented the most simple login system where the application accepts any user name that is not already in use in the current zone. However applications like chats and games usually require users to input a valid name and password.
Adding this feature to your SmartFoxServer Basic applications is very easy: you first send user data to your server side page for validation and then log the user in the multiplayer server.

Before commenting the actionscript code we can have a look at the PHP example page that will handle the login requests:

<?php
    // A Simple List of allowed users
    // You could substitute this code with a database connection
    $allowedUsers =  array ("test" => "test",
                            "smartfox" => "smartfox",
                            "flash" => "flash");
    
    // The response variable
    $res = "res=KO";

    
// Check incoming data     if ($_POST['name'] != "" && $_POST['pass'] != "")     {         foreach($allowedUsers as $name => $password)         {             if ($_POST['name'] == $name && $_POST['pass'] == $password)             {                 // Ok, user found                 $res = "res=OK";                 break;             }         }     }          print $res; ?>

To keep the server side code as simple as possible we didn't use a database to keep user data since it's not the purpose of this tutorial to teach server side database integration.
Once you have learned how to use this code you will be free to add your own implementation using your favourite data source be it a text file, XML or a relational database engine. For our simple example we have used an associative array where the key is the username and the associated value represents the password.
The variable called $res will output the response and we initially set it to "res=KO" where "res" is the variable name returned to Flash.

When a login request is sent we cycle through the $allowedUsers array checking if the name and password match, and if they do the loop is stopped and the $res variable is set to "res=OK". This will tell Flash that the login was successfull.

You can copy the above code, paste it in your favourite editor and save it with the name "sfsLogin.php" on a local or online webserver.

[ The server side ]

Now you can open the source file for this example and inspect the code located at the frame labeled "connect". The main difference with the original "Simple Chat" example is mainly in these three new variables:

var serverPage:String = "http://localhost/sfsLogin.php"
var serverIn:LoadVars = new LoadVars()
var serverOut:LoadVars = new LoadVars()
            

The serverPage var is the url where your PHP page is located, you can change it freely and point it to the webserver where the PHP page was saved. The next two variables are the LoadVars objects we will use to send and receive data from the server. As we said before the login data is going to be sent to the PHP page before we log the user in SmartFoxServer. The following code is executed as soon as the user presses the "LOG IN" button:

//----------------------------------------------------------
// Send login data to the server page
//----------------------------------------------------------
function validateLogin()
{
        if (login_txt.text.length > 0 && pwd_txt.text.length > 0)
        {
                serverOut.name = login_txt.text
                serverOut.pass = pwd_txt.text
                serverOut.sendAndLoad(serverPage, serverIn, "post")
        }
}
            

After we have checked that both textfields contain data the "name" and "pass" variables are created and sent as an http POST request to the PHP page. The server response will be handled by the "serverIn" object in its onLoad method:

//----------------------------------------------------------
// Handle the PHP server login response
//----------------------------------------------------------
serverIn.onLoad = function(success)
{
        if (success)
        {
                if (this.res == "OK")
                {
                        sendLogin()
                }
                else
                {
                        var win:MovieClip = showWindow("errorWindow")
                        win.errorMsg.text = "Wrong name or passord"
                }
        }
        else
        {
                var win:MovieClip = showWindow("errorWindow")
                win.errorMsg.text = "Connection failed"
        }
}
            

This event handler receives a boolean parameter that tells us if the connection to the server page was successfull. If so we can go ahead by checking the "res" variable we were expecting and see if it's equal to "OK". When the PHP page returns a positive response we can continue by logging the client to the multiplayer server and start the application, otherwise we'll show an error message.

The code for login is this:

function sendLogin()
{
        if (!_global.isBusy)
        	smartfox.login(zone, login_txt.text, pwd_txt.text)
}
            

[ Moderators ]

When you send a login and password to SmartFoxServer they are checked against a moderator list that is fully customizable in the config.xml file.

<Moderators status="on"> 
	<Mod name="test" pwd="test" />
	<Mod name="mod" pwd="mod" />
</Moderators>

You can define as many moderators as you want by adding this xml block in each zone of the config file. If one user logs in using a moderator account he will have special powers for kicking and banning users. To check if the current user has moderator privileges you can call the smartFox.isModerator() method:

if (smartFox.isModerator())
{
        trace("Welcome, moderator")
}
            

[ The Admin Extension ]

The administrator commands for kicking and banning are available as an Extension for SmartFoxServer. Extensions are special modules written in either Java or Actionscript and executed on the server side. They allow to add new features to the server pretty easily. Even if it's not the purpose of this article to give an in-depth look at SmartFoxServer Extensions we are going to learn how invoke commands on the Administrator Extension.

In general a server side Extension can be called from the Client API with this method:

smartFox.sendXtMessage("$dmn", action, dataObj)
            

The sendXtMessage will send a request to a certain Extension loaded by SmartFoxServer. The first parameter is the unique name of the Extension, so in this case the string "$dmn" represents the name of the Administrator Extension.

The second parameter is the name of the action we want to execute and third argument is an object containing the parameters needed for that action.

Let's see an example:

var dataObj:Object = {}

dataObj.id = userId.toString()
dataObj.msg = msg

smartFox.sendXtMessage("$dmn", "kick", dataObj)
            

In the above code a "kick" request is sent.
In order to kick a user we must provide two string parameters: the id of the user (called "id") and a text message (called "msg").
The message will be sent as an Administrator Message and the user will be kicked after a few seconds.

NOTE: An important thing to notice is that all parameter in the dataObj need to be strings: that's why we have added a .toString() to the userId variable.

In order to ban a user from the current application we use a very similar request:

var dataObj:Object = {}

dataObj.id = userId.toString()
dataObj.msg = msg
dataObj.mode = "0"

smartFox.sendXtMessage("$dmn", "kick", dataObj)
            

The mode parameter can be either "0" or "1" and it represents the ban-mode the server will use:

0 » ban the user by name
1 » ban the user by its IP address

The client that is going to be disconnected will receive an onAdminMessage event which could be handled by showing a dialogue box on screen:

//----------------------------------------------------------
// Handles an Administrator / Moderator Message
//----------------------------------------------------------
smartFox.onAdminMessage = function(msg)
{
        var mc = showWindow("win_adminMessage")
        mc.message_txt.text = msg
}
            

NOTE: It is important that every application that you develop handles the onAdminMessage. These messages are sent not only by the moderators but also by the server Administrator through the Admin Tool.

[ Conclusions ]

In this article you have learned how to integrate a login system with your current server technology, handle moderators and use the Administrator Extension to kick/ban users. By mixing these new features with the other things learned so far you will be able to create pretty advanced Flash applications and games with multiplayer interaction.


    
 
 
Name: Marco Lapi, a.k.a Lapo
Location: Fossano, Italy
Age: 34
Flash experience: started out with Flash 4 back in 1999
Job: web designer/developer
Website: http://www.gotoandplay.it/
 
 
| Homepage | News | Games | Articles | Multiplayer Central | Reviews | Spotlight | Forums | Info | Links | Contact us | Advertise | Credits |

| www.smartfoxserver.com | www.gotoandplay.biz | www.openspace-engine.com |

gotoAndPlay() v 3.0.0 -- (c)2003-2008 gotoAndPlay() Team -- P.IVA 03121770048