[TUTORIAL] Database login with ActionScript

Post here your questions about Actionscript and Java server side extensions development.

Moderators: Lapo, Bax

Flappi282
Posts: 158
Joined: 20 May 2009, 17:51
Contact:

[TUTORIAL] Database login with ActionScript

Post by Flappi282 »

To get this tutorial to work, find and edit this line in your config file
<Zone name="<!-- REPLACE WITH YOUR ZONE NAME -->" uCountUpdate="<!-- REPLACE WITH BOOLEAN -->" buddyList="<!-- MAX BUDDY LIST COUNT -->" maxUsers="<!-- MAX USERS-->" customLogin="true">
You also need to setup a database connection:

Code: Select all

<DatabaseManager active="true">

	<Driver>org.h2.Driver</Driver>
	<ConnectionString>jdbc:h2:tcp://localhost/~/test</ConnectionString>
<!-- Using MySQL Results in
	<Driver>com.mysql.jdbc.Driver</Driver>
	<ConnectionString>jdbc:mysql://127.0.0.1:3306/test</ConnectionString>
-->
	<UserName>DB USERNAME</UserName>
	<Password>DB PASS</Password>

	<TestSQL><![CDATA[SELECT COUNT(*) FROM <!-- USER TABLE -->]]></TestSQL>
	
	<MaxActive>10</MaxActive>
	<MaxIdle>10</MaxIdle>
	  
	<OnExhaustedPool>fail</OnExhaustedPool>
	<BlockTime>5000</BlockTime>
	
</DatabaseManager>
Now lets add an extension to this zone:

Code: Select all

			<Extensions>
				<extension name="dbLogin"  className="dbLogin.as" type="script" />
			</Extensions>
Now place this ActionScript code into the dbLogin.as extension file

Code: Select all

function init() {
	dbase = _server.getDatabaseManager();
}

function destroy(){
        //trace("dbLogin extension Closed");
}

function handleRequest(cmd, params, user, fromRoom){
trace("XT Message received: User: " & user & "\n Room: " & fromRoom  & "\n Command: " & cmd); //We don't need any requests
}

function handleInternalEvent(evt) {
	if (evt.name == "loginRequest") {
		trace("recieved event");
		
      var error = ""; 
       
      var nick = evt["nick"].toLowerCase(); 
      nick = _server.escapeQuotes(nick); 
      var pass = evt["pass"]; 
      pass = _server.escapeQuotes(pass); 
      var chan = evt["chan"];  //Remove this, and the sky will fall on your head
      var qRes = dbase.executeQuery("SELECT * FROM usertable WHERE username='" & nick & "' LIMIT 1;");
      if (qRes != null) {
         for (var i = 0; i<qRes.size(); i++) { 
                  var row  = qRes.get(i);
                  if(row['password'] == pass){
                        error = "";
                  } else {
                        error = "Incorrect Password";
                  }
         }
} else {
error = "Invalid User";
}
var res = new Object();
if(error != ""){
res._cmd = "logKO";
} else {
var login = _server.loginUser(nick, pass);
if(login.success){
error = "";
res._cmd = "logOK";
} else {
error = login.error;
}
res.err = error;
}
_server.sendResponse(res,-1,null,chan);
} //END FIRST BLOCK. DO NOT REMOVE
} //DO NOT REMOVE ME EITHER
In the client side, add this code:

Code: Select all

function doLogin(user, pass){
        zone = "simpleChat";
        if (!_global.isBusy)
        smartfox.login(zone, user, pass)
}

smartfox.onExtensionResponse = function(resObj:Object) {
        if (resObj._cmd == "logOK") {
                // Login Success Example Code
                _global.myName = resObj.name
                gotoAndStop("chatRoom")
        } else if (resObj._cmd == "logKO") {
                // Login failed example code
               gotoAndStop("login");
               error_txt.text = resObj.err;
        }
}
If you have any questions, feel free to post them, and I will happily reply
--
Flappi282
09op
Posts: 86
Joined: 12 Jun 2009, 06:16

Post by 09op »

hi flappi!
where are the username and passwords stored?
smilefr
Posts: 58
Joined: 23 Mar 2009, 16:50
Location: France

Post by smilefr »

09op wrote:hi flappi!
where are the username and passwords stored?
in a database, since there is a "dbase.executeQuery"
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

I'm trying now to configure MySQL server and the Client. But when i send the login, in server console showed:

Code: Select all

[ SEVERE ] [id: 17] (DbManager.executeQuery): DbManager error during query/result creation: 0
In the database i have created 2 rows. username and password. It's there any problem?

EDIT: OK, when i try to type in SQL syntax : SELECT * FROM usertable WHERE username="cpdavidd" LIMIT 1; , it gets the username right. But in the extension doesn't work

EDIT2: Then now typed :

Code: Select all

var qRes = dbase.executeQuery("SELECT * FROM usertable WHERE username='"+nick+"' LIMIT 1;");
And the console ends with dbLogin.as : recieved event
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

The server got the username from client and can connect to the database. BUT somewhy always if i type an username, that exist in database, the login fails with REASON: Incorrect Password.

Here is my whole code:

Code: Select all

function init() {
   dbase = _server.getDatabaseManager();
}

function destroy(){
        //trace("dbLogin extension Closed");
}

function handleRequest(cmd, params, user, fromRoom){
trace("XT Message received: User: " & user & "\n Room: " & fromRoom  & "\n Command: " & cmd); 
}

