Login with ionic framework

Just want to share some piece of code. Today we are going to talk about log in in ionic framework.

ionic

Let’s go !

We have LoginCtrl, AppAuth – simple service to make log in call. I have $resources for all API models. AppAuth – this service will store user token and will be responsible for signs in requests. CurrentUser – service that we will use in other controllers to get current user info.


(function () {
    'use strict';

    angular
        .module('app.login.controller', [])
        .controller('LoginCtrl', LoginCtrl)
        .run(function (routerHelper) {
            routerHelper.configureStates(getStates());
        });

    /* @ngInject */
    function LoginCtrl($scope, LoginService, CurrentUser, $state, $ionicLoading, $ionicPlatform) {

        $ionicPlatform.ready(function () {
            // This does not disable scrolling in the Ionic scroll view, rather it disables the native
            // overflow scrolling that happens automatically as a result of focusing on inputs below the keyboard.
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.disableScroll(true);
            }
        });

        // if use is loged in then go to home
        if (!CurrentUser.isGuest()) {
            $state.go('home');
            return;
        }

        /**
         * If click back still need to redirect to bulletin
         */
        $scope.$on('$ionicView.enter', function() {
            if (!CurrentUser.isGuest()) {
                $state.go('home');
                return;
            }
        });

        var vm = this;
        $scope.$on('event:auth-login-confirmed', function (e, userData) {
            CurrentUser.setId(userData.id);
            $ionicLoading.hide();
            $state.go('home');
        });

        $scope.$on('event:auth-login-failed', function (e, status) {
            $ionicLoading.hide();
            $scope.error = "Please check your credentials!";
            if (status == 401) {
                $scope.error = "Invalid Username or Password.";
            }
        });


        vm.user = {
            username: null,
            password: null
        };

        vm.login = function () {
            $ionicLoading.show({
                template: 'Log in'
            });
            LoginService.login(vm.user);
            if (typeof cordova !== 'undefined') {
                cordova.plugins.Keyboard.close();
            }
        };
    }

    function getStates() {
        return [
            {
                state: 'login',
                config: {
                    url: '/login',
                    templateUrl: 'login/login.html',
                    controller: 'LoginCtrl as loginCtrl'
                }
            }
        ];
    }

})();


(function () {

    'use strict';

    angular
        .module('app.login.service', [])
        .service('LoginService', LoginService);

    /* @ngInject */
    function LoginService($http, AppAuth, AppConfig) {
        return {
            login: function (user) {
                $http.post(AppConfig.BASE_API_URL + '/user/login', user, {ignoreAuthModule: true})
                    .success(function (data, status, headers, config) {
                        if (typeof data.error === 'undefined' && typeof data.auth_key !== 'undefined') {
                            AppAuth.loginConfirmed(data, data.auth_key);
                        } else {
                            AppAuth.loginFailed(data);
                        }

                    })
                    .error(function (data, status, headers, config) {
                        AppAuth.loginFailed(data);
                    });
            }
        };
    }
})();


