SmartFoxServer 2x Custom User Registration and Login

Posted by & filed under Action Script 3, ADOBE FLEX, Flash, MYSQL, SmartFox Server.

In multi player gaming development there is requirement like custom user registration and custom user login which is some what tricky in smartfoxserver 2x or smartfoxserver pro.

SmartFoxServer 2x Custom User Registration and Login Tutorial

SmartFoxServer 2x Custom User Registration and Login Tutorial

 

Download

Download


In smartfoxserver 2x for  custom user registration and login, we need two zones for registration and login. One zone for user registration and another one for login.

Note: In smartfoxserver 2x or smartfoxserver pro if want to communicate with server we must logged in smartfoxserver. Only after successful login with server, user can send request as well get response from the server.

Step 1: We need create two zones (BasicExamples, muni) in smartfoxserver 2x using SmartFoxServer 2x admin tool.

custom user registration and login smartfoxserver 2x

Step 2: BasicExamples zone’s custom login property set to false, which is used for user registration purpose.

custom user registration and login smartfoxserver 2x

Step 3: muni zone’s custom login property set to true, which is used for custom user login purpose.

custom user registration and login smartfoxserver 2x ..

refer following URL for detailed zone configuration settings tutorial…….

Sample registration user interface  with three textInput control with instance name of username, password and email respectively.

custom user registration and login smartfoxserver 2x

once you finished user interface design, name their instance name using property panel.

Client side action script 3 coding :

connect to smartfoxserver 2x from Flash professional 5.5 :

Note: before going to do Actionscript 3 coding in your Flash professional, please add smartfoxserver actionscript 3 client API (SFS2X_API_AS3).  File -> ActionScript settings -> library path and browse SFS2X_API_AS3.swc file from the smartfoxserver client directory (C:\Program Files\SmartFoxServer2X\Client\ActionScript3).

add smartfoxserver actionscript 3 client api to flash professional
import com.smartfoxserver.v2.SmartFox;
import com.smartfoxserver.v2.core.SFSEvent;

var sfs:SmartFox= new SmartFox();

sfs.connect("127.0.0.1",9339);

sfs.addEventListener(SFSEvent.CONNECTION, onConnection);

function onConnection(event:SFSEvent)
{
	trace("connection success");
}

Initialize smartfoxserver main class SmartFox with name sfs and send connection request to the server using connect() method. If connection with server is success SFSEvent.CONNECTION event will occur that calls onConnection method, it print connection success message to output window.

Once connection is success with server, we need to login with smartfoxserver for user registration.

Logging in for user registration :

Declare task variable which keeps the name of the process. During user registration it has “register” string, while login it has “login” string.

var task=””;

Declare two variables zone1 and zone2, which both keeps the zone names.

var zone1=’BasicExamples’;
var zone2=’muni’;

Here sample code for user registration in client side :

When user clicks registration button it will call onBtConnectClick method, where we assign task variable with “register” string as well getting user name, password and email of the user. Once assignment is over, it calls loginHandler(task) method. During user registration process in  loginHandler() function  we will send login request to SmartfoxSever with no user name and password.

Note : when we send login request to the server with no user name and password, server will log you as a Guest user like Guest1, Guest2, Guest3 and etc………

register.addEventListener(MouseEvent.CLICK, onBtConnectClick);

private function onBtConnectClick(evt:Event):void
			{
			           task='register';
				    user_name1=user_name.text;
				    user_password=password.text;
				    user_email=email.text;
					loginHandler(task);

			}

private function loginHandler(task)
			{
				if(task=='register')
				{
					trace('register');
				    sfs1.send(new LoginRequest("", "", 'BasicExamples'));
				}
				else if(task=='login')
				{
					trace('login');
					sfs1.send(new LoginRequest(user_name1, user_password, zone2));
				}
			}

private function onLogin(evt:SFSEvent):void
			 {

				 if(task=="register")
				 {
					  var params:ISFSObject = new SFSObject();
					  params.putUtfString('userName',user_name1);
                      params.putUtfString("password", user_password);
                      params.putUtfString("email", user_email);
                      sfs1.send(new ExtensionRequest("register", params));
				 }
				 else if(task=="login")
				 {
					  trace("Login successful!");
				 }
			 }

 

Here sample code for user login in client side :

When user clicks login button it will call userLogin() method, where we assign task variable with “login” string as well getting user name, password of the user. Once assignment is over, it calls loginHandler(task) method. During user login process in  loginHandler() function  we will send login request to SmartfoxSever with user name and password.

login.addEventListener(MouseEvent.CLICK,userLogin);

private function userLogin(event:MouseEvent):void
		{
			userName=user_name.text;
			userPass=password.text;
			task="login";
			loginHandler(task);

		}

private function loginHandler(task):void
		{
			if(task=='register')
			{
				sfs.send(new LoginRequest("","","BasicExamples"));
			}
			else if(task=='login')
			{
				trace("login request----------------------");
				trace(userName);
				trace(userPass);
				sfs.send(new LoginRequest(userName,userPass,"muni"));
			}
		}

private function onLogin(event:SFSEvent):void

		{
			if(task=='register')
			{
			trace("login success");
			var param:SFSObject= new SFSObject();
			param.putUtfString("name",userName);
			param.putUtfString("password",userPass);
			param.putUtfString("email",userEmail);
			sfs.send(new ExtensionRequest("register",param));
			}
			else if(task=='login')
			{
				trace('user logged in successfully');
			}

		}