function handleInternalEvent(evt) {
   if (evt.name == "loginRequest") {
      trace("Recieved Login Request");
      
	  var error = "";
       
      var nick = evt["nick"].toLowerCase();
      nick = _server.escapeQuotes(nick);
      var pass = evt["pass"];
      pass = _server.escapeQuotes(pass);
      var chan = evt["chan"]; 
	  trace("User "+nick+" is connection to the server" );
      var qRes = dbase.executeQuery("SELECT * FROM usertable WHERE username='"+nick+"' LIMIT 1;");
      if (qRes != null) {
         for (var i = 0; i<qRes.size(); i++) {
                  var row  = qRes.get(i);
                  if(row['password'] == pass){
                        error = "";
                  } else {
                        error = "Incorrect Password";
                  }
         }
} else {
error = "Invalid User";
}
var response = new Object();
if(error != ""){
trace("Login of user:"+nick+" failed. Reason:"+error)
response._cmd = "logKO";
} else {
var login = _server.loginUser(nick, pass);
if(login.success){
error = "";
response._cmd = "logOK";
trace("Login of user:"+nick+" was been succefful")
} else {
error = login.error;
}
response.err = error;
}
_server.sendResponse(response,-1,null,chan);
} 
} 
And here is sendLogin function

Code: Select all

function sendLogin()
{
	if (!_global.isBusy)
		smartfox.login(zone, login_txt.text, password_text.text)
}
... and here is the onExtensionResponse fuction, which is somewhy not working

Code: Select all

smartfox.onExtensionResponse = function(resObj:Object) {
        if (resObj._cmd == "logOK") {
                // Login Success Example Code
                _global.myName = resObj.name
                gotoAndStop("chat")
        } else if (resObj._cmd == "logKO") {
                // Login failed example code
				_gloabl.isBusy 	= true
               error_txt.text = resObj.err;
        }
} 

cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

So found with trace, that row['password'] will give result: undefined.

If it's correct, then this part of code:

Code: Select all

      if (qRes != null) {
         for (var i = 0; i < qRes.size(); i++) {
                  var row  = qRes.get(i);
... is writen bad. Anyone repair :D
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

Sorry. :oops: This code is writted bad.

if(row["password"] == pass){

or my database is wrong? I have 2 rows. username and password. Typing the swl query:

Code: Select all

SELECT * FROM usertable WHERE username='nickname of user' LIMIT 1;
or

Code: Select all

SELECT * FROM usertable WHERE password='password of user' LIMIT 1;
get's the right value. So where is the problem?
gl0om
Posts: 54
Joined: 30 Mar 2010, 17:39

Post by gl0om »

cpdavidd wrote:Sorry. :oops: This code is writted bad.

if(row["password"] == pass){

or my database is wrong? I have 2 rows. username and password. Typing the swl query:

Code: Select all

SELECT * FROM usertable WHERE username='nickname of user' LIMIT 1;
or

Code: Select all

SELECT * FROM usertable WHERE password='password of user' LIMIT 1;
get's the right value. So where is the problem?
Maybe this sould work...

Code: Select all

SELECT * FROM usertable WHERE password='password of user' AND username = 'username of user' LIMIT 1;

Code: Select all

if (qRes != null) { 
//ok
}
else
{
//fail
}
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

Now, i can't find solution for this. gl00m's sql

Code: Select all

SELECT * FROM usertable WHERE password='"+pass+"' AND username = '"+nick+"' LIMIT 1; 
... get's the right value in phpmyadmin, but the cmd response always gets: undefined. Also if I "harcode" it, it still gets undefined.

So the code doesn't work :(

Anyone help? :(
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

Anyone please?
BigFIsh
Posts: 1698
Joined: 25 Feb 2008, 19:26
Location: New Zealand

Post by BigFIsh »

The syntax is: row.getItem("password")
Smartfox's forum is my daily newspaper.
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

That i tried too (replacing the row["password"]), but the result is, that the cmd response is nor: undefined. :o

I'm now thinking, that is a problem in database, but I¨m not sure
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

Ok, for a hours of coding I found the corrrect way :)

But I got a small problem:
If the username in database doesn't exist, it causes that:
1) The console says: ¨

Code: Select all

18:42:45.601 - [ FINE ] > SystemHandler action refused: getRmList, from: ip adress...
2) The client enters the chat without username

Oh here is the log in the client:

Code: Select all

[Sending]: <msg t='sys'><body action='login' r='0'><login z='testZone'><nick><![CDATA[ddd]]></nick><pword><![CDATA[d]]></pword></login></body></msg>

[Received]: <msg t="xt"><body action="xtRes" r="-1"><dataObj><var n=&apos;_cmd&apos; t=&apos;s&apos;>logOK</var></dataObj></body></msg>
[Sending]: <msg t='sys'><body action='getRmList' r='-1'></body></msg>
And here is the part of the extension, that cares about loginning

Code: Select all

		if (qRes != null) {
                ...
		} else {
		error = "not exist" //this should work, but doesnt :((
		}
Last edited by cpdavidd on 23 Apr 2010, 13:42, edited 1 time in total.
BigFIsh
Posts: 1698
Joined: 25 Feb 2008, 19:26
Location: New Zealand

Post by BigFIsh »

Code: Select all

      if (qRes != null) //means that it successfully excuted the query
      {
            if (qRes.size() > 0) 
            {
                 //found a user (or users)
            }
            else
            {
                  //user not found
            }
      }
      else
      {
            //problem with excuting the query
      }
Smartfox's forum is my daily newspaper.
cpdavidd
Posts: 31
Joined: 25 Feb 2010, 08:03

Post by cpdavidd »

Thanks ALOT :D
Post Reply