Skip to content

Commit

Permalink
fix: execute userMiddleware handler if the user is authorized
Browse files Browse the repository at this point in the history
  • Loading branch information
yicrotkd committed Apr 10, 2024
1 parent 445c650 commit dfcce69
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion packages/next-auth/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,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 @@ -256,7 +263,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

0 comments on commit dfcce69

Please sign in to comment.