import { NextApiRequest , NextApiResponse } from "next" ; import http from "http" ; import listen from "test-listen" ; import { apiResolver } from "next-server/dist/server/api-utils" ; import fetch from "isomorphic-unfetch" ; import { PublicConfig } from ".." ; import jwt from "jsonwebtoken" ; import { AuthRouteHandlerOptions , ServerConfig , createGetServerSideAuth , } from "../api" ; export { fetch } ; export const publicConfig = { baseUrl : "http://localhost:3000" , identityProviders : { } , } ; export const serverConfig = { cookieName : "happyauth-test" , identityProviders : { } , secure : false , tokenSecret : "fake-token-secret" , triggers : { sendConfirmAccountMail : jest . fn ( ) , sendForgotPasswordMail : jest . fn ( ) , fetchAdditionalTokenContent : jest . fn ( ) , } , driver : { attemptEmailPasswordLogin : jest . fn ( ) , changeEmailUserPassword : jest . fn ( ) , confirmAccount : jest . fn ( ) , createEmailUser : jest . fn ( ) , getUserIdByEmail : jest . fn ( ) , updateEmailUserPassword : jest . fn ( ) , } , } ; export function createAuthRouteHandlerOptions ( defaultServerConfig = serverConfig ) { return { getServerSideAuth : createGetServerSideAuth ( defaultServerConfig ) , publicConfig , serverConfig : { ... defaultServerConfig , driver : { attemptEmailPasswordLogin : jest . fn ( ) , changeEmailUserPassword : jest . fn ( ) , confirmAccount : jest . fn ( ) , createEmailUser : jest . fn ( ) , getUserIdByEmail : jest . fn ( ) , updateEmailUserPassword : jest . fn ( ) , } , triggers : { sendConfirmAccountMail : jest . fn ( ) , sendForgotPasswordMail : jest . fn ( ) , fetchAdditionalTokenContent : jest . fn ( ) , } , } , } ; } export async function createApi ( handler , params ? ) { const requestHandler = ( req , res ) => apiResolver ( req as NextApiRequest , res as NextApiResponse , params , handler ) ; const server = http . createServer ( requestHandler ) ; const url = await listen ( server ) ; return [ url , ( ) => { server . close ( ) ; } , ] ; } export function handler ( prepare , testFn ) { return async ( ) => { const apiHandler = await ( typeof prepare === "function" ? prepare ( ) : prepare . handle ( ) ) ; const [ url , close ] = await createApi ( apiHandler , typeof prepare === "function" ? undefined : prepare . params ) ; try { await testFn ( url ) ; close ( ) ; } catch ( e ) { close ( ) ; throw e ; } } ; } export function createAuthCookie ( options , payload ) { const value = jwt . sign ( payload , options . serverConfig . tokenSecret ) ; return `${ options . serverConfig . cookieName }=${ value }` ; }