Last active
April 12, 2017 05:59
-
-
Save teknosains/64cfa82a3beb5d6cf2818aa662d9480e to your computer and use it in GitHub Desktop.
JWT Helper, angular Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//JWT Helper.. | |
.service('jwtHelper', function() { | |
this.urlBase64Decode = function(str) { | |
var output = str.replace(/-/g, '+').replace(/_/g, '/'); | |
switch (output.length % 4) { | |
case 0: { break; } | |
case 2: { output += '=='; break; } | |
case 3: { output += '='; break; } | |
default: { | |
throw 'Illegal base64url string!'; | |
} | |
} | |
return decodeURIComponent(escape(window.atob(output))); //polifyll https://github.com/davidchambers/Base64.js | |
} | |
this.decodeToken = function(token) { | |
if (!token) { | |
return {}; | |
} else { | |
var parts = token.split('.'); | |
if (parts.length !== 3) { | |
throw new Error('JWT must have 3 parts'); | |
} | |
var decoded = this.urlBase64Decode(parts[1]); | |
if (!decoded) { | |
throw new Error('Cannot decode the token'); | |
} | |
return JSON.parse(decoded); | |
} | |
} | |
this.getTokenExpirationDate = function(token) { | |
var decoded; | |
decoded = this.decodeToken(token); | |
if(!decoded.exp) { | |
return null; | |
} | |
var d = new Date(0); // The 0 here is the key, which sets the date to the epoch | |
d.setUTCSeconds(decoded.exp); | |
return d; | |
}; | |
this.isTokenExpired = function(token, offsetSeconds) { | |
var d = this.getTokenExpirationDate(token); | |
offsetSeconds = offsetSeconds || 0; | |
if (!d) { | |
return false; | |
} | |
// Token expired? | |
return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000))); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment