Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Don't call signIn in middleware server-side #647

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/runtime/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { navigateToAuthPages, determineCallbackUrl } from '../utils/url'
import { navigateTo, defineNuxtRouteMiddleware, useRuntimeConfig, useAuth } from '#imports'
import { navigateTo, defineNuxtRouteMiddleware, useRuntimeConfig, useAuth, abortNavigation } from '#imports'

type MiddlewareMeta = boolean | {
/** Whether to only allow unauthenticated users to access this page.
Expand Down Expand Up @@ -27,7 +27,7 @@ declare module '#app' {
}
}

export default defineNuxtRouteMiddleware((to) => {
export default defineNuxtRouteMiddleware(async (to) => {
const metaAuth = typeof to.meta.auth === 'object'
? {
unauthenticatedOnly: true,
Expand Down Expand Up @@ -85,6 +85,18 @@ export default defineNuxtRouteMiddleware((to) => {
}

if (authConfig.provider.type === 'authjs') {
if (process.server) {
// @ts-ignore This is valid for fetching the providers, as we already know this middelware only runs for authjs
const { getProviders } = useAuth()
const providers = await getProviders()
const defaultProvider = providers[authConfig.provider.defaultProvider] ?? providers[Object.keys(providers)[0]]
if (defaultProvider) {
return navigateTo(defaultProvider.signinUrl, { external: true })
}
// Fallback, if no provider signin url can be found, throw error page
return abortNavigation({ message: 'Please authenticate', statusCode: 403 })
}

const signInOptions: Parameters<typeof signIn>[1] = { error: 'SessionRequired', callbackUrl: determineCallbackUrl(authConfig, () => to.fullPath) }
// @ts-ignore This is valid for a backend-type of `authjs`, where sign-in accepts a provider as a first argument
return signIn(undefined, signInOptions) as ReturnType<typeof navigateToAuthPages>
Expand Down