import { Maybe } from '@api/generated/graphql' ; import { extractAuthToken , destroyAuthTokenCookie , } from '@api/auth/authcookie.utils' ; import { Viewer } from '../shared/shared.types' ; import { NextApiMiddleware } from '@api/shared/shared.types' ; declare module 'next' { interface NextApiRequest { viewer : Viewer ; authToken : Maybe < string > ; } } const authenticate = ( fn ) => async ( req , res ) => { const authToken = extractAuthToken ( req . cookies ) ; if ( ! authToken ) { return fn ( req , res ) ; } const { db } = req ; const verified = await db . authToken . verify ( authToken ) ; if ( ! verified ) { destroyAuthTokenCookie ( res ) ; return fn ( req , res ) ; } const { userId } = verified ; const viewer = await db . user . findOneById ( userId ) ; req . viewer = viewer ; req . authToken = authToken ; Object . values ( db ) . forEach ( ( repo ) => repo . patchContext ( { viewer , authToken } ) ) ; return fn ( req , res ) ; } ; export default authenticate ;