Permalink
Browse files

feat: rewriteRedirects

  • Loading branch information...
pi0 committed Feb 2, 2018
1 parent c50e68f commit dde409af9b4b9b4cb899488889015e04a00c5255
Showing with 29 additions and 10 deletions.
  1. +5 −0 README.md
  2. +23 −10 lib/auth.js
  3. +1 −0 lib/defaults.js
@@ -150,6 +150,11 @@ If enabled, user will be auto fetched after login.
If enabled, user will be automatically logged out if any error happens. (For example when token expired)
### `rewriteRedirects`
- Default: `true`
If enabled, user will came back to the original guarded route instead of `redirects.home`.
### `namespace`
- Default: `auth`
@@ -3,6 +3,8 @@ import { parse as parseCookie } from 'cookie'
import getProp from 'dotprop'
import Vue from 'vue'
const RELATIVE_URL_REGEX = /^\/[a-zA-Z0-9@\-%_~][\/a-zA-Z0-9@\-%_~]{1,200}$/
export default class Auth {
constructor (ctx, options) {
this.ctx = ctx
@@ -54,10 +56,9 @@ export default class Auth {
this.$store.watch(
state => state[this.options.namespace]['loggedIn'],
() => {
this.redirect()
this.redirect('home')
}
)
return this._loggedInWatcher
}
@@ -275,20 +276,32 @@ export default class Auth {
}
redirect (name) {
if (name === undefined) {
name = this.getState('loggedIn') ? 'home' : 'login'
}
let to = this.options.redirect[name]
const from = this.$route.path
// Prevent infinity redirects
if (to.split('?')[0] === from) {
if (!to) {
return
}
if (name === 'login' && to.indexOf('?') === -1) {
to = to + '?redirect=' + from
// Apply rewrites
if (this.options.rewriteRedirects) {
if (name === 'login') {
to = to + '?redirect=' + encodeURIComponent(from)
}
if (name === 'home' && this.$route.query.redirect) {
// Decode
const redirect = decodeURIComponent(this.$route.query.redirect)
// Validate
if (RELATIVE_URL_REGEX.test(redirect)) {
to = redirect
}
}
}
// Prevent infinity redirects
if (to.split('?')[0] === from) {
return
}
this.ctx.redirect(to)
@@ -1,6 +1,7 @@
module.exports = {
fetchUserOnLogin: true,
resetOnError: true,
rewriteRedirects: true,
namespace: 'auth',
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },

0 comments on commit dde409a

Please sign in to comment.