Skip to content

Commit aacb191

Browse files
pooya parsapaulgv
andcommitted
feat: support onRedirect hook (#185)
Co-authored-by: Paul Gascou <paul.gascvail@gmail.com>
1 parent e5579e9 commit aacb191

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

docs/api/auth.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,16 @@ export default function({ app }) {
124124
})
125125
}
126126
```
127+
128+
### `onRedirect(handler)`
129+
130+
Pre-process URLs before redirect: (`plugins/auth.js`)
131+
132+
```js
133+
export default function({ app }) {
134+
app.$auth.onRedirect((to, from) => {
135+
console.error(to)
136+
// you can optionally change `to` by returning a new value
137+
})
138+
}
139+
```

lib/core/auth.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ export default class Auth {
1414
// Error listeners
1515
this._errorListeners = []
1616

17+
// Redirect listeners
18+
this._redirectListeners = []
19+
1720
// Storage & State
1821
options.initialState = { user: null, loggedIn: false }
1922
const storage = new Storage(ctx, options)
@@ -352,6 +355,9 @@ export default class Auth {
352355
}
353356
}
354357

358+
// Call onRedirect hook
359+
to = this.callOnRedirect(to, from) || to
360+
355361
// Prevent infinity redirects
356362
if (isSameURL(to, from)) {
357363
return
@@ -368,6 +374,17 @@ export default class Auth {
368374
}
369375
}
370376

377+
onRedirect (listener) {
378+
this._redirectListeners.push(listener)
379+
}
380+
381+
callOnRedirect (to, from) {
382+
for (const fn of this._redirectListeners) {
383+
to = fn(to, from) || to
384+
}
385+
return to
386+
}
387+
371388
hasScope (scope) {
372389
const userScopes = this.$state.user && getProp(this.$state.user, this.options.scopeKey)
373390

0 commit comments

Comments
 (0)