Skip to content

Commit

Permalink
feat(request handler): add initializeRequestInterceptor method
Browse files Browse the repository at this point in the history
  • Loading branch information
JoaoPedroAS51 committed Mar 17, 2020
1 parent a440961 commit 07759c8
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions lib/core/requestHandler.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import ExpiredAuthSessionError from './includes/ExpiredAuthSessionError'

export default class RequestHandler {
constructor (auth) {
this.$auth = auth
}

_getUpdatedRequestConfig (config) {
config.headers[this.$auth.strategy.options.token.name] = this.$auth.token.get()
return config
}

setHeader (token) {
if (this.$auth.strategy.options.token.global) {
// Set Authorization token for all axios requests
Expand All @@ -16,4 +23,29 @@ export default class RequestHandler {
this.$auth.ctx.app.$axios.setHeader(this.$auth.strategy.options.token.name, false)
}
}

initializeRequestInterceptor () {
this.$auth.ctx.app.$axios.onRequest(async config => {
// Sync token
const token = this.$auth.token.sync()

// Get status
const tokenStatus = this.$auth.token.status()

// If no token, bail
if (!token) {
return config
}

// Token has expired. Force reset.
if (tokenStatus.expired()) {
await this.$auth.reset()

throw new ExpiredAuthSessionError()
}

// Token is still valid. Fetch updated token and add to current request
return this._getUpdatedRequestConfig(config)
})
}
}

0 comments on commit 07759c8

Please sign in to comment.