Friday 7 April 2017

Angular.js Authentication with Node.js

I'm unable to login with front-end might be problem with Angular-ui-Router. When I click on login button first I got an error as 'Possibly unhandled rejection' then I injected '$qProvider' in config file after adding $qProvider I don't see any error in console but the page is not changing it state whereas in the network tab i can see the Token is sent from the server. Can some one please help me.

App.config.js

angular.module('myApp', ['ui.router', 'myAppModel'])
        .config(function($qProvider, $stateProvider, $urlRouterProvider) {
            $urlRouterProvider.otherwise('/');
            $qProvider.errorOnUnhandledRejections(false);
            $stateProvider
                .state('base', {
                    abstract: true,
                    views: {
                        'nav@': {
                            template: '<navigation1></navigation1>'
                        }
                    }
                })
                .state('base.login', {
                    parent: 'base',
                    url: '/',
                    views: {
                        'main@': {
                            template: '<login></login>'
                        }
                    }
                })
                .state('base.register', {
                    parent: 'base',
                    url: '/register',
                    views: {
                        'main@': {
                            template: '<register></register>'
                        }
                    }
                })
                .state('base.dashboard', {
                    parent: 'base',
                    url: '/dashboard',
                    views: {
                        'main@': {
                            template: '<dashboard></dashboard>'
                        }
                    }
                })
        });

login.js

angular.module('myAppModel')
        .component('login', {
            templateUrl: '/components/login/login.html',
            controller: function loginCtrl(Authentication, $state) {
                var ctrl = this;

                ctrl.pageHeader = 'Login';

                ctrl.credentials = {
                    email: '',
                    password: '' 
                };

                ctrl.onSubmit = function () {
                    ctrl.formError = '';
                    if(!ctrl.credentials.email || !ctrl.credentials.password) {
                        ctrl.formError = 'All fields required, please try again';
                        return false;
                    }else {
                        ctrl.doLogin();
                    }
                };

                ctrl.doLogin = function () {
                    ctrl.formError = '';
                    Authentication.login(ctrl.credentials).then(function(status) {
                        console.log(status);
                        $state.go('base.dashboard');
                    });
                };

            }
        });

Authentication-service.js

angular.module('myAppModel')
        .service('Authentication', function ($window, $http) { //Register new service with application and inject $window service
            var saveToken = function (token) {  //create a saveToken method to save a value to localStorage
                $window.localStorage['app-token'] = token;
            };

            var getToken = function () {    //Create a getToken method to read a value from localStorage
                return $window.localStorage['app-token'];
            }

            var register = function (user) {
                return $http.post('/api/users/register', user).then(function(data){
                    saveToken(data.token);
                });
            };

            var login = function (user) {
                return $http.post('/api/users/login', user).then(function (data) {
                    saveToken(data.token);
                });
            };

            var logout = function () {
                $window.localStorage.removeItem('app-token');
            };

            var isLoggedIn = function () {
                var token = getToken(); //Get token from storage

                if(token) { //If token exists get payload decode it, and parse it to JSON
                    var payload = JSON.parse($window.atob(token.split('.')[1]));
                    return payload.exp > Date.now() / 1000; //validate whether expiry date has passed
                }else {
                    return false;
                }
            };

            //Getting User Information from the JWT
            var currentUser = function () {
                if (isLoggedIn()) {
                    var token = getToken();
                    var payload = JSON.parse($window.atob(token.split('.')[1]));
                    return {
                        email: payload.email,
                        name: payload.name
                    };
                }
            };

            return {
                saveToken: saveToken,   //Expose methods to application
                getToken: getToken,
                register: register,
                login: login,
                logout: logout,
                isLoggedIn: isLoggedIn,
                currentUser: currentUser
            };

        });



via Arjun

No comments:

Post a Comment