Switch to tRPC (#173)

This commit is contained in:
Luke Vella 2022-05-18 10:22:40 +01:00 committed by GitHub
parent 3d7e7e8a95
commit 2c4157ea24
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
245 changed files with 1585 additions and 1755 deletions

83
src/utils/auth.ts Normal file
View file

@ -0,0 +1,83 @@
import {
IronSession,
IronSessionOptions,
sealData,
unsealData,
} from "iron-session";
import { withIronSessionApiRoute, withIronSessionSsr } from "iron-session/next";
import { GetServerSideProps, NextApiHandler } from "next";
import { prisma } from "~/prisma/db";
import { randomid } from "./nanoid";
const sessionOptions: IronSessionOptions = {
password: process.env.SECRET_PASSWORD,
cookieName: "rallly-session",
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
ttl: 0, // basically forever
};
export function withSessionRoute(handler: NextApiHandler) {
return withIronSessionApiRoute(handler, sessionOptions);
}
export function withSessionSsr(handler: GetServerSideProps) {
return withIronSessionSsr(handler, sessionOptions);
}
export const decryptToken = async <P extends Record<string, unknown>>(
token: string,
): Promise<P> => {
return await unsealData(token, { password: sessionOptions.password });
};
export const createToken = async <T extends Record<string, unknown>>(
payload: T,
) => {
return await sealData(payload, {
password: sessionOptions.password,
ttl: 60 * 15, // 15 minutes
});
};
export const createGuestUser = async (session: IronSession) => {
session.user = {
id: `user-${await randomid()}`,
isGuest: true,
};
await session.save();
};
// assigns participants and comments created by guests to a user
// we could have multiple guests because a login might be triggered from one device
// and opened in another one.
export const mergeGuestsIntoUser = async (
userId: string,
guestIds: string[],
) => {
await prisma.participant.updateMany({
where: {
guestId: {
in: guestIds,
},
},
data: {
guestId: null,
userId: userId,
},
});
await prisma.comment.updateMany({
where: {
guestId: {
in: guestIds,
},
},
data: {
guestId: null,
userId: userId,
},
});
};