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: execute userMiddleware handler if the user is authorized #10529

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 14 additions & 1 deletion packages/next-auth/src/lib/index.ts
Expand Up @@ -114,6 +114,13 @@ function isReqWrapper(arg: any): arg is NextAuthMiddleware | AppRouteHandlerFn {
return typeof arg === "function"
}

function isMiddleware(
_userMiddlewareOrRoute: NextAuthMiddleware | AppRouteHandlerFn,
arg1: NextFetchEvent | Parameters<AppRouteHandlerFn>[1]
): _userMiddlewareOrRoute is NextAuthMiddleware {
return "sourcePage" in arg1 && arg1.sourcePage.includes("middleware")
}

export function initAuth(
config:
| NextAuthConfig
Expand Down Expand Up @@ -254,7 +261,13 @@ async function handleAuth(
) {
authorized = true
}
} else if (userMiddlewareOrRoute) {
} else if (
userMiddlewareOrRoute &&
// If userMiddlewareOrRoute is a route handler, execute it
// If it's a middleware, only execute it if the user is authorized
(!isMiddleware(userMiddlewareOrRoute, args[1]) ||
(isMiddleware(userMiddlewareOrRoute, args[1]) && authorized))
) {
// Execute user's middleware/handler with the augmented request
const augmentedReq = request as NextAuthRequest
augmentedReq.auth = auth
Expand Down