Skip to content

Instantly share code, notes, and snippets.

@doanhpv-0200
Forked from zolotyx/auth.js
Created August 14, 2021 08:23
Show Gist options
  • Save doanhpv-0200/38b381f4b1d9c6f8c9db51c0e7facefd to your computer and use it in GitHub Desktop.
Save doanhpv-0200/38b381f4b1d9c6f8c9db51c0e7facefd to your computer and use it in GitHub Desktop.

Revisions

  1. @zolotyx zolotyx revised this gist Jul 28, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion auth.js
    Original file line number Diff line number Diff line change
    @@ -44,7 +44,7 @@ export default function ({ app }) {
    this.ctx.redirect(to)
    }
    } else {
    this.ctx.redirect(to, { redirect: from })
    this.ctx.redirect(to, { ...this.ctx.route.query, redirect: from })
    }
    }

  2. @zolotyx zolotyx created this gist Jul 27, 2018.
    52 changes: 52 additions & 0 deletions auth.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    export const isSameURL = (a, b) => a.split('?')[0] === b.split('?')[0]

    export const isRelativeURL = u =>
    u && u.length && /^\/[a-zA-Z0-9@\-%_~][/a-zA-Z0-9@\-%_~]*[?]?([^#]*)#?([^#]*)$/.test(u)

    export default function ({ app }) {
    const redirect = function (name, noRouter = false) {
    if (!this.options.redirect) {
    return
    }

    const from = this.options.fullPathRedirect ? this.ctx.route.fullPath : this.ctx.route.path

    let to = this.options.redirect[name]
    if (!to) {
    return
    }

    // Apply rewrites
    if (this.options.rewriteRedirects) {
    if (name === 'login' && isRelativeURL(from) && !isSameURL(to, from)) {
    this.$storage.setUniversal('redirect', from)
    }

    if (name === 'home') {
    const redirect = this.$storage.getUniversal('redirect') || this.ctx.route.query.redirect
    this.$storage.setUniversal('redirect', null)

    if (isRelativeURL(redirect)) {
    to = redirect
    }
    }
    }

    // Prevent infinity redirects
    if (isSameURL(to, from)) {
    return
    }

    if (process.browser) {
    if (noRouter) {
    window.location.replace(to)
    } else {
    this.ctx.redirect(to)
    }
    } else {
    this.ctx.redirect(to, { redirect: from })
    }
    }

    app.$auth.redirect = redirect.bind(app.$auth)
    }