Login authentication from database

hallo,

i am trying to undestand how can i create a login process.

My users will be stored in an external mysql database. I don`t want to use webviews but only REST services to get and post data. How it is possible?

thank you very much

2 Likes

Hi @gnasis,
You could check out this link: http://www.nikola-breznjak.com/blog/codeproject/posting-data-from-ionic-app-to-php-server/?ckattempt=1

2 Likes

hallo @zachary545

yes it seems to work!but unfortunately this doesn`t include a mysql database of the server-side!

Hey @gnasis,

I’m the author of the post that @zachary545 posted (thanks for linking!). Sure, there’s no example for MySQL.

It seems you would need to go through some tutorials that deal with that particular topic (PHP + MySQL).

I personally don’t have a good starting tutorial on that, so I would like to ask other forum members that they share any good that they used once they were starting with this topic.

What I would like to urge you is that once you get acquainted with querying the MySQL database with PHP that you take a more in-depth look into prepared statements, and I happened to have written a decent tutorial on that subject: http://www.nikola-breznjak.com/blog/php/using-prepared-statements-in-php-with-mysqli/.

Hope this helps and gives you a starting point. Btw, I would also like to note that if this is your first time delving into databases with PHP then don’t feel discouraged. You will need some amount of time to get the idea of how it all works together.

Good luck!

1 Like

hi @Hitman666

i have found this one and it seems very good but this is not combined with ionic! :confused:

do you think it is possible?

thank you

1 Like

Hi @gnasis,

Ok, so, there are two steps to this:

  1. How to send data from Ionic to PHP server (you’ve got this part covered with my tutorial)
  2. How to query the MySQL database with PHP so that you can get the data from it that you need (this part you need to learn)

What I would like make clear is the fact that 1 and 2 are not necessarily connected. What I mean by that is that you can have your backend on any “stack” that you may wish (be it a MEAN stack with MongoDB as a database, be it a LAMP stack with MySQL as the database, or even LAPP stack with Postgres as the database). It really doesn’t matter what you use for a backend store or language (PHP, Node, Python, you name it) as long as you make it available as a REST service.

As I quickly took a look at that tutorial it seems it’s talking about REST, so yeah, go and check that out.

As I said, it seems you’re quite new to this, so don’t expect to get all of the answers in one afternoon, it takes (well, at least in my case since I’m no wizard ;)) some time…

Good luck!

1 Like

hi @Hitman666