(function () {
    'use strict';

    angular.module('app.auth', [])
        .factory('AppAuth', AppAuth)
        .config(configHttpProvider);


    /**
     * Store auth token to device
     * @param token
     * @param userData
     */
    function storeAuthData(token, userId) {
        window.localStorage.setItem('authToken', token);
        window.localStorage.setItem('currentUserId', userId);
    }

    /**
     * Return saved auth token
     * @returns {*}
     */
    function getAuthToken() {
        return window.localStorage.getItem('authToken');
    }

    /**
     * Return saved user id auth token
     * @returns {*}
     */
    function getCurrentUserId() {
        return window.localStorage.getItem('currentUserId');
    }

    /**
     * Destroy user credentials
     */
    function destroyUserCredentials() {
        window.localStorage.removeItem('authToken');
        window.localStorage.removeItem('currentUserId');
    }

    /* @ngInject */
    function AppAuth($rootScope, $timeout, $ionicHistory) {
        return {
            /**
             * Call this function to indicate that authentication was successful.
             * @param userData
             * @token auth token
             */
            loginConfirmed: function (userData, token) {
                storeAuthData(token, userData.id);
                $rootScope.$broadcast('event:auth-login-confirmed', userData);
            },

            /**
             * Call this function to indicate that authentication was unsuccessful
             * @param data
             */
            loginFailed: function (data) {
                $rootScope.$broadcast('event:auth-login-failed', data);
            },

            /**
             * Return current user ID
             * @returns {*}
             */
            getCurrentUserId: function () {
                return getCurrentUserId();
            },

            /**
             * Logout user
             * @param data
             */
            logout: function () {
                destroyUserCredentials();
                $rootScope.$broadcast('event:auth-logout');
                $timeout(function () {
                    $ionicHistory.clearCache();
                    $ionicHistory.clearHistory();
                }, 1500)
            },

            /**
             * Add authorization header. Use this functions for low level $http calls
             * @param headers
             * @returns {*}
             */
            addAuthHeader: function (headers) {
                var authToken = getAuthToken();
                if (authToken) {
                    headers.Authorization = 'Bearer ' + authToken;
                }
                return headers;
            }
        };
    }


    /* @ngInject */
    function configHttpProvider($httpProvider) {
        $httpProvider.interceptors.push(['$rootScope', '$q', function ($rootScope, $q) {
            return {
                request: function (config) {
                    config.headers = config.headers || {};
                    var authToken = getAuthToken();
                    if (authToken) {
                        config.headers.Authorization = 'Bearer ' + authToken;
                    }
                    return config;
                },
                responseError: function (rejection) {
                    if (!rejection.config.ignoreAuthModule) {
                        switch (rejection.status) {
                            case 401:
                                var deferred = $q.defer();
                                $rootScope.$broadcast('event:auth-login-required', rejection);
                                return deferred.promise;
                            case 403:
                                $rootScope.$broadcast('event:auth-forbidden', rejection);
                                break;
                        }
                    }
                    // otherwise, default behaviour
                    return $q.reject(rejection);
                }
            };
        }]);
    }

})();

/**
 * App Auth module
 */
(function () {
    'use strict';

    angular.module('app.current_user', [])
        .service('CurrentUser', CurrentUser)
        .run(configRootScope);

    var currentUserId;
    var currentUser = {};

    /* @ngInject */
    function CurrentUser(AppAuth, UsersApi, ProfilesApi, $q, $rootScope) {

        currentUserId = AppAuth.getCurrentUserId();

        var deferredUser;

        return {
            get id() {
                return this.getId();
            },

            /**
             * Send current user ID
             */
            setId: function(id) {
                currentUserId = id;
            },

            /**
             * Set user data after update
             * @param data
             */
            setUserData: function(data) {
                currentUser = data;
                $rootScope.$broadcast('account-updated', currentUser);
            },
          
            /**
             * Logout current user
             */
            logout: function() {
                currentUserId = null;
                currentUser = {};
                deferredUser = undefined;
                $rootScope.$broadcast('account-updated', undefined);
            },

            /**
             * Check is current user is guest
             */
            isGuest: function() {
                return currentUserId === null;
            },
            /**
             * Return current user ID
             * @returns {*}
             */
            getId: function() {
                if (this.isGuest()) {
                    return null;
                }
                return currentUserId;
            },
            /**
             * Returns promise that will return user data
             * @returns {promise|*|qFactory.Deferred.promise|fd.g.promise}
             */
            getUserData: function() {
                if (deferredUser) {
                    return deferredUser.promise;
                }

                deferredUser = $q.defer();
                if (this.isGuest()) {
                    deferredUser.reject({});
                } else {
                    UsersApi.get({id: currentUserId}, function(data) {
                        currentUser = data;
                        deferredUser.resolve(data);
                    });
                }

                return deferredUser.promise;
            },           
        };
    }

    /**
     * Config root scope, load currently logged in user
     * @param $rootScope
     */
    function configRootScope($rootScope) {
        $rootScope.$on('event:auth-login-confirmed', function(e, userData) {
            currentUser = userData;
        });
    }

})();

Leave a Reply

Your email address will not be published. Required fields are marked *