/** * Copyright (C) 2019-2021 Carl Kittelberger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ 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 = ( ctx: DocumentContext & { req: IncomingMessageWithSession }, ) => Promise; export type HandlerWithPageContextAndSession = ( ctx: NextPageContext & { req: IncomingMessageWithSession }, ) => Promise; export type HandlerWithReqResAndSession = ( req: IncomingMessageWithSession, res: NextApiResponse ) => Promise; export type HandlerWithSession = T extends IncomingMessageWithSession ? HandlerWithReqResAndSession : T extends NextPageContext ? HandlerWithPageContextAndSession : HandlerWithDocumentContextAndSession; export type SessionHandler = (req: IncomingMessageWithSession, res: NextApiResponse, ...args: Array) => R; export default function withSession(handler: SessionHandler) { 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), }); }