yes i`m quite new too this! :wink:

i am trying to combine the second tutorial!i hope i wil figure it out!

thank you very much!

I’m sure you will. If, however, you get stuck, and have a specific question - don’t hesitate to ask.

Just remember to never stop learning :innocent:

I just tackled this myself last week. I found this tutorial on creating an email authentication system and then just tailored it to be used with angular/ionic. It goes step by step and even uses a hash to store the passwords in the database so the actual password is not visible to DB administrators. The biggest challenge was submitting forms the angular way vs traditional. But once you conquer that, the rest is quite easy and is pretty much done for you in this tutorial.

I added several fields to my service, but the principle was the same.

hi @rgecy

this is a very good tuturial for the login process about php and mysql. but how it is connected with ionic and angularjs???

1 Like

For the answer to this question you should again read the answer I already gave you: Login authentication from database. Now you have both steps covered.

1 Like

Ok, here is some of my code. Basically I created a login service to use in my registration controller. My login form used the email and password to log in and retrieve the user data, then passed it back from the php as JSON . This is just the way I did it and may not be the prefered way, but you should be able to put it together from this and the tutorials.

Some of the PHP… login.php

<?php

$postdata = file_get_contents("php://input");
$loginData = json_decode($postdata);
$email = $loginData->email;
$password = $loginData->password;

$userData = array('userID' => '',
				'firstName' => '',
				'lastName' => '',
				'phone' => '',
				'email' => '',
				'active' => '');	

mysql_connect("IP address of DB", "DB user name", "DB password") or die('{"userData":'.json_encode($userData).', "error": {"code": "003", "message": "Login error! Code: 003"}}'); // Connect to database server(localhost) with username and password.
mysql_select_db("table name") or die('{"userData":'.json_encode($userData).', "error": {"code": "004", "message": "Login error! Code: 004"}}'); 

if(!empty($email) && !empty($password)){
	
	//echo($email.'  '.$password);
	
	$email = mysql_escape_string($email);
	$password = mysql_escape_string(md5($password));
	 
	$results = mysql_query("SELECT id, fname, lname, phone, email, password, active FROM users WHERE email='".$email."' AND password='".$password."' LIMIT 1") or die('{"error":"Login error! Code: 003"}'); 
	$match  = mysql_num_rows($results);
	
	$res = mysql_fetch_assoc($results);
	
	if($match > 0 ){		
		if ($res['active'] = 1) {
			// login success
			$userData['userID'] = $res['id'];
			$userData['firstName'] = $res['fname'];
			$userData['lastName'] = $res['lname'];
			$userData['phone'] = $res['phone'];
			$userData['email'] = $res['email'];
			$userData['active'] = $res['active'];
			echo ('{"userData":'.json_encode($userData).',"error":{"code":"000","message":"Logged in as '.$userData['firstName'].' '.$userData['lastName'].'."}}');
		} else {				
			echo('{"userData":'.json_encode($userData).', "error":{"code":"001","message":"Your account has not been ativated. Please verify your account by clicking on the link in the activation email sent when you registered.\r\n If you did not receive an email, click on the Resend Activation Email link and make sure the email is not being blocked by your spam filter."}}');
		}
	}else{
		// login failed
		echo ('{"userData":'.json_encode($userData).', "error": {"code": "002","message": "The email or password you entered is incorrect."}}');			
	}
} else {
	// something failed with submitting data, should never get here!
	echo('{"userData":'.json_encode($userData).', "error": {"code":"005", "message": "Login error! Code: 005"}}');
}
?>

Here’s my controller…

.controller('RegistrationCtrl', function ($scope, LoginService) {

    $scope.login = function (userLogin) {
        LoginService.loginUser(userLogin)
        .then(function (data) {
            //log in successfull
        }, function (data) {
            //log in failed
        });
    };

    $scope.register = function (reg) {
       LoginService.registerUser(reg)
        .then(function (resp) {
            // registration success
        }, function (resp) {
            //registration error
        });      
    };        
})

And heres my service…

.service('LoginService', function ($q, $http) {
    return {
        loginUser: function (loginData) {
            var deferred = $q.defer(),
                promise = deferred.promise;

            $http({
                url: 'http://someurl/login.php',
                method: "POST",
                data: loginData,
                headers: {'Content-Type': 'application/json'}
            })
                .then(function (response) {
                    if (response.data.error.code === "000") {
                        console.log("User login successful: " + JSON.stringify(response.data));
                        deferred.resolve(response.data);
                    } else {
                        console.log("User login failed: " + JSON.stringify(response.data.error));
                        deferred.reject(response.data);
                    }
                }, function (error) {
                    console.log("Server Error on login: " + JSON.stringify(error));
                    deferred.reject(error);
                });

            promise.success = function (fn) {
                promise.then(fn);
                return promise;
            };
            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            };
            return promise;
        },
        
        registerUser: function (regData) {
            var deferred = $q.defer(),
                promise = deferred.promise;
            
            $http({
                url: 'http://someurl/register.php',
                method: "POST",
                data: regData,
                headers: {'Content-Type': 'application/json'}
            }).then(function (response) {
                if (response.data.error.code === "000") {
                    console.log("User login successful: " + JSON.stringify(response.data));
                    deferred.resolve(response.data);
                } else {
                    console.log("User login failed: " + JSON.stringify(response.data.error));
                    deferred.reject(response.data);
                }
            }, function (error) {
                console.log("Server Error on login: " + JSON.stringify(error));
                deferred.reject(error);
            });
            
            promise.success = function (fn) {
                promise.then(fn);
                return promise;
            };
            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            };
            return promise;
        }
    };
});

@rgecy: thanks for posting this example for @gnasis.

However, as you can read on the official PHP site, mysql_* commands are being deprecated as of PHP 5.5.0. You can take a look at a tutorial I wrote about using mysqli (notice the letter i) extension with PHP: http://www.nikola-breznjak.com/blog/php/using-prepared-statements-in-php-with-mysqli/.

hallo there @Hitman666 @rgecy

please can you have a look at this?

thank you very much

Hi, Can you please share how to send mail confirmation once the user has done registration?

You can take a look at this tutorial on How to send an email in Ionic application.

Yes I already studied the same tutorial.
I am not using FORM, I am using ng-click=“register(name, email, password)” for SignUp.
My app is working fine. But after a successful registration, the email is not sending to corresponding user?

Is there any way to send this? I am using FIREBASE.

It makes no difference if you’re using form or not. You would issue an ajax request inside the register() function, in which you would call the api for email sending.

Where should I add ajax request?
Can you please share the code for email sending api?
**This is my register code : **
$scope.register = function(name, email, password) {
fbAuth.$createUser({email: email, password: password}).then(function(userData) {
$ionicLoading.show({
template: ‘Please wait…’
});
return fbAuth.$authWithPassword({
email: email,
password: password
});
})

From the official example: https://www.firebase.com/docs/web/api/firebase/authwithpassword.html

var ref = new Firebase(“https://.firebaseio.com”);
ref.authWithPassword({
“email”: "bobtony@firebase.com",
“password”: “correcthorsebatterystaple”
}, function(error, authData) {
if (error) {
console.log(“Login Failed!”, error);
} else {
console.log(“Authenticated successfully with payload:”, authData);

//call the email sending api here

}
});

As for the email sending api written in PHP, you can take a look at my blog post which I mentioned earlier, I gave the full code listing there.