0

I'm trying to build a session login with social login option via hybrid auth plugin. I'm having the following php code:

session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    header("location: index.php");
    exit();
}

include(dirname(__FILE__) . '/../nits-db/db.php');

if (isset($_POST["user_email"])&&isset($_POST["password"])) {
    $useremail = $_POST["user_email"];
    $password = $_POST["password"];

    $sql = "SELECT * FROM nits_user 
            WHERE user_email ='$useremail' 
              AND user_password ='$password'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row=mysqli_fetch_array($sql)) {
            $user_id = $row["user_id"];
        }
        $_SESSION["user_id"] = $user_id;
        $_SESSION["loggedin"] = true;
        $_SESSION["user_email"] = $useremail;
        $_SESSION["password"] = $password;
        $_SESSION["user_name"] = $row["user_name"];
        header("location: index.php");
        exit();
    } else {
        echo 'Information incorrect';
    }
} elseif(isset($_REQUEST["provider"])) {
    //the selected provider
    $provider_name = $_REQUEST["provider"];
    try
    {
        // inlcude HybridAuth library
        // change the following paths if necessary
        $config   = dirname(__FILE__) . '/hybridauth/config.php';
        require_once( "hybridauth/Hybrid/Auth.php" );

        // initialize Hybrid_Auth class with the config file
        $hybridauth = new Hybrid_Auth( $config );

        // try to authenticate with the selected provider
        $adapter = $hybridauth->authenticate( $provider_name );

        // then grab the user profile
        $user_profile = $adapter->getUserProfile();
    }

    // something went wrong?
    catch( Exception $e ) {
        header("Location: login.php");
    }

    // check if the current user already have authenticated using this provider before
    $user_exist = get_user_by_provider_and_id( $provider_name, $user_profile->identifier );

    // if the used didn't authenticate using the selected provider before
    // we create a new entry on database.users for him
    if( ! $user_exist ) {
        create_new_hybridauth_user(
                        $user_profile->email,
                        $user_profile->firstName,
                        $user_profile->lastName,
                        $provider_name,
                        $user_profile->identifier
                    );
    }

    // set the user as connected and redirect him
    $_SESSION["user_connected"] = true;

    header("Location: index.php");
}

$server = 'localhost';
$user = 'root';
$password = '';
$db = 'nits_editor';

global $link;

$link = mysqli_connect($server,$user,$password,$db);


function mysqli_query_excute( $sql ) {   
    $server = 'localhost';
    $user = 'root';
    $password = '';
    $db = 'nits_editor';

    $link = mysqli_connect($server,$user,$password,$db);

    $result = mysqli_query( $link, $sql );

    if(  ! $result ) {
        die( printf( "Error: %s\n", mysqli_error( $link ) ) );
    }
    return $result->fetch_object();
}

/*
* get the user data from database by email and password
**/
function get_user_by_email_and_password( $email, $password )
{
    return mysqli_query_excute( "SELECT * FROM nits_user 
                                 WHERE user_email = '$email' 
                                   AND user_password = '$password'" );
}

/*
* get the user data from database by provider name and provider user id
**/
function get_user_by_provider_and_id( $provider_name, $provider_user_id )
{
    return mysqli_query_excute( "SELECT * FROM nits_user 
                                 WHERE hybridauth_provider_name = '$provider_name' 
                                   AND hybridauth_provider_uid = '$provider_user_id'" );
}

/*
* get the user data from database by provider name and provider user id
**/
function create_new_hybridauth_user( $email, $first_name, $last_name, $provider_name, $provider_user_id )
{
    // let generate a random password for the user
    $password = md5( str_shuffle( "0123456789abcdefghijklmnoABCDEFGHIJ" ) );

    mysqli_query_excute(
        "INSERT INTO nits_user
        (
            user_email,
            user_password,
            user_firstname,
            user_lastname,
            hybridauth_provider_name,
            hybridauth_provider_uid,
            user_createdate
        )
        VALUES
        (
            '$email',
            '$password',
            '$first_name',
            '$last_name',
            $provider_name,
            $provider_user_id,
            NOW()
        )"
    );
}

While executing the above, normal login is working perfectly fine but, while using social login I'm getting an error. I checked the whole code and came to know that $sql paramenter going inside the mysqli_query is getting two parameters, I mean user is being checked and selected from the database and also new user is bieng inserted into the database. I guess the userexists function throws true and false both. when i echoed the sql i got following code:

 SELECT * FROM nits_user WHERE hybridauth_provider_name = 'facebook' AND hybridauth_provider_uid = '479196262278189'localhostrootnits_editorINSERT INTO nits_user ( user_email, user_password, user_firstname, user_lastname, hybridauth_provider_name, hybridauth_provider_uid, user_createdate ) VALUES ( 'nitishnoetic@gmail.com', 'f7bcca52ba33335000b15c58440588aa', 'Nitish', 'Kumar', facebook, 479196262278189, NOW() )

It is selecting and inserting both.

Please help me out with this.

RiggsFolly
  • 83,545
  • 20
  • 96
  • 136
Nitish Kumar
  • 5,259
  • 12
  • 57
  • 123
  • Take a close look at the echoed sql, _I mean a close look_ and see if it looks valid to you??? – RiggsFolly May 05 '16 at 10:32
  • I know it is not correct either it has to select or to insert it is executing both. Can you please help me out with this. – Nitish Kumar May 05 '16 at 11:00
  • Not many of us have the time to wade through all that badly indented code, specially as you do not even identify which is _Normal Login_ and which is _social login_ code. Remember terminology like this can lead to confusion at best – RiggsFolly May 05 '16 at 11:33
  • 1
    Please dont __roll your own__ password hashing. PHP provides `password_hash()` and `password_verify()` – RiggsFolly May 05 '16 at 11:39
  • 1
    **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure that you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard May 05 '16 at 15:53

1 Answers1

1

try this

database connection only once.

    <?php


     //database connection  at top and also once only 

      global $link;
     $server = 'localhost';
    $user = 'root';
    $password = '';
    $db = 'nits_editor';

$link = mysqli_connect($server,$user,$password,$db);




session_start();

if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)
{
    header("location: index.php");
    exit();
}

include(dirname(__FILE__) . '/../nits-db/db.php');

if (isset($_POST["user_email"])&& isset($_POST["password"]))
{
    $useremail = $_POST["user_email"];
    $password = $_POST["password"];

    $sql = "SELECT * FROM nits_user WHERE user_email ='$useremail' AND user_password ='$password'";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) 
    {
        while($row=mysqli_fetch_array($sql))
        {
            $user_id = $row["user_id"];
        }
        $_SESSION["user_id"] = $user_id;
        $_SESSION["loggedin"] = true;
        $_SESSION["user_email"] = $useremail;
        $_SESSION["password"] = $password;
        $_SESSION["user_name"] = $row["user_name"];
        header("location: index.php");
        exit();
    }
    else
    {
        echo 'Information incorrect';
    }
}
elseif(isset($_REQUEST["provider"]))
{
    //the selected provider
    $provider_name = $_REQUEST["provider"];
    try
    {
        // inlcude HybridAuth library
        // change the following paths if necessary
        $config   = dirname(__FILE__) . '/hybridauth/config.php';
        require_once( "hybridauth/Hybrid/Auth.php" );

        // initialize Hybrid_Auth class with the config file
        $hybridauth = new Hybrid_Auth( $config );

        // try to authenticate with the selected provider
        $adapter = $hybridauth->authenticate( $provider_name );

        // then grab the user profile
        $user_profile = $adapter->getUserProfile();
    }

    // something went wrong?
    catch( Exception $e )
    {
        header("Location: login.php");
    }

        /*
* get the user data from database by provider name and provider user id
**/
function get_user_by_provider_and_id( $provider_name, $provider_user_id,$link )
{
    $qry1 ="SELECT * FROM nits_user WHERE hybridauth_provider_name = '$provider_name' AND hybridauth_provider_uid = '$provider_user_id'";

        $result1 = mysqli_query($link,$qry1);

        return mysqli_fetch_object($result1);

}



    // check if the current user already have authenticated using this provider before
    $user_exist = get_user_by_provider_and_id( $provider_name, $user_profile->identifier,$link );

    // if the used didn't authenticate using the selected provider before
    // we create a new entry on database.users for him
    if( ! $user_exist )
    {



                function create_new_hybridauth_user( $email, $first_name, $last_name, $provider_name, $provider_user_id ,$link)
                {
                    // let generate a random password for the user
                    $password = md5( str_shuffle( "0123456789abcdefghijklmnoABCDEFGHIJ" ) );

                    $qry2 = (
                        "INSERT INTO nits_user
                        (
                            user_email,
                            user_password,
                            user_firstname,
                            user_lastname,
                            hybridauth_provider_name,
                            hybridauth_provider_uid,
                            user_createdate
                        )
                        VALUES
                        (
                            '$email',
                            '$password',
                            '$first_name',
                            '$last_name',
                            $provider_name,
                            $provider_user_id,
                            NOW()
                        )"
                    );

                    $result2 = mysqli_query($link,$qry2);

                //$last_insert_id = mysqli_insert_id($link);


                return $email;
                }


        $val = create_new_hybridauth_user(
            $user_profile->email,
            $user_profile->firstName,
            $user_profile->lastName,
            $provider_name,
            $user_profile->identifier,$link
        );


        if($val)
        {

                 $_SESSION['loggedin'] = true;



                 if(isset($_SESSION['loggedin']))
                 {
                    header('Location: success_page.php');
                 }
         }


        }
        else
        {

             // set the user as connected and redirect him

            $_SESSION['loggedin'] = $user_profile->email;



                 if(isset($_SESSION['loggedin']))
                 {
                    header('Location: success_page.php');
                 }
            header("Location: index.php");

        }
    }




?>
JYoThI
  • 11,587
  • 1
  • 9
  • 24
  • 1
    Why should the OP "try this"? A **good answer** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer. – RiggsFolly May 05 '16 at 11:29
  • @jothi thanks for your answer, I'm getting an error of `undefined variable: email` in the `if($val)` statement. – Nitish Kumar May 05 '16 at 11:46
  • sry my mistake change like this $_SESSION['loggedin'] = true; insted of $_SESSION['loggedin'] = $email; – JYoThI May 05 '16 at 11:50
  • @jothi : But its not adding to the database. I can see in phpmyadmin, no addition to nits_user table.!!!! – Nitish Kumar May 05 '16 at 12:24
  • check function create_new_hybridauth_user calling correctly working or echo mysqli_connect_error() to get the any mysql error ? – JYoThI May 05 '16 at 12:30
  • try to login by new user – JYoThI May 05 '16 at 12:35
  • @jothi : qry2 syntax is correct? i mean it should be inside brackets? I tried mysqli_connect_error and shows no error and also tried logging in with new user. – Nitish Kumar May 05 '16 at 13:39