Skip to content

Instantly share code, notes, and snippets.

@Subtletree
Last active November 22, 2016 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Subtletree/e3ae75f0d378732d4aa626d0aeea6da9 to your computer and use it in GitHub Desktop.
Save Subtletree/e3ae75f0d378732d4aa626d0aeea6da9 to your computer and use it in GitHub Desktop.
import Ember from 'ember';
import Jwt from 'ember-simple-auth-token/authenticators/jwt';
export default Jwt.extend({
scheduleAccessTokenRefresh(expiresAt, token) {
if (this.refreshAccessTokens) {
expiresAt = this.resolveTime(expiresAt);
const now = this.getCurrentTime();
const wait = (expiresAt - now - this.refreshLeeway) * 1000; // 1000*whole equation, not just leeway
if (!Ember.isEmpty(token) && !Ember.isEmpty(expiresAt) && wait > 0) {
Ember.run.cancel(this._refreshTokenTimeout);
delete this._refreshTokenTimeout;
this._refreshTokenTimeout = Ember.run.later(this, this.refreshAccessToken, token, wait);
}
}
},
restore(data) {
const dataObject = Ember.Object.create(data);
return new Ember.RSVP.Promise((resolve, reject) => {
const now = this.getCurrentTime();
const token = dataObject.get(this.tokenPropertyName);
let expiresAt = this.resolveTime(dataObject.get(this.tokenExpireName));
if (Ember.isEmpty(token)) {
return reject(new Error('empty token'));
}
if (Ember.isEmpty(expiresAt)) {
// Fetch the expire time from the token data since `expiresAt`
// wasn't included in the data object that was passed in.
const tokenData = this.getTokenData(token);
expiresAt = this.resolveTime(tokenData[this.tokenExpireName]);
if (Ember.isEmpty(expiresAt)) {
return resolve(data);
}
}
if (expiresAt > now) {
const wait = (expiresAt - now - this.refreshLeeway) * 1000;
if (wait > 0) {
if (this.refreshAccessTokens) {
this.scheduleAccessTokenRefresh(dataObject.get(this.tokenExpireName), token);
}
resolve(data);
} else if (this.refreshAccessTokens) {
resolve(this.refreshAccessToken(token));
} else {
reject(new Error('unable to refresh token'));
}
} else {
reject(new Error('token is expired'));
}
});
},
getCurrentTime() {
return Math.floor((new Date()).getTime() / 1000);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment