How to setup Login/Register using Ionic Cordova : Part 6
Posted in Html5
Here i will give you an overview on, how i implemented a Login / Register in my app. You can also refer to my complete project via GitHub.
If you find it difficult to follow, please go through my previous set of tutorials on Ionic Development:
How to design HTML5 app using Ionic Cordova : Part 2
How to build HTLM5 app using Ionic Cordova: Part 3
How to build HTML5 Shopping Cart app using Ionic Cordova : Part 4
How to build HTML5 Shopping Cart app using Ionic Cordova : Part 5
UPDATE (10-07-16):
Latest FoodKart V0.3 is released. Read the complete tutorial here.
LEVEL 2 [ Intermediate ] :-
SERVER SIDE:
LOGIN PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); if(isset($_GET["e"]) && isset($_GET["p"]) ){ if( !empty($_GET["e"]) && !empty($_GET["p"]) ){ $conn = new mysqli("localhost", "username", "password", "database"); $username=$_GET["e"]; $password=$_GET["p"]; // To protect MySQL injection for Security purpose $username = stripslashes($username); $password = stripslashes($password); $username = $conn->real_escape_string($username); $password = $conn->real_escape_string($password); $password = md5($password); $query="SELECT u_name, u_id, u_phone, u_address, u_pincode FROM users where u_verified=1 and u_id like '".$username."' and u_password like '".$password."'"; $result = $conn->query($query); $outp = ""; if( $rs=$result->fetch_array(MYSQLI_ASSOC)) { if ($outp != "") {$outp .= ",";} $outp .= '{"u_name":"' . $rs["u_name"] . '",'; $outp .= '"u_id":"' . $rs["u_id"] . '",'; $outp .= '"u_phone":"' . $rs["u_phone"] . '",'; $outp .= '"u_address":"' . $rs["u_address"] . '",'; $outp .= '"u_pincode":"'. $rs["u_pincode"] . '"}'; } $outp ='{"records":'.$outp.'}'; $conn->close(); echo($outp); } } ?> |
REGISTER PHP :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); if(isset($_GET["n"]) && isset($_GET["un"])&& isset($_GET["ps"])&& isset($_GET["ph"])&& isset($_GET["add"])&& isset($_GET["pin"]) ){ if( !empty($_GET["n"]) && !empty($_GET["un"])&& !empty($_GET["ps"])&& !empty($_GET["ph"])&& !empty($_GET["add"])&& !empty($_GET["pin"]) ){ $conn = new mysqli("localhost", "usrname", "password", "database"); $name=$_GET["n"]; $username=$_GET["un"]; $password=$_GET["ps"]; $password=md5($password); $phone=$_GET["ph"]; $address=$_GET["add"]; $pincode=$_GET["pin"]; // To protect MySQL injection for Security purpose $name = stripslashes($name); $username = stripslashes($username); $password = stripslashes($password); $phone = stripslashes($phone); $address = stripslashes($address); $pincode = stripslashes($pincode); $name = mysql_real_escape_string($name); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $phone = mysql_real_escape_string($phone); $address = mysql_real_escape_string($address); $pincode = mysql_real_escape_string($pincode); $check="SELECT * FROM users WHERE u_id = '$username'"; $rs = mysqli_query($conn,$check); $data = mysqli_fetch_array($rs, MYSQLI_NUM); // check if the user already exists. if($data[0] > 1) { $outp='{"result":{"created": "0" , "exists": "1" }'; } else{ $sql = "INSERT INTO users VALUES ('$name', '$username', '$password', '$phone','$address' ,'$pincode',1 )"; if ($conn->query($sql) === TRUE) { $outp='{"result":{"created": "1", "exists": 0" }'; } } // created= 1 means the account is created. // exists =1 means the account already exists. echo $outp; $conn->close(); } } ?> |
MYSQL DATABASE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
-- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `u_name` varchar(300) NOT NULL, `u_id` varchar(300) NOT NULL, `u_password` varchar(300) NOT NULL, `u_phone` varchar(300) NOT NULL, `u_address` varchar(300) NOT NULL, `u_pincode` varchar(300) NOT NULL, `u_verified` tinyint(1) NOT NULL, PRIMARY KEY (`u_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; |
CLIENT SIDE
LOGIN PAGE
1. templates\login.html [ LOGIN PAGE]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<ion-view title="Login"> <ion-content padding="'true'" class="has-header"> <form class="list" > <ion-list> <label class="item item-input"> <span class="input-label">Email</span> // here we create a user object and store email as its property <input ng-model="user.email" type="email" placeholder="" > </label> <label class="item item-input"> <span class="input-label">Password</span> // user object <input ng-model="user.password" type="password" placeholder=""> </label> </ion-list> <div class="spacer" style="height: 40px;"></div> // login() function is called <button class="button button-stable button-block " ng-click="login()" >Log in</button> // a link to register page <a href="#/page5" class="button button-positive button-clear button-block ">Or create an account</a> </form> </ion-content> </ion-view> |
2 . js\controllers.js [ loginCtrl ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
.controller('loginCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) { $scope.user = {}; //declares the object user $scope.login = function() { str="http://www.website.com/foodcart/server_side/user-details.php?e="+$scope.user.email+"&p="+$scope.user.password; $http.get(str) .success(function (response){ // if login request is Accepted // records is the 'server response array' variable name. $scope.user_details = response.records; // copy response values to user-details object. //stores the data in the session. if the user is logged in, then there is no need to show login again. sessionStorage.setItem('loggedin_name', $scope.user_details.u_name); sessionStorage.setItem('loggedin_id', $scope.user_details.u_id ); sessionStorage.setItem('loggedin_phone', $scope.user_details.u_phone); sessionStorage.setItem('loggedin_address', $scope.user_details.u_address); sessionStorage.setItem('loggedin_pincode', $scope.user_details.u_pincode); // remove the instance of login page, when user moves to profile page. // if you dont use it, you can get to login page, even if you are already logged in . $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); //in my FoodKart App, it checks the page from where the user logs in. //if it is from the check out, then after login, the check out page will be shown. //else normal profile page will be shown lastView = $ionicHistory.backView(); if(lastView.stateId=="checkOut"){ $state.go('checkOut', {}, {location: "replace", reload: true}); } else{$state.go('profile', {}, {location: "replace", reload: true});} }).error(function() { //if login failed var alertPopup = $ionicPopup.alert({ title: 'Login failed!', template: 'Please check your credentials!' }); }); }; }) |
3 . js\routes.js [ ROUTING ]
You can also add extra checking to make sure that login page is not visible , after user logs in( even when back button is pressed .)
1 2 3 4 5 6 7 8 9 10 11 12 |
.state('login', { url: '/page4', templateUrl: 'templates/login.html', controller: 'loginCtrl', resolve:{ "check":function($location){ if(sessionStorage.getItem('loggedin_id')){ $location.path('/page9'); } else { $location.path('/page4'); } } } }) |
SIGN UP PAGE
1. templates\signup.html [ REGISTRATION PAGE]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<ion-view title="Signup"> <ion-content padding="'true'" scroll="false" class="has-header"> <form class="list"> <ion-list> <label class="item item-input"> <span class="input-label">Name</span> //Note: data object contains all the detials about the user registering. <input type="text" placeholder="" ng-model="data.name"> </label> <label class="item item-input"> <span class="input-label">Username</span> <input type="email" placeholder="" ng-model="data.username"> </label> <label class="item item-input"> <span class="input-label">Password</span> <input type="password" placeholder="" ng-model="data.password"> </label> <label class="item item-input"> <span class="input-label">Phone</span> <input type="number" placeholder="" ng-model="data.phone"> </label> </ion-list> <label class="item item-input"> <span class="input-label">Address</span> <input type="text" placeholder="" ng-model="data.address"> </label> <label class="item item-input"> <span class="input-label">Pincode</span> <input type="number" placeholder="" ng-model="data.pincode"> </label> //data object is passed to the signup() <button ng-click="signup(data)" class="button button-stable button-block ">Sign up</button> </form> </ion-content> </ion-view> |
2 . js\controllers.js [ signupCtrl]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
.controller('signupCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) { $scope.signup=function(data){ var link = 'http://www.website.com/foodcart/server_side/signup.php'; //using http post as we are passing password. $http.post(link, {n : data.name, un : data.username, ps : data.password , ph: data.phone , add : data.address , pin : data.pincode }) .then(function (res){ //if a response is recieved from the server. $scope.response = res.data.result; //contains Register Result //Shows the respective popup and removes back link if($scope.response.created=="1"){ $scope.title="Account Created!"; $scope.template="Your account has been successfully created!"; //no back option $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); // the user is redirected to login page after sign up $state.go('login', {}, {location: "replace", reload: true}); }else if($scope.response.exists=="1"){ $scope.title="Email Already exists"; $scope.template="Please click forgot password if necessary"; }else{ $scope.title="Failed"; $scope.template="Contact Our Technical Team"; } var alertPopup = $ionicPopup.alert({ title: $scope.title, template: $scope.template }); }); } }) |
PROFILE PAGE
1. templates\profile.html [ USER PROFILE PAGE]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<ion-view title="Profile"> <ion-content padding="'true'" class="has-header"> <ion-list> <ion-item class="item-divider">Detials</ion-item> <label class="item item-input"> <span class="input-label">Name</span> <textarea placeholder="" readonly> {{" "+loggedin_name}}</textarea> </label> <label class="item item-input"> <span class="input-label">Email</span> <textarea placeholder="" readonly>{{" "+loggedin_id}} </textarea> </label> <label class="item item-input"> <span class="input-label">Phone</span> <textarea placeholder="" readonly > {{" "+loggedin_phone}}</textarea> </label> <label class="item item-input"> <span class="input-label">Address</span> <textarea placeholder="" readonly > {{" "+loggedin_address}}</textarea> </label> <label class="item item-input"> <span class="input-label">Pincode</span> <textarea placeholder="" readonly > {{" "+loggedin_pincode}}</textarea> </label> <div class="button-bar"> <a href="#/page10" class="button button-stable button-block icon ion-android-alarm-clock"></a> <a href="#/page11" class="button button-stable button-block icon ion-edit"></a> <a href="#/page12" class="button button-stable button-block icon ion-android-favorite"></a> </div> <button ng-click="logout()" class="button button-balanced button-block icon-left ion-log-out">Logout</button> <a href="tel:+8877887788" class="button button-calm button-block icon-left ion-android-call">Call Us</a> </ion-list> </ion-content> </ion-view> |
2 . js\controllers.js [ profileCtrl ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
.controller('profileCtrl', function($scope,$rootScope,$ionicHistory,$state) { // loads value from the loggin session $scope.loggedin_name= sessionStorage.getItem('loggedin_name'); $scope.loggedin_id= sessionStorage.getItem('loggedin_id'); $scope.loggedin_phone= sessionStorage.getItem('loggedin_phone'); $scope.loggedin_address= sessionStorage.getItem('loggedin_address'); $scope.loggedin_pincode= sessionStorage.getItem('loggedin_pincode'); //logout function $scope.logout=function(){ //delete all the sessions delete sessionStorage.loggedin_name; delete sessionStorage.loggedin_id; delete sessionStorage.loggedin_phone; delete sessionStorage.loggedin_address; delete sessionStorage.loggedin_pincode; // remove the profile page backlink after logout. $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); // After logout you will be redirected to the menu page,with no backlink $state.go('menu', {}, {location: "replace", reload: true}); }; }) |
UPDATE: ( 31-07-2016)
Here is a video demo of setting up Ionic Cart!