{"id":82,"date":"2015-02-15T23:11:35","date_gmt":"2015-02-15T17:41:35","guid":{"rendered":"http:\/\/subashselvaraj.com\/?p=82"},"modified":"2025-06-21T18:57:15","modified_gmt":"2025-06-21T18:57:15","slug":"login-based-application-with-ionic-framework-connect-to-websql-part1","status":"publish","type":"post","link":"https:\/\/subashselvaraj.com\/index.php\/2015\/02\/15\/login-based-application-with-ionic-framework-connect-to-websql-part1\/","title":{"rendered":"Login based application with ionic framework &#8211; Part 1"},"content":{"rendered":"<p>It is obvious case that you need to have login as a beginning of your app. We will learn how to create login based application with ionic in this tutorial.<br \/>\nInstall ionic<br \/>\n<code>npm install -g cordova ionic<\/code><br \/>\nCreate a project with readily available templates from ionic. Use sidemenu template in our case.<br \/>\n<code>ionic start login sidemenu<\/code><br \/>\nNow, go to your login\/www folder and open index.html in browser to see the default application with sidemenu as shown below.<a href=\"http:\/\/subashselvaraj.com\/wp-content\/uploads\/2015\/02\/home_default.jpg\"><img decoding=\"async\" loading=\"lazy\" src=\"http:\/\/subashselvaraj.com\/wp-content\/uploads\/2015\/02\/home_default-168x300.jpg\" alt=\"home_default\" width=\"168\" height=\"300\" class=\"alignnone size-medium wp-image-74\"><\/a><a href=\"http:\/\/subashselvaraj.com\/wp-content\/uploads\/2015\/02\/sidemenu_default.jpg\"><img decoding=\"async\" loading=\"lazy\" src=\"http:\/\/subashselvaraj.com\/wp-content\/uploads\/2015\/02\/sidemenu_default-170x300.jpg\" alt=\"sidemenu_default\" width=\"170\" height=\"300\" class=\"alignnone size-medium wp-image-75\"><\/a><br \/>\nIf you notice your browser console you will see the 404 error of cordova.js, but dont worry on that since cordova will inculde it at the time of creating build for mobile platforms.<br \/>\nYou can find the navigation items including login in the side menu. It will open login form in a modal if you click on login. You can see all the navigation items and side menu prior login in this default template.<br \/>\nWe are going to modify this application as login based application wherein login page comes first and post login user can see the side menu and other navigation items.<br \/>\nSo first, open templates\/login.html and remove <code>&lt;ion-modal-view&gt;<\/code> wrapper and close button. Your login.html should look like below.<\/p>\n<pre class=\"brush:html\">  <ion-header-bar>\n\n<h1 class=\"title\">Login<\/h1>\n\n  <\/ion-header-bar>\n  <ion-content>\n    <form ng-submit=\"doLogin()\">\n\n<div class=\"list\">\n        <label class=\"item item-input\">\n          <span class=\"input-label\">Username<\/span>\n          <input type=\"text\" ng-model=\"loginData.username\">\n        <\/label>\n        <label class=\"item item-input\">\n          <span class=\"input-label\">Password<\/span>\n          <input type=\"password\" ng-model=\"loginData.password\">\n        <\/label>\n        <label class=\"item\">\n          <button class=\"button button-block button-positive\" type=\"submit\">Log in<\/button>\n        <\/label>\n<\/div>\n\n    <\/form>\n  <\/ion-content>\n<\/pre>\n<p>We are ready with login page template, now we need to modify the router to show login page at the beginning instead of playlist screen.<br \/>\nOpen js\/app.js, inside config function add below state to <code>$stateProvider<\/code>.<\/p>\n<pre class=\"brush:js\">.state('login', {\n    url: \"\/login\",\n    templateUrl: \"templates\/login.html\",\n    controller: 'AppCtrl'\n  })\n<\/pre>\n<p>Also set login state as a fallback state if noe of the state matches by amodifying $urlProvider like below,<\/p>\n<pre class=\"brush:js\"> $urlRouterProvider.otherwise('\/login');<\/pre>\n<p>Now open your index.html, it will show you the login page at beginning.<br \/>\nOur next step is to create a service to store the user info, logged in state in cookies and retrieve it for further process.<br \/>\nCreate a file js\/services.js and copy paste the below code.<\/p>\n<pre class=\"brush:js\">angular.module('starter.services', ['ngCookies'])\n.factory('Auth', function ($cookieStore) {\n   var _user = $cookieStore.get('starter.user');\n   var setUser = function (user) {\n      _user = user;\n      $cookieStore.put('starter.user', _user);\n   }\n\n   return {\n      setUser: setUser,\n      isLoggedIn: function () {\n         return _user ? true : false;\n      },\n      getUser: function () {\n         return _user;\n      },\n      logout: function () {\n         $cookieStore.remove('starter.user');\n         _user = null;\n      }\n   }\n});<\/pre>\n<p>Include this service file and  <code><script src=\"https:\/\/code.angularjs.org\/1.4.0-beta.4\/angular-cookies.min.js\"><\/script><\/code> in your index.html. Also inject the service in your module inside js\/app.js<\/p>\n<pre class=\"brush:js\">angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])<\/pre>\n<p>Let us update the controller to save the user detail in cookies and redirect to playlist page upon successfull login.<\/p>\n<pre class=\"brush:js\">$scope.doLogin = function() {\n\n    if(!angular.isDefined($scope.loginData.username) || !angular.isDefined($scope.loginData.password) || $scope.loginData.username.trim() == \"\" || $scope.loginData.password.trim() == \"\"){\n       alert(\"Enter both user name and password\");\n       return;\n    }  \n      \n    Auth.setUser({\n      username: $scope.loginData.username\n    });\n\n    $state.go(\"app.playlists\");\n    \n  };\n<\/pre>\n<p>Open templates\/menu.html and remove login item from the menu and add logout item. Your menu.html should look like this,<\/p>\n<pre class=\"brush:html\"><ion-side-menus enable-menu-with-back-views=\"false\">\n  <ion-side-menu-content>\n    <ion-nav-bar class=\"bar-stable\">\n      <ion-nav-back-button>\n      <\/ion-nav-back-button>\n\n      <ion-nav-buttons side=\"left\">\n        <button class=\"button button-icon button-clear ion-navicon\" menu-toggle=\"left\">\n        <\/button>\n      <\/ion-nav-buttons>\n    <\/ion-nav-bar>\n    <ion-nav-view name=\"menuContent\"><\/ion-nav-view>\n  <\/ion-side-menu-content>\n\n  <ion-side-menu side=\"left\">\n    <ion-header-bar class=\"bar-stable\">\n\n<h1 class=\"title\">Starter<\/h1>\n\n    <\/ion-header-bar>\n    <ion-content>\n      <ion-list>        \n        <ion-item nav-clear=\"\" menu-close=\"\" href=\"#\/app\/search\">\n          Search\n        <\/ion-item>\n        <ion-item nav-clear=\"\" menu-close=\"\" href=\"#\/app\/browse\">\n          Browse\n        <\/ion-item>\n        <ion-item nav-clear=\"\" menu-close=\"\" href=\"#\/app\/playlists\">\n          Playlists\n        <\/ion-item>\n        <ion-item nav-clear=\"\" menu-close=\"\" ng-click=\"logout()\">\n          Logout\n        <\/ion-item>\n      <\/ion-list>\n    <\/ion-content>\n  <\/ion-side-menu>\n<\/ion-side-menus>\n<\/pre>\n<p>Add a function for logout in your AppCtrl(application controller), reset coockies by calling Auth.logout() method of Auth Service and redirect to login.<\/p>\n<pre class=\"brush:js\">  $scope.logout = function() {\n    Auth.logout();\n    $state.go(\"login\");\n  };\n<\/pre>\n<p>Your final js\/controllers.js file should be looking like the below,<\/p>\n<pre class=\"brush:js\">angular.module('starter.controllers', [])\n\n.controller('AppCtrl', function($scope, $state, Auth) {\n  \/\/ Form data for the login modal\n  $scope.loginData = {};  \n\n  $scope.logout = function() {\n    Auth.logout();\n    $state.go(\"login\");\n  };\n\n\n   \/\/ Perform the login action when the user submits the login form\n  $scope.doLogin = function() {\n\n    if(!angular.isDefined($scope.loginData.username) || !angular.isDefined($scope.loginData.password) || $scope.loginData.username.trim() == \"\" || $scope.loginData.password.trim() == \"\"){\n       alert(\"Enter both user name and password\");\n       return;\n    }  \n\n    Auth.setUser({\n      username: $scope.loginData.username\n    });\n\n    $state.go(\"app.playlists\");\n    \n  };\n\n})\n\n.controller('PlaylistsCtrl', function($scope) {\n  $scope.playlists = [\n    { title: 'Reggae', id: 1 },\n    { title: 'Chill', id: 2 },\n    { title: 'Dubstep', id: 3 },\n    { title: 'Indie', id: 4 },\n    { title: 'Rap', id: 5 },\n    { title: 'Cowbell', id: 6 }\n  ];\n})\n\n.controller('PlaylistCtrl', function($scope, $stateParams) {\n});\n<\/pre>\n<p>Now our application can handle login\/logout operations. But we need to handle the use case that if the user presses back button (in android) or swipes back the browser (in ios) after logout, application should not go to the inner pages. We can handle this in router inside onEnter callback of the states to which we need user login. We need to identify whether the user has been logged-in, using Auth.isLoggedIn() method of the serice we have created, if not redirect to login page.<\/p>\n<pre class=\"brush:js\">.state('app', {\n    url: \"\/app\",\n    abstract: true,\n    templateUrl: \"templates\/menu.html\",\n    controller: 'AppCtrl',\n    onEnter: function($state, Auth){\n        if(!Auth.isLoggedIn()){\n           $state.go('login');\n        }\n    }\n  });\n<\/pre>\n<p>Yeah, we are done with the application with mandatory login authentication in ionic.<\/p>\n<p>You can get the source code of this tutorial in this link <a href=\"http:\/\/subashselvaraj.com\/wp-content\/uploads\/2015\/02\/login_part1.zip\" title=\"login_part1\" target=\"_blank\" rel=\"noopener\">login_part1<\/a><br \/>\nYou can get the source code from <a href=\"https:\/\/github.com\/sesubash\/ionic-login-part1\" title=\"github\" target=\"_blank\" rel=\"noopener\">github<\/a>. Replace your code inside www with this code in your cordova application to see it in action.<br \/>\nWe will see how to connect to websql database in part2 coming soon&#8230;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It is obvious case that you need to have login as a beginning of your app. We will learn how to create login based application with ionic&#8230; <\/p>\n","protected":false},"author":1,"featured_media":227,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_mi_skip_tracking":false,"_themeisle_gutenberg_block_has_review":false},"categories":[8,19,20,4],"tags":[21],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/posts\/82"}],"collection":[{"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/comments?post=82"}],"version-history":[{"count":3,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/posts\/82\/revisions"}],"predecessor-version":[{"id":228,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/posts\/82\/revisions\/228"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/media\/227"}],"wp:attachment":[{"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/media?parent=82"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/categories?post=82"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/subashselvaraj.com\/index.php\/wp-json\/wp\/v2\/tags?post=82"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}