Connect external MySQL database from SmartfoxServer 2X :

To connect SmartFoxSever with external database download MySQL JDBC connector from MySQL site. Now find mysql-connector-java-5.1.22-bin.jar from the downlaoded file and that jar to your SmartfoxServer library folder  (C:\Program Files\SmartFoxServer2X\SFS2X\lib).

Now  SmartfoxServer 2x admin tool, and launch zone configurator select the zone you want configure. Finally click on Database manager to enter JDBC driver details and database you created on the localhost of your system.

Database driver class : org.gjt.mm.mysql.Driver
connection string : jdbc:mysql://127.0.0.1:3306/wkm
Username : wkm
Password : wkm
Test SQL : SELECT * FROM login

connect smartfoxserver 2x with external mysql database

Connect SmartFoxServer with External MySQL Database

Once you entered above details correctly, enter the  submit button and restart the server.

Server side Java API coding :

Java extension file do all the custom logic on the server side. To write your first Java Server side extension follow the this tutorial on how to write java server side extension.

I am using Eclipse IDE to write SmartFoxServer 2x Java server side extension. I used three Java class file

1. WkmExtension class — this main java extension file

2. UserRegistrationHandler class — this registration handler class

3. LoginEventHandler class — this login handler class.

During user registration after successful login as Guest user,  we will send Extension request from client side with userName, password and email to register a user in a database. where server side UserRegistrationHandler class gets the user name, password and email and updates those details in database as well sends success response to the client.

During login process we will send login request

sfs.send(new LoginRequest(userName,userPass,”muni”));

to the server with user name, password, where on the server addEventHandler

addEventHandler(SFSEventType.USER_LOGIN, LoginEventHandler.class);

receives user login request that calls LoginEventHandler class. So the LoginEventHandler class gets user name and password and does authentication  process. Finally it sends login success or failure message to the client.

here is main extension class (Wkmextension.java)

package com.game;

import com.smartfoxserver.v2.core.SFSEventType;
import com.smartfoxserver.v2.extensions.SFSExtension;

public class WkmExtension extends SFSExtension{

	@Override
	public void init()
	{
		//Custom user registration request handler
		addRequestHandler("register", UserRegistrationHandler.class);
		//Login request Handler
		addEventHandler(SFSEventType.USER_LOGIN, LoginEventHandler.class);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

}

Here RegistrationHandler class (UserRegistrationHandler.java)

package com.game;

import java.sql.SQLException;

import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class UserRegistrationHandler extends BaseClientRequestHandler {
	@Override
	public void handleClientRequest(User user, ISFSObject params) {
		// TODO Auto-generated method stub

		//Gets user sent parameters
		String name=params.getUtfString("name");
		String password=params.getUtfString("password");
		String email=params.getUtfString("email");
		// Initialize IDBManager object
		IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
		// MySQL query to update user details
		String sql="INSERT into login(user_name, password, email) values ('"+name+"','"+password+"','"+email+"')";

		try {
			// Excute MySQL query
			dbManager.executeUpdate(sql);
		} catch (SQLException e) {
			// Sends MySQL exception details to the client
			ISFSObject error= new SFSObject();
			error.putUtfString("error", "MySQL updation failed");
			send("register", error, user);
		}

		ISFSObject success= new SFSObject();
		success.putUtfString("success", "User successfully registered");
		send("register", success, user);

	}

}

Login handler class (LoginEventHandler.java)

package com.game;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.smartfoxserver.bitswarm.sessions.ISession;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.exceptions.SFSErrorCode;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.exceptions.SFSLoginException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

public class LoginEventHandler extends BaseServerEventHandler {
	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException {
		// TODO Auto-generated method stub

		// Grab parameters from client request
		String userName = (String) event.getParameter(SFSEventParam.LOGIN_NAME);
		String cryptedPass = (String) event.getParameter(SFSEventParam.LOGIN_PASSWORD);
		ISession session = (ISession) event.getParameter(SFSEventParam.SESSION);
		// Get password from DB
		IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
		Connection connection;

		// Grab a connection from the DBManager connection pool
        try {
			connection = dbManager.getConnection();

			// Build a prepared statement
	        PreparedStatement stmt = connection.prepareStatement("SELECT user_name, password FROM login where user_name='"+userName+"'");

		    // Execute query
		    ResultSet res = stmt.executeQuery();
		   // Verify that one record was found
 			if (!res.first())
 			{
 				// This is the part that goes to the client
 				SFSErrorData errData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
 				errData.addParameter(userName);

 				// Sends response if user gave incorrect user name
 				throw new SFSLoginException("Bad user name: " + userName, errData);
 			}

 			String dbPword = res.getString("password");

			// Verify the secure password
			if (!getApi().checkSecurePassword(session, dbPword, cryptedPass))
			{
				SFSErrorData data = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
				data.addParameter(userName);
				// Sends response if user gave incorrect password
				throw new SFSLoginException("Login failed for user: "  + userName, data);
			}

        }

        // User name was not found
        catch (SQLException e)
        {
        	SFSErrorData errData = new SFSErrorData(SFSErrorCode.GENERIC_ERROR);
        	errData.addParameter("SQL Error: " + e.getMessage());
        	// Sends response about mysql errors
        	throw new SFSLoginException("A SQL Error occurred: " + e.getMessage(), errData);
        }

    }

}

 

 

 

 

 

 

 .

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

%d bloggers like this:

Get Instant Script Download Access!