Skip to content

Commit

Permalink
feat(cognito): fallback based on user status
Browse files Browse the repository at this point in the history
  • Loading branch information
aiji42 committed Nov 22, 2021
1 parent d5fb481 commit 22f281f
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/cognito.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ import { decodeProtectedHeader, importJWK, JWK, jwtVerify } from 'jose'
export const makeCognitoInspector = (
fallback: Fallback,
cognitoRegion: string,
cognitoUserPoolId: string
cognitoUserPoolId: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customHandler?: (payload: any) => boolean
): AsyncMiddleware => {
return async (request, event) => {
const ok = await verifyCognitoAuthenticatedUser(
request,
cognitoRegion,
cognitoUserPoolId
cognitoUserPoolId,
customHandler
)
if (ok) return
return handleFallback(fallback, request, event)
Expand All @@ -22,7 +25,9 @@ export const makeCognitoInspector = (
const verifyCognitoAuthenticatedUser = async (
req: NextRequest,
region: string,
poolId: string
poolId: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customHandler?: (payload: any) => boolean
): Promise<boolean> => {
const token = Object.entries(req.cookies).find(([key]) =>
/CognitoIdentityServiceProvider\..+\.idToken/.test(key)
Expand All @@ -38,6 +43,6 @@ const verifyCognitoAuthenticatedUser = async (
if (!jwk) return false

return jwtVerify(token, await importJWK(jwk))
.then(() => true)
.then((res) => customHandler?.(res.payload) ?? true)
.catch(() => false)
}

0 comments on commit 22f281f

Please sign in to comment.