Skip to content

Instantly share code, notes, and snippets.

@JosephScript
Created September 22, 2015 14:25
Show Gist options
  • Save JosephScript/b7a399c6faf02cbae387 to your computer and use it in GitHub Desktop.
Save JosephScript/b7a399c6faf02cbae387 to your computer and use it in GitHub Desktop.
This is an AngularJS authentication service for using JSON Web Tokens
app.service('authService', ['$window', function ($window) {
this.parseJwt = function (token) {
if (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse($window.atob(base64));
} else return {};
};
this.saveToken = function (token) {
$window.localStorage.jwtToken = token;
};
this.getToken = function () {
return $window.localStorage.jwtToken;
};
this.isAuthed = function () {
var token = this.getToken();
if (token) {
var params = this.parseJwt(token);
var notExpired = Math.round(new Date().getTime() / 1000) <= params.exp;
if (!notExpired) {
this.logout();
}
return notExpired;
} else {
return false;
}
};
this.logout = function () {
delete $window.localStorage.jwtToken;
};
// expose user as an object
this.getUser = function() {
return this.parseJwt(this.getToken())
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment