Skip to content

Commit

Permalink
feat: rewriteRedirects
Browse files Browse the repository at this point in the history
  • Loading branch information
Pooya Parsa authored and pi0 committed Feb 2, 2018
1 parent c50e68f commit dde409a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 10 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
33 changes: 23 additions & 10 deletions lib/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions lib/defaults.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = {
fetchUserOnLogin: true,
resetOnError: true,
rewriteRedirects: true,
namespace: 'auth',
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
Expand Down

0 comments on commit dde409a

Please sign in to comment.