Skip to content

Commit

Permalink
feat(app): added redirection to unauthorized route after signin
Browse files Browse the repository at this point in the history
Added a feature to store the requested route that is outside the scope of the excluded routes. The route is stored in a cookie and disabled by default.
  • Loading branch information
Matthewenderle committed Jan 21, 2024
1 parent 410ae98 commit 96b799b
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ export default defineNuxtModule<ModuleOptions>({
redirectOptions: {
login: '/login',
callback: '/confirm',
exclude: []
exclude: [],
cookieRedirect: false
},
cookieName: 'sb',
cookieOptions: {
Expand Down Expand Up @@ -151,8 +152,7 @@ export default defineNuxtModule<ModuleOptions>({

// ensure callback URL is not using SSR
const mergedOptions = nuxt.options.runtimeConfig.public.supabase
if (mergedOptions.redirect &&
mergedOptions.redirectOptions.callback) {
if (mergedOptions.redirect && mergedOptions.redirectOptions.callback) {
const routeRules: { [key: string]: any } = {}
routeRules[mergedOptions.redirectOptions.callback] = { ssr: false }
nuxt.options.nitro = defu(nuxt.options.nitro, {
Expand Down
6 changes: 4 additions & 2 deletions src/runtime/plugins/auth-redirect.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useSupabaseUser } from '../composables/useSupabaseUser'
import { defineNuxtPlugin, addRouteMiddleware, defineNuxtRouteMiddleware, useRuntimeConfig, navigateTo } from '#imports'
import { defineNuxtPlugin, addRouteMiddleware, defineNuxtRouteMiddleware, useCookie, useRuntimeConfig, navigateTo } from '#imports'

export default defineNuxtPlugin({
name: 'auth-redirect',
Expand All @@ -8,7 +8,8 @@ export default defineNuxtPlugin({
'global-auth',
defineNuxtRouteMiddleware((to) => {
const config = useRuntimeConfig().public.supabase
const { login, callback, exclude } = config.redirectOptions
const { login, callback, exclude, cookieRedirect } = config.redirectOptions
const { cookieName, cookieOptions } = config

// Do not redirect on login route, callback route and excluded routes
const isExcluded = [...exclude, login, callback]?.some((path) => {
Expand All @@ -19,6 +20,7 @@ export default defineNuxtPlugin({

const user = useSupabaseUser()
if (!user.value) {
if (cookieRedirect) { useCookie(`${cookieName}-redirect-path`, cookieOptions).value = to.fullPath }
return navigateTo(login)
}
}),
Expand Down
1 change: 1 addition & 0 deletions src/runtime/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ export interface RedirectOptions {
login: string
callback: string
exclude?: string[]
cookieRedirect?: boolean
}

0 comments on commit 96b799b

Please sign in to comment.