Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Handle User Sign-In With Ionic Framework

TwitterFacebookRedditLinkedInHacker News

When making an API app or any app that requires authentication it is critical to have a solid sign-in process. A good way to handle user sign-in with Ionic Framework is to make use of the already included ui-router module. The idea behind this is to route between sign in and protected screens as necessary.

In the config area of your AngularJS file, we are going to create very simple routes. So simple, that it will only be two routes. One will be a sign in screen and the other will be a protected screen. By default, the Ionic application will try to route to the protected page. The authentication magic will happen in the controllers of the sign in screen and the protected screen.

var testApp = angular.module('test', ['ionic'])
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: 'templates/login.html',
                controller: 'LoginController'
            })
            .state('protected', {
                url: '/protected',
                templateUrl: 'templates/protected.html',
                controller: 'ProtectedController'
            });
        $urlRouterProvider.otherwise('/protected');
    });

In the controller that manages our protected view, the first thing we do is check to see if we are signed in. Since our sign in system is not complex, we are only checking to see if password is set in local storage. No logic is done to validate whether passwords are correct. If the password is not set, the $ionicViewService will clear the navigation stack and then redirect to the sign in view. The reason we clear the navigation stack is because we don’t want Android users to hit the back button and end up back in the protected view / controller. This is a non-issue for iOS users because there is no back button. When the navigation stack is cleared, the back button will simply exit the application. Note that PC web browser back buttons will still go back regardless if the navigation stack is cleared. If the local storage is set, simply return a scope variable that says so.

testApp.controller("ProtectedController", function($scope, $location, $ionicViewService) {
    if(window.localStorage.getItem("password") === "undefined" || window.localStorage.getItem("password") === null) {
        $ionicViewService.nextViewOptions({
            disableAnimate: true,
            disableBack: true
        });
        $location.path("/login");
    }
    $scope.status = "Making it this far means you are signed in";
}

In the sign in view we accept a password via a text input field. As you can see in the snippet below, there is nothing complex about it.

<ion-view title="Login">
    <ion-content>
        <div ng-controller="LoginController">
            <div class="list list-inset">
                <label class="item item-input">
                    <input ng-model="password" type="text" placeholder="Password" />
                </label>
            </div>
            <div class="padding">
                <button ng-click="login(password)" class="button button-block button-balanced">
                    Sign In
                </button>
            </div>
        </div>
    </ion-content>
</ion-view>

When the sign in button is pressed, the login() function is called in our LoginController. Again, since this is a simplistic example, no sign in logic will be done. All that happens is the local storage for password is set and then we are redirected to the protected view. Like in our protected view code, we also include an $ionicViewService to prevent use of the Android back button by clearing the navigation stack. We did this so the back button won’t take us back to the sign in screen when already logged in. Instead it will just exit the application.

testApp.controller('LoginController', function($scope, $location, $ionicViewService) {
    $scope.login = function(password) {
        window.localStorage.setItem("password", password);
        $ionicViewService.nextViewOptions({
            disableAnimate: true,
            disableBack: true
        });
        $location.path("/protected");
    }
});

By handling sign in like this, your users will have a smooth experience and shouldn’t notice the transition between screens. It is however, up to you to create a more complex system for rejecting and creating passwords.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.