53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
|
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>;
|
||
|
|
||
|
export default function withSession<T>(
|
||
|
handler: (
|
||
|
req: IncomingMessageWithSession,
|
||
|
res: NextApiResponse,
|
||
|
...args: any) => Promise<T>,
|
||
|
): (...args: any) => Promise<T> {
|
||
|
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),
|
||
|
});
|
||
|
}
|