rebase fixing conflicts

This commit is contained in:
Agusti Fernandez Pardo committed 2022-03-23 22:22:57 +01:00
1 parent 11e1312e3a
commit 9a5c3f96ec
22 files changed
+694 -56

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(req: NextApiRequest) {
// return early if url isn't supposed to be protected
// if (!req.url.includes("/protected-url")) {
// return NextResponse.next()
// }
console.log(req.headers);
const session = await getToken({ req, secret: process.env.SECRET });
// You could also check for any property on the session object,
// like role === "admin" or name === "John Doe", etc.
if (!session) {
return NextResponse.redirect("https://localhost:3002/unauthorized");
}
// If user is authenticated, continue.
return NextResponse.next();
}
+82
View File
@@ -0,0 +1,82 @@
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import NextAuth, { NextAuthOptions } from "next-auth";
import EmailProvider from "next-auth/providers/email";
// FIXME: not working when importing prisma directly from our project
// import prisma from "@calcom/prisma";
const prisma = new PrismaClient();
// TODO: get rid of this and do it in it's own auth.cal.com project with a custom Next.js app
export const authOptions: NextAuthOptions = {
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
adapter: PrismaAdapter(prisma),
// https://next-auth.js.org/configuration/providers
providers: [
EmailProvider({
maxAge: 10 * 60 * 60, // Magic links are valid for 10 min only
// sendVerificationRequest,
}),
],
secret: process.env.NEXTAUTH_SECRET,
session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `strategy` should be set to 'jwt' if no database is used.
// TODO: Do we want to move 'database' sessions at some point?
strategy: "jwt",
// Seconds - How long until an idle session expires and is no longer valid.
// maxAge: 30 * 24 * 60 * 60, // 30 days
// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
// updateAge: 24 * 60 * 60, // 24 hours
},
// JSON Web tokens are only used for sessions if the `strategy: 'jwt'` session
// option is set - or by default if no database is specified.
// https://next-auth.js.org/configuration/options#jwt
jwt: {
// A secret to use for key generation (you should set this explicitly)
secret: process.env.SECRET,
// Set to true to use encryption (default: false)
// encryption: true,
// You can define your own encode/decode functions for signing and encryption
// if you want to override the default behaviour.
// encode: async ({ secret, token, maxAge }) => {},
// decode: async ({ secret, token, maxAge }) => {},
},
// https://next-auth.js.org/configuration/pages
// NOTE: We don't want to enable these, only the API endpoints for auth. We will get rid of this when we do auth.cal.com
pages: {
signIn: "/", // Displays signin buttons
signOut: "/", // Displays form with sign out button
error: "/", // Error code passed in query string as ?error=
verifyRequest: "/", // Used for check email page
newUser: "/", // If set, new users will be directed here on first sign in
},
// Callbacks are asynchronous functions you can use to control what happens
// when an action is performed.
// https://next-auth.js.org/configuration/callbacks
callbacks: {
// async signIn({ user, account, profile, email, credentials }) { return true },
// async redirect({ url, baseUrl }) { return baseUrl },
// async session({ session, token, user }) { return session },
// FIXME: add a custom jwt callback, that is stored outside next-auth
// and can be reused to generate valid Personal Access Tokens for the API.
// async jwt({ token, user, account, profile, isNewUser }) { return token }
},
// Events are useful for logging
// https://next-auth.js.org/configuration/events
// Enable debug messages in the console if you are having problems
debug: false,
};
export default NextAuth(authOptions);
+19
View File
@@ -0,0 +1,19 @@
import { EventType } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
type EventIdData = {
event?: EventType;
error?: any;
};
export default async function eventType(req: NextApiRequest, res: NextApiResponse<EventIdData>) {
try {
const event = await prisma.eventType.findUnique({ where: { id: Number(req.query.id) } });
res.status(200).json({ event });
} catch (error) {
console.log(error);
res.status(400).json({ error: error });
}
}
+20
View File
@@ -0,0 +1,20 @@
import { PrismaClient, EventType } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
type EventTypeIdData = {
events?: EventType[];
error?: any;
};
const prisma = new PrismaClient();
export default async function eventType(req: NextApiRequest, res: NextApiResponse<EventTypeIdData>) {
try {
const eventTypes = await prisma.eventType.findMany({ where: { id: Number(req.query.eventTypeId) } });
res.status(200).json({ events: { ...eventTypes } });
} catch (error) {
console.log(error);
// FIXME: Add zod for validation/error handling
res.status(400).json({ error: error });
}
}
+85
View File
@@ -0,0 +1,85 @@
import { PrismaClient, EventType } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
const prisma = new PrismaClient();
interface Body {
userId: string;
newOrganization: {
name: string;
users: string[];
};
}
type EventsData = {
event?: EventType;
error?: string;
};
export default async function createEventLink(req: NextApiRequest, res: NextApiResponse<EventsData>) {
const {
body: {
title,
slug,
description,
position,
locations,
hidden,
teamId,
eventName,
timeZone,
periodType,
periodStartDate,
periodEndDate,
periodDays,
periodCountCalendarDays,
requiresConfirmation,
disableGuests,
minimumBookingNotice,
beforeEventBuffer,
afterEventBuffer,
schedulingType,
price,
currency,
slotInterval,
metadata,
length,
},
method,
} = req;
if (method === "POST") {
// Process a POST request
const newEvent = await prisma.eventType.create({
data: {
title: `${title}`,
slug: `${slug}`,
length: Number(length),
// description: description as string,
// position: Number(position),
// locations: locations,
// hidden: Boolean(hidden) as boolean,
// teamId: Number.isInteger(teamId) ? Number(teamId) : null,
// eventName: eventName,
// timeZone: timeZone,
// periodType: periodType,
// periodStartDate: periodStartDate,
// periodEndDate: periodEndDate,
// periodDays: periodDays,
// periodCountCalendarDays: periodCountCalendarDays,
// requiresConfirmation: requiresConfirmation,
// disableGuests: disableGuests,
// minimumBookingNotice: minimumBookingNotice,
// beforeEventBuffer: beforeEventBuffer,
// afterEventBuffer: afterEventBuffer,
// schedulingType: schedulingType,
// price: price,
// currency: currency,
// slotInterval: slotInterval,
// metadata: metadata,
},
});
res.status(201).json({ event: newEvent });
} else {
// Handle any other HTTP method
res.status(405).json({ error: "Only POST Method allowed" });
}
}
+8
View File
@@ -0,0 +1,8 @@
import type { NextApiRequest, NextApiResponse } from "next"
import { getToken } from "next-auth/jwt";
const secret = process.env.NEXTAUTH_SECRET;
export default async function jwt(req: NextApiRequest, res: NextApiResponse) {
const token = await getToken({ req, secret });
res.send(JSON.stringify(token, null, 2));
}
+36
View File
@@ -0,0 +1,36 @@
import { PrismaClient } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { getToken } from "next-auth/jwt";
// This local import doesn't work
// import { PrismaClient } from "@calcom/prisma";
const prisma = new PrismaClient();
const secret = process.env.NEXTAUTH_SECRET;
type Data = {
message: string;
};
export default async function me(req: NextApiRequest, res: NextApiResponse<Data>) {
const token = await getToken({ req, secret, raw: false });
console.log("token", token);
if (!token)
return res.status(404).json({
message: `You're not authenticated. Provide a valid Session JWT as Authorization: 'Bearer {your_token_here}'`,
});
if (!token.email)
return res.status(404).json({
message: `Your token doesn't have a valid email`,
});
const email: string | undefined = token?.email;
const user = await prisma.user.findUnique({
where: {
email: email,
},
});
return res.json({
message: `Hello ${user?.name}, your email is ${user?.email}, and your email is ${
user?.emailVerified ? "verified" : "unverified"
}`,
});
}
+19
View File
@@ -0,0 +1,19 @@
// This is an example of how to read a JSON Web Token from an API route
import type { NextApiRequest, NextApiResponse } from "next";
import { getToken } from "next-auth/jwt";
const secret = process.env.NEXTAUTH_SECRET;
export default async function jwt(req: NextApiRequest, res: NextApiResponse) {
const token = await getToken({ req, secret, raw: false });
if (token) {
res.send({
content: "This is protected content. You can access this content because you are signed in.",
token,
});
} else {
res.send({
error: "You must be signed in to view the protected content on this page.",
});
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "./auth/[...nextauth]";
export default async function session(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession({ req, res }, authOptions);
/* ... */
if (session) {
res.send(JSON.stringify(session, null, 2));
} else {
res.end();
}
}
+21
View File
@@ -0,0 +1,21 @@
import { PrismaClient } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
// This local import doesn't work
// import { PrismaClient } from "@calcom/prisma";
const prisma = new PrismaClient();
type Data = {
message: string;
};
export default async function userId(req: NextApiRequest, res: NextApiResponse<Data>) {
const { id }: { id?: string } = req.query;
if (!id) return res.status(404).json({ message: `User not found` });
const user = await prisma.user.findUnique({
where: {
id: parseInt(id),
},
});
return res.json({ message: `Hello ${user?.name}` });
}