2020-08-22 20:25:57 +00:00
|
|
|
import { withIronSession } from 'next-iron-session';
|
|
|
|
import type { Session } from 'next-iron-session';
|
|
|
|
import { IncomingMessage, ServerResponse } from 'http';
|
|
|
|
import { NextApiResponse, NextPageContext } from 'next';
|
|
|
|
import { DocumentContext } from 'next/document';
|
|
|
|
|
|
|
|
export interface IncomingMessageWithSession extends IncomingMessage {
|
|
|
|
body: any;
|
|
|
|
session: Session
|
|
|
|
}
|
|
|
|
|
|
|
|
export type HandlerWithDocumentContextAndSession<T> = (
|
|
|
|
ctx: DocumentContext & {
|
|
|
|
req: IncomingMessageWithSession
|
|
|
|
},
|
|
|
|
) => Promise<T>;
|
|
|
|
|
|
|
|
export type HandlerWithPageContextAndSession<T> = (
|
|
|
|
ctx: NextPageContext & {
|
|
|
|
req: IncomingMessageWithSession
|
|
|
|
},
|
|
|
|
) => Promise<T>;
|
|
|
|
|
|
|
|
export type HandlerWithReqResAndSession<T> = (
|
|
|
|
req: IncomingMessageWithSession,
|
|
|
|
res: NextApiResponse
|
|
|
|
) => Promise<T>;
|
|
|
|
|
|
|
|
export type HandlerWithSession<T, U> =
|
|
|
|
T extends IncomingMessageWithSession
|
|
|
|
? HandlerWithReqResAndSession<U>
|
|
|
|
: T extends NextPageContext
|
|
|
|
? HandlerWithPageContextAndSession<U>
|
|
|
|
: HandlerWithDocumentContextAndSession<U>;
|
|
|
|
|
2021-01-04 16:31:36 +00:00
|
|
|
export type SessionHandler<R = any, A = any, O = any> = (req: IncomingMessageWithSession, res: NextApiResponse<O>, ...args: Array<A>) => R;
|
|
|
|
|
|
|
|
export default function withSession<R = any, A = any, O = any>(handler: SessionHandler<R, A, O>) {
|
2020-08-22 20:25:57 +00:00
|
|
|
return withIronSession(handler, {
|
|
|
|
cookieName: 'gdq-archive',
|
|
|
|
cookieOptions: {
|
|
|
|
// the next line allows to use the session in non-https environements like
|
|
|
|
// Next.js dev mode (http://localhost:3000)
|
|
|
|
secure: process.env.NODE_ENV === 'production',
|
|
|
|
httpOnly: true,
|
|
|
|
},
|
|
|
|
password: process.env.SECRET_PASSWORD || '0'.repeat(32),
|
|
|
|
});
|
|
|
|
}
|