Created
January 7, 2022 05:07
-
-
Save zaverden/9f6579f262ac25b591dd814047e19b30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { withAuthUserTokenSSR, AuthAction, type AuthUser } from "next-firebase-auth"; | |
import { NextApiRequest, NextApiResponse } from "next"; | |
const checkServerSideAuth = | |
typeof window !== "undefined" | |
? () => {} // "withAuthUserTokenSSR" can only be called server-side. | |
: withAuthUserTokenSSR({ | |
whenAuthed: AuthAction.RENDER, | |
whenUnauthed: AuthAction.REDIRECT_TO_LOGIN, | |
authPageURL: "401", | |
})(async ({ AuthUser }) => ({ AuthUser, props: {} })); | |
type AuthorizedApiHandler = ( | |
req: NextApiRequest, | |
res: NextApiResponse, | |
auth: AuthUser | |
) => Promise<void>; | |
export function withAuthUserTokenAPI(handler: AuthorizedApiHandler) { | |
return async (req: NextApiRequest, res: NextApiResponse) => { | |
// @ts-expect-error wrong typings in lib. remove expect-error if typings are correct now | |
const { AuthUser, redirect } = await checkServerSideAuth({ req, res }); | |
if (redirect) { | |
res.status(401).json({ ok: false, code: "unauthorized" }); | |
return; | |
} | |
return handler(req, res, AuthUser); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment