Login based application with ionic framework – Part 1
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.
Install ionic
npm install -g cordova ionic
Create a project with readily available templates from ionic. Use sidemenu template in our case.
ionic start login sidemenu
Now, go to your login/www folder and open index.html in browser to see the default application with sidemenu as shown below.
If 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.
You 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.
We 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.
So first, open templates/login.html and remove <ion-modal-view>
wrapper and close button. Your login.html should look like below.
Login
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.
Open js/app.js, inside config function add below state to $stateProvider
.
.state('login', { url: "/login", templateUrl: "templates/login.html", controller: 'AppCtrl' })
Also set login state as a fallback state if noe of the state matches by amodifying $urlProvider like below,
$urlRouterProvider.otherwise('/login');
Now open your index.html, it will show you the login page at beginning.
Our next step is to create a service to store the user info, logged in state in cookies and retrieve it for further process.
Create a file js/services.js and copy paste the below code.
angular.module('starter.services', ['ngCookies']) .factory('Auth', function ($cookieStore) { var _user = $cookieStore.get('starter.user'); var setUser = function (user) { _user = user; $cookieStore.put('starter.user', _user); } return { setUser: setUser, isLoggedIn: function () { return _user ? true : false; }, getUser: function () { return _user; }, logout: function () { $cookieStore.remove('starter.user'); _user = null; } } });
Include this service file and in your index.html. Also inject the service in your module inside js/app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
Let us update the controller to save the user detail in cookies and redirect to playlist page upon successfull login.
$scope.doLogin = function() { if(!angular.isDefined($scope.loginData.username) || !angular.isDefined($scope.loginData.password) || $scope.loginData.username.trim() == "" || $scope.loginData.password.trim() == ""){ alert("Enter both user name and password"); return; } Auth.setUser({ username: $scope.loginData.username }); $state.go("app.playlists"); };
Open templates/menu.html and remove login item from the menu and add logout item. Your menu.html should look like this,
Starter
Search Browse Playlists Logout
Add a function for logout in your AppCtrl(application controller), reset coockies by calling Auth.logout() method of Auth Service and redirect to login.
$scope.logout = function() { Auth.logout(); $state.go("login"); };
Your final js/controllers.js file should be looking like the below,
angular.module('starter.controllers', []) .controller('AppCtrl', function($scope, $state, Auth) { // Form data for the login modal $scope.loginData = {}; $scope.logout = function() { Auth.logout(); $state.go("login"); }; // Perform the login action when the user submits the login form $scope.doLogin = function() { if(!angular.isDefined($scope.loginData.username) || !angular.isDefined($scope.loginData.password) || $scope.loginData.username.trim() == "" || $scope.loginData.password.trim() == ""){ alert("Enter both user name and password"); return; } Auth.setUser({ username: $scope.loginData.username }); $state.go("app.playlists"); }; }) .controller('PlaylistsCtrl', function($scope) { $scope.playlists = [ { title: 'Reggae', id: 1 }, { title: 'Chill', id: 2 }, { title: 'Dubstep', id: 3 }, { title: 'Indie', id: 4 }, { title: 'Rap', id: 5 }, { title: 'Cowbell', id: 6 } ]; }) .controller('PlaylistCtrl', function($scope, $stateParams) { });
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.
.state('app', { url: "/app", abstract: true, templateUrl: "templates/menu.html", controller: 'AppCtrl', onEnter: function($state, Auth){ if(!Auth.isLoggedIn()){ $state.go('login'); } } });
Yeah, we are done with the application with mandatory login authentication in ionic.
You can get the source code of this tutorial in this link login_part1
You can get the source code from github. Replace your code inside www with this code in your cordova application to see it in action.
We will see how to connect to websql database in part2 coming soon…
hi, I really need help for this one, how i can define username and password like user=”admin” and password=”12345″, please help me
Hi Gonaçlo,
Replace $scope.doLogin method with the below code,
$scope.doLogin = function() {
if(!angular.isDefined($scope.loginData.username) || !angular.isDefined($scope.loginData.password) || $scope.loginData.username.trim() == “” || $scope.loginData.password.trim() == “”){
alert(“Enter both user name and password”);
return;
}else if($scope.loginData.username.trim() == “admin” && $scope.loginData.password.trim() == “12345”){
Auth.setUser({
username: $scope.loginData.username
});
$state.go(“app.playlists”);
}
};
Pls upload part 2….
Working on it. Will be out soon..
Please, upload part 2 🙁 i’m going frustate.
Thank you subash. i am new to ionic frmwrk. i have tried so many examples and sites, nothing helped me , except yours. hoping you will be uploading new apps and part2.
hii,
I’m new to ionic I want to make an app were user will login and my user data is in pouchdb how this can be done can you help me
Hi Harsh,
I am working on the part2 which deals with pouchdb to store and retrieve user info in websql. Will be releasing it this week.