Search Unity

[GUIDE] How to Add User Registration and Login to your Game... for Free!

Discussion in 'Multiplayer' started by programmrzinc, Apr 11, 2013.

  1. programmrzinc

    programmrzinc

    Joined:
    May 29, 2011
    Posts:
    79
    Hello and welcome to the first installment
    We are going to add a credential system to an existing game, and make it work seamlessly with Unity.

    There are 3 things you will have to do:
    1. Create a c9.io account ( for PHP server )
    2. Alternativly, you can host your PHP file here
    3. Create a freesqldatabase.com account ( for database )
    4. Create a new scene in Unity

    With the credentials given to you via email from freesqldatabase.com, sign in to phpmyadmin.co. Create a table name Users with these columns
    1. Username
    2. Password
    3. Email

    You can create a demo user for testing in this database

    Now, navigate to c9.io. Create a workspace called credmanager ( for the purpose of this tut) , and in this workspace, create an crossdomail (crossdomain.xml ). This is the only way Unity can use the PHP file. Place the crossdomain file at the root of your project.
    Code (csharp):
    1.  
    2. <?xml version="1.0"?>
    3. <cross-domain-policy>
    4. <allow-access-from domain="*"/>
    5. </cross-domain-policy>
    6.  
    Now create a php file called Login ( Login.php ). You can copy this code into it.

    PHP:
    <?php
        
    // Database Things =========================================================
    //These values can be found in the email.
        
    $host "####.freesqldatabase.com"//<--put your host here
        
    $user "###"//<-- put username here
        
    $password "####"//<--put your password here
        
    $dbname "###"//<-- put your database name here
        
    mysql_connect($host$user$password) or die("Cant connect into database");
        
    mysql_select_db($dbname)or die("Cant connect into database");   
        
    // =============================================================================
        
    $Act $_GET["Act"];// what is action, Login or Register?
        
    $nick $_GET["User"];
        
    $pass $_GET["Pass"];   
        
    $Email $_GET["Email"];    
        if(
    $Act == "Login"){
        if(!
    $nick || !$pass) {
            echo 
    "Login or password cant be empty.";
            } else {
           
                     
    $SQL "SELECT * FROM Users WHERE Username = '" $nick "'";
                    
    $result_id = @mysql_query($SQL) or die("DB ERROR");
                    
    $total mysql_num_rows($result_id);
                        if(
    $total) {
                            
    $datas = @mysql_fetch_array($result_id);
                                if(!
    strcmp($pass$datas["Password"])) {
                                    echo 
    "Correct";
                                } else {
                                    echo 
    "Wrong";
                                }
                        } else {
                            echo 
    "No User";
                    }
                
        }
        }
       if(
    $Act == "Register"){
           
            
    $checkuser mysql_query("SELECT Username FROM Users WHERE Username='$nick'"); 
            
    $username_exist mysql_num_rows($checkuser);
            if(
    $username_exist 0)
            {
                  echo 
    "TAKEN";// Username is taken
                  
                  
    unset($nick);
                  exit();
            }else{
                
    $query "INSERT INTO Users (Username, Password,Email) VALUES('$nick', '$pass', '$Email')";
                
    mysql_query($query) or die("ERROR");
                
    mysql_close();
                echo 
    "Registered";
            }
        }
        
    // Close mySQL Connection
        
    mysql_close();
        
    ?>
    Now click run at the top of the window. it should open up a new tab with a url, that looks something similar to this(username will be your username however...):
    http://credmanager.username.c9.io/Login.php

    Now the fun part. We will manually modify the URL to register a user like as follows:

    http://credmanager.username.c9.io/L...123&Act=Register&Email=PGriffin@familyguy.net

    The webpage should now say Registered. But refresh the page again and it will say TAKEN. This is because your user is now entered the database! You can check this by going back to your phpmyadmin.co table. Now you have registered a user manually, but how do I login?

    Simply change the url to this:

    http://credmanager.username.c9.io/Login.php?User=Peter&Pass=Stewie123&Act=Login

    The webpage should now say correct! IT works!



    Now, most of the work is done. Now we can open up unity.

    Create a scene, and make it the first scene indexed in Build Settings.

    Create a JScript name Login( Login.js )

    Here is my script. You may need to edit this to suit your needs.
    Code (csharp):
    1. private var formNick = ""; //this is the field where the player will put the name to login
    2.     private var formPassword = ""; //this is his password
    3.     private var RformNick = ""; //this is the field where the player will put the name to login
    4.     private var RformPassword = "";
    5.     private var Remail = "";
    6.    private  var TRformPassword = "";
    7.     public var guiSkin : GUISkin;
    8.     var LoadOut : System.Boolean;
    9.     var LoadOutText = "";
    10.     var formText = ""; //this field is where the messages sent by PHP script will be in
    11.      
    12.     var URL = "http://credmanager.username.c9.io/Login.php"; //change for your URL
    13.    // var hash = "812ca28212be5705ad52010bccc9ea3f"; //change your secret code, and remember to change into the PHP file too
    14.     var DoLogin : System.Boolean;
    15.      
    16.     private var textrect = Rect (10, 150, 500, 500); //just make a GUI object rectangle
    17.      function Start (){
    18.      PlayerPrefs.DeleteAll();
    19.      
    20.      
    21.      }
    22.     function OnGUI() {
    23.             if(LoadOut){
    24.             GUI.skin = guiSkin;
    25.             GUI.Box (new Rect(Screen.width/2 - 150, Screen.height/2 - 30, 300, 60), LoadOutText);
    26.            
    27.            
    28.             }else{
    29.             GUI.Window (0, new Rect (Screen.width/2 - 250, Screen.height/2 - 150, 500, 400),Login, "");
    30.             }
    31.     }
    32.     function Login (id : int){
    33.    
    34.     if(DoLogin){
    35.    
    36.     GUILayout.BeginVertical();
    37.    
    38.         GUI.skin = guiSkin;
    39.        
    40.         GUILayout.Box (/* new Rect (Screen.width/2 - 250, Screen.height/2 - 150, 500, 400),*/"Login");
    41.        
    42.         GUILayout.BeginHorizontal();
    43.         GUILayout.FlexibleSpace();     
    44.         GUILayout.Label( "Username:" ); //text with your nick
    45.         formNick = GUILayout.TextField ( formNick , 15,  GUILayout.Width(345), GUILayout.Height(35));
    46.         GUILayout.EndHorizontal();
    47.         GUILayout.Space(10);
    48.        
    49.         GUILayout.BeginHorizontal();
    50.         GUILayout.FlexibleSpace(); 
    51.         GUILayout.Label( "Password:" );
    52.         formPassword = GUILayout.TextField (formPassword , 15,  GUILayout.Width(345), GUILayout.Height(35) ); //same as above, but for password
    53.         GUILayout.EndHorizontal();
    54.         GUILayout.Space(10);
    55.         GUILayout.BeginHorizontal();
    56.         GUILayout.Space(5);
    57.         if ( GUILayout.Button ("Login" ) ){ //just a button
    58.             Action("Login");
    59.         }
    60.         if ( GUILayout.Button ( "Sign Up" ) ){ //just a button
    61.             DoLogin = false;
    62.            
    63.         }
    64.         GUILayout.EndHorizontal();
    65.         GUILayout.EndVertical();
    66.        
    67.         }else{
    68.        
    69.         GUI.skin = guiSkin;
    70.        
    71.         GUILayout.Box ("Register");
    72.        
    73.         GUILayout.BeginHorizontal();
    74.         GUILayout.FlexibleSpace(); 
    75.         GUILayout.Label("Username:" );
    76.         RformNick = GUILayout.TextField (RformNick, 15,GUILayout.Width(300) ,GUILayout.Height(35)  );
    77.        
    78.         GUILayout.EndHorizontal();
    79.        
    80.         GUILayout.BeginHorizontal();
    81.         GUILayout.FlexibleSpace(); 
    82.         GUILayout.Label("Password:" );
    83.         RformPassword = GUILayout.TextField (RformPassword , 15,GUILayout.Width(300) , GUILayout.Height(35) );
    84.         GUILayout.EndHorizontal();
    85.        
    86.         GUILayout.BeginHorizontal();
    87.         GUILayout.FlexibleSpace(); 
    88.         GUILayout.Label("Password:" );
    89.        
    90.         TRformPassword = GUILayout.TextField (TRformPassword , 15,GUILayout.Width(300) , GUILayout.Height(35) );
    91.         GUILayout.EndHorizontal();
    92.        
    93.         GUILayout.BeginHorizontal();
    94.         GUILayout.FlexibleSpace(); 
    95.         GUILayout.Label("Email:" );
    96.         Remail = GUILayout.TextField (Remail, 75,GUILayout.Width(300) , GUILayout.Height(35) );
    97.         GUILayout.EndHorizontal();
    98.        
    99.        
    100.         if ( GUILayout.Button ("Finish" ) ){ //just a button
    101.             Action("Register");
    102.         }
    103.         if ( GUILayout.Button ("Back" ) ){ //just a button
    104.             DoLogin = true;
    105.            
    106.         }
    107.        
    108.        
    109.        
    110.         }
    111.        
    112.        
    113.         //GUI.TextArea( textrect, formText );
    114.     }
    115.      
    116.     function Action(Act : String) {
    117.    
    118.        
    119.         var form = new WWWForm(); //here you create a new form connection
    120.        //add your hash code to the field myform_hash, check that this variable name is the same as in PHP file
    121.         var tempURL : String;
    122.         if(Act =="Login"){
    123.         tempURL = URL + "?User="+formNick+"&Pass="+formPassword+"&Act="+Act;
    124.         }else{
    125.         tempURL = URL + "?User="+RformNick+"&Pass="+RformPassword+"&Act="+Act+"&Email="+Remail;
    126.         }
    127.         var w = WWW(tempURL); //here we create a var called 'w' and we sync with our URL and the form
    128.        
    129.         yield w; //we wait for the form to check the PHP file, so our game dont just hang
    130.        
    131.         if (w.error != null) {
    132.             //print(w.error); //if there is an error, tell us
    133.         } else {
    134.             if(w.data == "    Correct"){
    135.                 print("Logging In...");
    136.                 LoadOut = true;
    137.                 LoadOutText = "Signing In...";
    138.                 yield WaitForSeconds(5);
    139.                 PlayerPrefs.SetString("RegUser",formNick);
    140.                
    141.                 Application.LoadLevel(1);
    142.             }
    143.             if(w.data == "    Wrong"){
    144.                 LoadOut = true;
    145.                 LoadOutText = "Wrong Password";
    146.                 yield WaitForSeconds(3);
    147.                 LoadOut = false;
    148.             }
    149.             if(w.data == "    No User"){
    150.                 LoadOut = true;
    151.                 LoadOutText = "No Registered User Found";
    152.                 yield WaitForSeconds(3);
    153.                 LoadOut = false;
    154.             }
    155.             if(w.data == "    ILLEGAL REQUEST"){
    156.                 LoadOut = true;
    157.                 LoadOutText = "Server Error";
    158.                 yield WaitForSeconds(3);
    159.                 LoadOut = false;
    160.             }
    161.              if(w.data == "    Registered"){
    162.                 print("Account Created. Logging In.");
    163.                 LoadOut = true;
    164.                 LoadOutText = "Creating Account  Logging In...";
    165.                 PlayerPrefs.SetString("RegUser",RformNick);
    166.                 yield WaitForSeconds(5);
    167.                 Application.LoadLevel(1);
    168.                
    169.             }
    170.              if(w.data == "    ERROR"){
    171.                 LoadOut = true;
    172.                 LoadOutText = "Login Error. Restarting.";
    173.                 yield WaitForSeconds(3);
    174.                 Application.LoadLevel(0);
    175.             }
    176.             print(w.data);
    177.                
    178.            // formText = w.data; //here we return the data our PHP told us
    179.             w.Dispose(); //clear our form in game
    180.         }
    181.      
    182.         formNick = ""; //just clean our variables
    183.         formPassword = "";
    184.        
    185.        
    186. }
    187.    
    You will need to edit out your URL at the top. Set the script to the camera, and click in Unity. Type Peter for Username and Stewie123 for password. Hopefully it loads. If not, check your URL and c9.io to make sure it is still running. You might need a dedicated computer running c9.io if you want to test over a couple of days. I do not suggest c9.io as your full game handler. I just use it for testing since I have a budget of 0.

    Now that you have finished the tutorial, you can edit the scripts to suit your needs.


    If you want to , you can donate to me at bit.ly/NLGDonate:cool:
    Thanks
    - NitroLabGames ( Peter A. )
     
    Last edited: Apr 25, 2013
    herohelpme002 likes this.
  2. DryTear

    DryTear

    Joined:
    Nov 30, 2012
    Posts:
    312
    So this can do Registration and Login inside unity? im using this for my Multiplayer Building Game - great, this is something we all need. Wish I had paypal so I could donate, but im only 14 - I would also recommend that you improve your script with a ton of enhancements and publish it to the Asset Store for a payed priced, or publish the original for free.
     
    faizanshakeel likes this.
  3. programmrzinc

    programmrzinc

    Joined:
    May 29, 2011
    Posts:
    79
    What a great idea!

    And to answer your question, this is inside Unity. Just create a scene and add the script. So users cannot advance unless signed in.
     
  4. DryTear

    DryTear

    Joined:
    Nov 30, 2012
    Posts:
    312

    :) , I was thinking of that
     
  5. monsterjamp

    monsterjamp

    Joined:
    Feb 10, 2013
    Posts:
    30
    I'm trying to follow these instructions for my site.
    I'm having a lot of troubles. Can you do a separate tutorial or PM me?
     
  6. landon912

    landon912

    Joined:
    Nov 8, 2011
    Posts:
    1,579
    I found this GREAT tutorial covering EVERY ASPECT of how to implement this including web hosting, MySQL database, and Unity interactions:

    Link
     
  7. monsterjamp

    monsterjamp

    Joined:
    Feb 10, 2013
    Posts:
    30
    I'll try his tutorial but I don't have time right now.
    I wish some made a good written tutorial. :(
     
  8. programmrzinc

    programmrzinc

    Joined:
    May 29, 2011
    Posts:
    79
    I will make a detailed video in the coming week. Stay tuned
     
    HiradEmami likes this.
  9. monsterjamp

    monsterjamp

    Joined:
    Feb 10, 2013
    Posts:
    30
    Thanks landon the video was helpful.
     
  10. DryTear

    DryTear

    Joined:
    Nov 30, 2012
    Posts:
    312
    Great, just tested it out, worked, also not to bother, using WWWForm, can I use GUI.Label displaying my name indicating that im logged in and or possibly with 3DText(Mesh)?
     
  11. rahuxx

    rahuxx

    Joined:
    May 8, 2009
    Posts:
    537
    Looks good. Look forward for the video.
     
  12. Meshtopher

    Meshtopher

    Joined:
    Apr 29, 2013
    Posts:
    1
    Thanks! you saved me days of headaches!
     
  13. Bariel

    Bariel

    Joined:
    Mar 8, 2012
    Posts:
    34
    I don't like to put things down when people are trying to be helpful but there's a few things that people need to be aware of with this thread. Anyone considering using it should be aware that there are huge security flaws in this:

    - It's open to SQL Injection attacks, meaning anyone can alter anything in your database, change anyones password, delete accounts, drop tables, Anything.
    - Passwords are sent in plain text over the internet so anyone can steal your password
    - Passwords are stored in the database unencrypted so anyone gaining access to the database (i.e. via sql injection) can get a list of usernames, passwords and email addresses (probably a lot of people use the same password for their email too so you just compromised their passwords).

    I would advise anyone against using this without first correcting those things.

    These scripts are copied from elsewhere on these forums I find it bad etiquette is to copy someone else scripts, modify them and pass off as your own without attributing credit to the original author, especially when asking for donations.
     
    Severos, ow3n, Mintonne and 1 other person like this.
  14. Mastertrol

    Mastertrol

    Joined:
    Sep 29, 2013
    Posts:
    1
    Thanks This Helps a lot however that data is stored in my database but all if statement testing "Correct and Error" Ex. Fail they don't even get reconigze. It's like unity skips them.

    In the Editor it will display Correct but the LoadOut and LoadOutText are never activated/set


    How can I fix it so that when someone logs in it load level 1 like it's suppose to?
     
  15. devoted93

    devoted93

    Joined:
    Nov 7, 2013
    Posts:
    6
    Why hasn't somebody released a functional script? I'm a php developer and a web designer, been doing it for 6 years now. Is it not possible to repair these leaks? and if it is then sorry for being blunt but were you all born with loose screws?


    EDIT: Also why is this script using $_GET functions, you can simply use $_POST instead. This way you cannot edit the values directly without editing the script it's self. $_GET functions are generally alterable client side, meaning browser as the client.
     
    Last edited: Mar 12, 2014
    ow3n and princyam like this.
  16. tiggus

    tiggus

    Joined:
    Sep 2, 2010
    Posts:
    1,240
    POST method variables are just as easy to modify client side as GET, this is not a solution to the security issues pointed out.

    Most simple scripts like this with no input validation are basically you just installing a backdoor on your webserver for attackers to abuse. Not sure who you are berating for having loose screws but anyways thought I would point that out.
     
    Aiursrage2k likes this.
  17. amahlaka97

    amahlaka97

    Joined:
    Jul 7, 2017
    Posts:
    1
    i know this is old post, but i want to mention that you should NOT do login database this way, as it stores your password in plaintext and is extremely vulnerable to sql injection, please don't do login like this in anywhere more important than a potato
     
  18. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    Have you seen this:
     
    Noamxrx and KittyAnn like this.
  19. juraj123

    juraj123

    Joined:
    Feb 15, 2017
    Posts:
    3
    yeah but I need Database with BANN function...
     
  20. magstorey

    magstorey

    Joined:
    Feb 20, 2019
    Posts:
    13
    im trying to use this and have edited to my needs but you say create a js file but the code shown says its c# . and when i try to add the js file to my unity project, it wont let me. can anyone help?
     
  21. MonVenomF5

    MonVenomF5

    Joined:
    Mar 31, 2020
    Posts:
    2
    They had deleted javascript from Unity 2017.2 Beta since that then, Unity is not going to add Javascripts on upcoming updates but you know C# known as Csharp you can still script of course. But yes you can't add javascript on the new versions of unity 2017.2 to current versions.
     
  22. MonVenomF5

    MonVenomF5

    Joined:
    Mar 31, 2020
    Posts:
    2
    But if you want magstorey to get javascripts again just download Unity 2017.1 or older.
     
  23. mitchmeyer1

    mitchmeyer1

    Joined:
    Sep 19, 2016
    Posts:
    32
    Hey guys if you want to get similar functionality with doing 0 server setup / maintenance try Cloud Login
    https://github.com/mitchmeyer1/cloud-login
    cloudlogin.dev

    Its free for small indie projects and gives you more than just login!
     
    lucidtripper likes this.
  24. lucidtripper

    lucidtripper

    Joined:
    Aug 3, 2017
    Posts:
    24
    Hi Mitch

    I'm looking for a unity sdk that can reward players with crypto tokens direct into their wallet - something you can help with?

    Ed
    lucidtripper.com