Mikyas TADESSE Mikyas TADESSE - 8 days ago 4
Javascript Question

How to get username of currenlty logged on user authservice

I would like to get the currently loged in username so i can display it. But i dont know how to do it ? Any ideas ? I am using authservice Here is my angular controller in which i would like to get the username.

myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []

Meetup.query(function (results) {
$scope.meetups = results;
});


$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);


my main angular controller code
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);

myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});

myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});







myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []

Meetup.query(function (results) {
$scope.meetups = results;
});


$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}





}]);


my second angular code :

var app = angular.module('myApp');

app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {

$scope.login = function () {

// initial values
$scope.error = false;
$scope.disabled = true;

// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});

};

$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};

$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
}]);

app.controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {

$scope.logout = function () {

// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});

};

$scope.gotoregister = function () {




$location.path('/register');


};
$scope.gotoprive = function () {




$location.path('/prive');


};

}]);

app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {

$scope.register = function () {

// initial values
$scope.error = false;
$scope.disabled = true;

// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});

};

}]);


and my services

angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http) {

// create user variable
var user = null;

// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register
});

function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}

function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}

function login(username, password) {

// create a new instance of deferred
var deferred = $q.defer();

// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});

// return promise object
return deferred.promise;

}

function logout() {

// create a new instance of deferred
var deferred = $q.defer();

// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});

// return promise object
return deferred.promise;

}

function register(username, password) {

// create a new instance of deferred
var deferred = $q.defer();

// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});

// return promise object
return deferred.promise;

}

}]);

Answer

So this should probably work, maybe you will need to make some small adjustments because i don't know how exactly is your app structured, but this will work.

First you need to change your AuthService to look like this

angular.module('myApp').factory('AuthService',
  ['$q', '$timeout', '$http',
  function ($q, $timeout, $http, $cookies) {

    // create user variable
    var user = null;

    // we must create authMemberDefer var so we can get promise anywhere in app
    var authenticatedMemberDefer = $q.defer();

    // return available functions for use in the controllers
    return ({
      isLoggedIn: isLoggedIn,
      getUserStatus: getUserStatus,
      login: login,
      logout: logout,
      register: register,
      getAuthMember: getAuthMember,
      setAuthMember: setAuthMember
    });

    function isLoggedIn() {
      if(user) {
        return true;
      } else {
        return false;
      }
    }
    //this is function that we will call each time when we need auth member data
    function getAuthMember() {
        return authenticatedMemberDefer.promise;
    }
    //this is setter function to set member from coockie that we create on login
    function setAuthMember(member) {
        authenticatedMemberDefer.resolve(member);
    }

    function getUserStatus() {
      return $http.get('/user/status')
      // handle success
      .success(function (data) {
        if(data.status){
          user = true;
        } else {
          user = false;
        }
      })
      // handle error
      .error(function (data) {
        user = false;
      });
    }

    function login(username, password) {

      // create a new instance of deferred
      var deferred = $q.defer();

      // send a post request to the server
      $http.post('/user/login',
        {username: username, password: password})
        // handle success
        .success(function (data, status) {
          if(status === 200 && data.status){
            user = true;
            deferred.resolve();

            //**
            $cookies.putObject('loginSession', data);
            // here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there


          } else {
            user = false;
            deferred.reject();
          }
        })
        // handle error
        .error(function (data) {
          user = false;
          deferred.reject();
        });

      // return promise object
      return deferred.promise;

    }

    function logout() {

      // create a new instance of deferred
      var deferred = $q.defer();

      // send a get request to the server
      $http.get('/user/logout')
        // handle success
        .success(function (data) {
          user = false;
          deferred.resolve();
          //on log out remove coockie
          $cookies.remove('loginSession');

        })
        // handle error
        .error(function (data) {
          user = false;
          deferred.reject();
        });

      // return promise object
      return deferred.promise;

    }

    function register(username, password) {

      // create a new instance of deferred
      var deferred = $q.defer();

      // send a post request to the server
      $http.post('/user/register',
        {username: username, password: password})
        // handle success
        .success(function (data, status) {
          if(status === 200 && data.status){
            deferred.resolve();
          } else {
            deferred.reject();
          }
        })
        // handle error
        .error(function (data) {
          deferred.reject();
        });

      // return promise object
      return deferred.promise;

    }

}]);

after that changes in authService, you must make this on your app run, so each time application run (refresh) it first check coockie to see if there is active session(member) and if there is it will set it inside our AuthService.

myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
    $rootScope.$on('$routeChangeStart',
        function(event, next, current) {
            if ($cookies.get('loginSession')) {
                var session = JSON.parse($cookies.get('loginSession'));
                AuthService.setAuthMember(session);
            } else {
                $location.path('/login');
            }
        });
});

And simply anywhere where you want to get auth member you have to do this, first include in your controller/directive AuthService and do this

AuthService.getAuthMember().then(function(member){
 console.log(member);
 //here your member should be and you can apply any logic or use that data where     u want
});

I hope this helps you, if you find any difficulties i'm happy to help

Comments