Simple AngularJS Authentication with JWT

Are we Authenticated?

Build out methods for an authentication service to determine and manage authentication state

Let's add a method that will check for the existence of a valid token and return true or false respectively. This method can be used throughout an application to show/hide elements or allow/disallow certain actions.

Add the isAuthed() method:
self.isAuthed = function() {
  var token = self.getToken();
  if(token) {
    var params = self.parseJwt(token);
    return Math.round(new Date().getTime() / 1000) <= params.exp;
  } else {
    return false;

Remember that Unix Time is in seconds while JavaScript returns milliseconds, so a conversion is necessary.

Logging Out

We'll round off the auth service with a way to log a user out. Since the presence of a valid JWT in localStorage is all that separates an authenticated user from an unathenticated user, logging out is simply a matter of deleting the token.

Add a final method to the auth service to delete the stored JWT:
self.logout = function() {