Skip to content

Commit

Permalink
feat(core): add token expiration helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
MathiasCiarlo authored and pi0 committed Mar 15, 2020
1 parent 6ba12a9 commit a42ba8e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
66 changes: 66 additions & 0 deletions lib/core/utilities.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import jwtDecode, { InvalidTokenError } from 'jwt-decode'

export const isUnset = o => typeof o === 'undefined' || o === null
export const isSet = o => !isUnset(o)

Expand Down Expand Up @@ -110,3 +112,67 @@ export function getProp (holder, propName) {

return result
}

const TokenExpirationStatusEnum = Object.freeze({
UNKNOWN: 'UNKNOWN',
VALID: 'VALID',
EXPIRED: 'EXPIRED',
REFRESH_EXPIRED: 'REFRESH_EXPIRED'
})

export class TokenExpirationStatus {
constructor (scheme) {
this.token = scheme.$auth.getToken(scheme.name)
this.refreshToken = scheme.$auth.getRefreshToken(scheme.name)

this.status = this._calculateTokenStatus()
}

_calculateTokenStatus () {
const now = Date.now()
let tokenExpiresAt, refreshTokenExpiresAt

try {
tokenExpiresAt = jwtDecode(this.token).exp * 1000
refreshTokenExpiresAt = jwtDecode(this.refreshToken).exp * 1000
} catch (error) {
// If the token is not jwt, we can't decode and refresh it
if (error instanceof InvalidTokenError) {
return TokenExpirationStatusEnum.UNKNOWN
}
throw error
}

// Give us some slack to help the token from expiring between validation and usage
const timeSlackMillis = 500
tokenExpiresAt -= timeSlackMillis
refreshTokenExpiresAt -= timeSlackMillis

// Token is still valid
if (now < tokenExpiresAt) {
return TokenExpirationStatusEnum.VALID
}

if (now > refreshTokenExpiresAt) {
return TokenExpirationStatusEnum.REFRESH_EXPIRED
}

return TokenExpirationStatusEnum.EXPIRED
}

unknown () {
return TokenExpirationStatusEnum.UNKNOWN === this.status
}

valid () {
return TokenExpirationStatusEnum.VALID === this.status
}

expired () {
return TokenExpirationStatusEnum.EXPIRED === this.status
}

refreshExpired () {
return TokenExpirationStatusEnum.REFRESH_EXPIRED === this.status
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"cookie": "^0.4.0",
"is-https": "^1.0.0",
"js-cookie": "^2.2.1",
"jwt-decode": "^2.2.0",
"lodash": "^4.17.15",
"nanoid": "^2.1.11"
},
Expand Down

0 comments on commit a42ba8e

Please sign in to comment.