gdq-archive/frontend/util/session.ts

67 lines
2.3 KiB
TypeScript

/**
* Copyright (C) 2019-2021 Carl Kittelberger <icedream@icedream.pw>
*
* 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 <http://www.gnu.org/licenses/>.
*/
import { withIronSession } from 'next-iron-session';
import type { Session } from 'next-iron-session';
import { IncomingMessage } 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 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>) {
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),
});
}