Skip to content

Commit 113b165

Browse files
committed
fix: auth middleware
1 parent 1d72336 commit 113b165

File tree

3 files changed

+20
-21
lines changed

3 files changed

+20
-21
lines changed

src/module.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ export default defineNuxtModule<ModuleOptions>({
5555
passwordResetTokens: options.tables?.passwordResetTokens || defaultOptions.tables.passwordResetTokens,
5656
},
5757
auth: {
58-
whitelist: options.auth?.whitelist || defaultOptions.auth?.whitelist || ['/login'],
58+
whitelist: [...(defaultOptions.auth?.whitelist || []), ...(options.auth?.whitelist || [])]
5959
},
6060
}
6161

src/runtime/middleware/auth.global.ts

Lines changed: 0 additions & 19 deletions
This file was deleted.

src/runtime/plugin.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import { defineNuxtPlugin, useRuntimeConfig } from '#app'
1+
import { addRouteMiddleware, defineNuxtPlugin, useRuntimeConfig, navigateTo } from '#app'
2+
import type { RouteLocationNormalized } from 'vue-router'
23
import type { ModuleOptions } from '../types'
34
import { checkTableExists } from '../utils'
5+
import { useAuth } from './composables/useAuth'
46

57
export default defineNuxtPlugin(async (_nuxtApp) => {
68
const { nuxtUsers } = useRuntimeConfig()
@@ -10,4 +12,20 @@ export default defineNuxtPlugin(async (_nuxtApp) => {
1012
if (!hasMigrationsTable) {
1113
console.warn('[Nuxt Users] ⚠️ Migrations table does not exist, you should run the migration script to create it by running: npx nuxt-users migrate')
1214
}
15+
16+
addRouteMiddleware('auth.global', (to: RouteLocationNormalized, _from: RouteLocationNormalized) => {
17+
const { user } = useAuth()
18+
19+
// TODO add role based access control see #55
20+
if (
21+
user.value || nuxtUsers.auth?.whitelist?.includes(to.path)
22+
) {
23+
console.log('🔐 [Nuxt Users] Auth middleware: Access allowed')
24+
return
25+
}
26+
27+
console.log('🔐 [Nuxt Users] Auth middleware: Redirecting to login - no user and not whitelisted')
28+
return navigateTo('/login')
29+
},
30+
{ global: true })
1331
})

0 commit comments

Comments
 (0)