fix: reenable member invites

This commit is contained in:
Henry
2025-05-22 12:18:56 +01:00
parent 82ec18e95e
commit 71c92eea27
16 changed files with 2183 additions and 231 deletions

View File

@@ -1,98 +0,0 @@
// import type { EmailOtpType } from "@supabase/supabase-js";
// import type { NextApiRequest } from "next";
// import { NextResponse } from "next/server";
// import { createDrizzleClient } from "@kan/db/client";
// import * as memberRepo from "@kan/db/repository/member.repo";
// import * as userRepo from "@kan/db/repository/user.repo";
// import { stripe } from "@kan/stripe";
// import { createNextApiClient } from "@kan/";
// export default async function handler(req: NextApiRequest) {
// if (req.method !== "GET") {
// return new NextResponse(null, {
// status: 405,
// headers: { Allow: "GET" },
// });
// }
// if (!req.url) {
// return new NextResponse(null, {
// status: 400,
// });
// }
// const url = new URL(req.url);
// const queryParams = Object.fromEntries(url.searchParams.entries());
// const tokenHash = queryParams.token_hash;
// const type = queryParams.type;
// const code = queryParams.code;
// const memberPublicId = queryParams.memberPublicId;
// let next = "/error";
// let authRes;
// const response = NextResponse.next();
// if ((tokenHash && type) ?? code) {
// const supabaseClient = createNextClient(req, response);
// if (tokenHash && type) {
// authRes = await supabaseClient.auth.verifyOtp({
// type: type as EmailOtpType,
// token_hash: tokenHash,
// });
// }
// if (code) {
// authRes = await supabaseClient.auth.exchangeCodeForSession(code);
// }
// const user = authRes?.data.user;
// const db = createDrizzleClient();
// if (user?.id && user.email) {
// const existingUser = await userRepo.getById(db, user.id);
// if (!existingUser) {
// const stripeCustomer = await stripe.customers.create({
// email: user.email,
// metadata: {
// userId: user.id,
// },
// });
// await userRepo.create(db, {
// id: user.id,
// email: user.email,
// stripeCustomerId: stripeCustomer.id,
// });
// }
// }
// if (memberPublicId) {
// const member = await memberRepo.getByPublicId(db, memberPublicId);
// if (member?.id) {
// await memberRepo.acceptInvite(db, member.id);
// }
// }
// if (authRes?.error) {
// console.error(authRes.error);
// } else {
// next = queryParams.next ?? "/boards";
// }
// }
// const redirectResponse = NextResponse.redirect(new URL(next, req.url));
// response.headers.getSetCookie().forEach((cookie) => {
// redirectResponse.headers.append("Set-Cookie", cookie);
// });
// return redirectResponse;
// }

View File

@@ -1,4 +1,4 @@
import { type NextApiRequest, type NextApiResponse } from "next";
import type { NextApiRequest, NextApiResponse } from "next";
import { createNextApiHandler } from "@trpc/server/adapters/next";
import { appRouter } from "@kan/api/root";
@@ -17,10 +17,7 @@ const nextApiHandler = createNextApiHandler({
: undefined,
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "OPTIONS") {
res.writeHead(200);
return res.end();

View File

@@ -10,11 +10,7 @@ import { PageHead } from "~/components/PageHead";
import { useModal } from "~/providers/modal";
import { useWorkspace } from "~/providers/workspace";
import { api } from "~/utils/api";
import {
getAvatarUrl,
getInitialsFromName,
inferInitialsFromEmail,
} from "~/utils/helpers";
import { getAvatarUrl } from "~/utils/helpers";
import { DeleteMemberConfirmation } from "./components/DeleteMemberConfirmation";
import { InviteMemberForm } from "./components/InviteMemberForm";
@@ -46,10 +42,6 @@ export default function MembersPage() {
isLastRow?: boolean;
showSkeleton?: boolean;
}) => {
const initials = memberName
? getInitialsFromName(memberName)
: inferInitialsFromEmail(memberEmail ?? "");
return (
<tr className="rounded-b-lg">
<td className={twMerge("w-[65%]", isLastRow ? "rounded-bl-lg" : "")}>
@@ -192,9 +184,9 @@ export default function MembersPage() {
<TableRow
key={member.publicId}
memberPublicId={member.publicId}
memberName={member.user.name}
memberEmail={member.user.email}
memberImage={member.user.image}
memberName={member.user?.name}
memberEmail={member.user?.email ?? member.email}
memberImage={member.user?.image}
memberRole={member.role}
memberStatus={member.status}
isLastRow={index === data.members.length - 1}

View File

@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { authClient } from "@kan/auth";
import * as memberRepo from "@kan/db/repository/member.repo";
import * as userRepo from "@kan/db/repository/user.repo";
import * as workspaceRepo from "@kan/db/repository/workspace.repo";
import { sendEmail } from "@kan/email";
import { createStripeClient } from "@kan/stripe";
import { createTRPCRouter, protectedProcedure } from "../trpc";
@@ -49,7 +48,7 @@ export const memberRouter = createTRPCRouter({
});
const isInvitedEmailAlreadyMember = workspace.members.some(
(member) => member.user.email === input.email,
(member) => member.email === input.email,
);
if (isInvitedEmailAlreadyMember) {
@@ -59,79 +58,12 @@ export const memberRouter = createTRPCRouter({
});
}
let invitedUserId: string | undefined;
let hashedToken: string | undefined;
let verificationType: string | undefined;
const existingUser = await userRepo.getByEmail(ctx.db, input.email);
// if (existingUser) {
// invitedUserId = existingUser.id;
// const magicLink = await ctx.supabaseClient.auth.admin.generateLink({
// type: "magiclink",
// email: input.email,
// options: {
// redirectTo: process.env.WEBSITE_URL,
// },
// });
// hashedToken = magicLink.data.properties?.hashed_token;
// verificationType = magicLink.data.properties?.verification_type;
// } else {
// const invite = await ctx.supabaseClient.auth.admin.generateLink({
// type: "invite",
// email: input.email,
// options: {
// redirectTo: process.env.WEBSITE_URL,
// },
// });
// hashedToken = invite.data.properties?.hashed_token;
// verificationType = invite.data.properties?.verification_type;
// const invitedUserAuthId = invite.data.user?.id;
// const invitedUserEmail = invite.data.user?.email;
// if (invitedUserAuthId && invitedUserEmail) {
// const stripeCustomer = await stripe.customers.create({
// email: invitedUserEmail,
// metadata: {
// userId: invitedUserAuthId,
// },
// });
// const newUser = await userRepo.create(ctx.db, {
// email: invitedUserEmail,
// id: invitedUserAuthId,
// stripeCustomerId: stripeCustomer.id,
// });
// if (!newUser)
// throw new TRPCError({
// message: `Failed to create a new user for email ${invitedUserEmail}`,
// code: "INTERNAL_SERVER_ERROR",
// });
// invitedUserId = newUser.id;
// }
// }
if (!invitedUserId)
throw new TRPCError({
message: `Unable to invite user with email ${input.email}`,
code: "INTERNAL_SERVER_ERROR",
});
if (!hashedToken || !verificationType)
throw new TRPCError({
message: `Unable to generate magic link for user with email ${input.email}`,
code: "INTERNAL_SERVER_ERROR",
});
const invite = await memberRepo.create(ctx.db, {
workspaceId: workspace.id,
userId: invitedUserId,
email: input.email,
userId: existingUser?.id ?? null,
createdBy: userId,
role: "member",
status: "invited",
@@ -143,16 +75,16 @@ export const memberRouter = createTRPCRouter({
code: "INTERNAL_SERVER_ERROR",
});
const magicLoginUrl = `${process.env.WEBSITE_URL}/api/auth/confirm?token_hash=${hashedToken}&type=${verificationType}&memberPublicId=${invite.publicId}`;
const { error } = await authClient.signIn.magicLink({
email: input.email,
callbackURL: `/boards?type=invite&memberPublicId=${invite.publicId}`,
});
await sendEmail(
input.email,
"Invitation to join workspace",
"JOIN_WORKSPACE",
{
magicLoginUrl,
},
);
if (error)
throw new TRPCError({
message: `Failed to send magic link to user with email ${input.email}`,
code: "INTERNAL_SERVER_ERROR",
});
return invite;
}),

View File

@@ -39,7 +39,7 @@ export const userRouter = createTRPCRouter({
const result = await userRepo.getById(ctx.db, userId);
if (!result?.name) {
if (!result) {
throw new TRPCError({
message: `User not found`,
code: "NOT_FOUND",

View File

@@ -117,8 +117,9 @@ export const workspaceRouter = createTRPCRouter({
.output(z.custom<Awaited<ReturnType<typeof workspaceRepo.create>>>())
.mutation(async ({ ctx, input }) => {
const userId = ctx.user?.id;
const userEmail = ctx.user?.email;
if (!userId)
if (!userId || !userEmail)
throw new TRPCError({
message: `User not authenticated`,
code: "UNAUTHORIZED",
@@ -131,6 +132,7 @@ export const workspaceRouter = createTRPCRouter({
name: input.name,
slug: workspacePublicId,
createdBy: userId,
createdByEmail: userEmail,
});
if (!result.publicId)

View File

@@ -5,6 +5,7 @@ import { apiKey } from "better-auth/plugins";
import { magicLink } from "better-auth/plugins/magic-link";
import type { dbClient } from "@kan/db/client";
import * as memberRepo from "@kan/db/repository/member.repo";
import * as userRepo from "@kan/db/repository/user.repo";
import * as schema from "@kan/db/schema";
import { sendEmail } from "@kan/email";
@@ -43,35 +44,69 @@ export const initAuth = (db: dbClient) => {
plugins: [
apiKey(),
magicLink({
expiresIn: 60 * 60 * 24 * 7, // 7 days
sendMagicLink: async ({ email, url }) => {
await sendEmail(email, "Sign in to kan.bn", "MAGIC_LINK", {
magicLoginUrl: url,
});
if (url.includes("type=invite")) {
await sendEmail(
email,
"Invitation to join workspace",
"JOIN_WORKSPACE",
{
magicLoginUrl: url,
},
);
} else {
await sendEmail(email, "Sign in to kan.bn", "MAGIC_LINK", {
magicLoginUrl: url,
});
}
},
}),
],
hooks: {
// after: createAuthMiddleware(async (ctx) => {
// if (ctx.path.startsWith("/sign-up") || ctx.path.startsWith("/sign-in")) {
// const session = ctx.context.session;
// if (
// session &&
// process.env.NEXT_PUBLIC_KAN_ENV === "cloud" &&
// !session.user.stripeCustomerId
// ) {
// const stripe = createStripeClient();
// const stripeCustomer = await stripe.customers.create({
// email: session.user.email,
// metadata: {
// userId: session.user.id,
// },
// });
// await userRepo.update(db, session.user.id, {
// stripeCustomerId: stripeCustomer.id,
// });
// }
// }
// }),
after: createAuthMiddleware(async (ctx) => {
if (ctx.path.startsWith("/get-session")) {
const user = ctx.context.session?.user;
if (
process.env.NEXT_PUBLIC_KAN_ENV === "cloud" &&
user &&
!user.stripeCustomerId
) {
const stripe = createStripeClient();
const stripeCustomer = await stripe.customers.create({
email: user.email,
metadata: {
userId: user.id,
},
});
await userRepo.update(db, user.id, {
stripeCustomerId: stripeCustomer.id,
});
}
} else if (
ctx.path === "/magic-link/verify" &&
(ctx.query?.callbackURL as string | undefined)?.includes(
"type=invite",
) &&
ctx.query?.memberPublicId
) {
const userId = ctx.context.newSession?.session.userId;
const memberPublicId = ctx.query.memberPublicId as string;
if (userId) {
const member = await memberRepo.getByPublicId(db, memberPublicId);
if (member?.id) {
await memberRepo.acceptInvite(db, {
memberId: member.id,
userId,
});
}
}
}
}),
},
advanced: {
cookiePrefix: "kan",

View File

@@ -0,0 +1,4 @@
ALTER TABLE "workspace_members" ALTER COLUMN "userId" DROP NOT NULL;--> statement-breakpoint
ALTER TABLE "workspace_members" ADD COLUMN "email" varchar(255);--> statement-breakpoint
UPDATE "workspace_members" wm SET "email" = u."email" FROM "user" u WHERE wm."userId" = u."id";--> statement-breakpoint
ALTER TABLE "workspace_members" ALTER COLUMN "email" SET NOT NULL;

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,13 @@
"when": 1746693478656,
"tag": "20250508083758_SetupTables",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1747903068807,
"tag": "20250522083748_AddEmailToWorkspaceMembers",
"breakpoints": true
}
]
}

View File

@@ -42,6 +42,7 @@
"drizzle-orm": "^0.42.0",
"drizzle-zod": "^0.5.1",
"pg": "^8.11.3",
"uuid": "^11.1.0",
"zod": "catalog:"
},
"devDependencies": {

View File

@@ -8,7 +8,8 @@ import { generateUID } from "@kan/shared/utils";
export const create = async (
db: dbClient,
memberInput: {
userId: string;
userId: string | null;
email: string;
workspaceId: number;
createdBy: string;
role: MemberRole;
@@ -19,6 +20,7 @@ export const create = async (
.insert(workspaceMembers)
.values({
publicId: generateUID(),
email: memberInput.email,
userId: memberInput.userId,
workspaceId: memberInput.workspaceId,
createdBy: memberInput.createdBy,
@@ -39,11 +41,14 @@ export const getByPublicId = async (db: dbClient, publicId: string) => {
});
};
export const acceptInvite = async (db: dbClient, id: number) => {
export const acceptInvite = async (
db: dbClient,
args: { memberId: number; userId: string },
) => {
const [result] = await db
.update(workspaceMembers)
.set({ status: "active" })
.where(eq(workspaceMembers.id, id))
.set({ status: "active", userId: args.userId })
.where(eq(workspaceMembers.id, args.memberId))
.returning({
id: workspaceMembers.id,
publicId: workspaceMembers.publicId,

View File

@@ -1,4 +1,5 @@
import { eq } from "drizzle-orm";
import { v4 as uuidv4 } from "uuid";
import type { dbClient } from "@kan/db/client";
import { users } from "@kan/db/schema";
@@ -29,12 +30,12 @@ export const getByEmail = (db: dbClient, email: string) => {
export const create = async (
db: dbClient,
user: { id: string; email: string; stripeCustomerId: string },
user: { id?: string; email: string; stripeCustomerId?: string },
) => {
const [result] = await db
.insert(users)
.values({
id: user.id,
id: user.id ?? uuidv4(),
email: user.email,
stripeCustomerId: user.stripeCustomerId,
emailVerified: false,

View File

@@ -11,6 +11,7 @@ export const create = async (
name: string;
slug: string;
createdBy: string;
createdByEmail: string;
},
) => {
const [workspace] = await db
@@ -34,6 +35,7 @@ export const create = async (
await db.insert(workspaceMembers).values({
publicId: generateUID(),
userId: workspaceInput.createdBy,
email: workspaceInput.createdByEmail,
workspaceId: workspace.id,
createdBy: workspaceInput.createdBy,
role: "admin",
@@ -103,6 +105,7 @@ export const getByPublicIdWithMembers = (
members: {
columns: {
publicId: true,
email: true,
role: true,
status: true,
},
@@ -171,6 +174,7 @@ export const getAllByUserId = (db: dbClient, userId: string) => {
},
where: and(
eq(workspaceMembers.userId, userId),
eq(workspaceMembers.status, "active"),
isNull(workspaceMembers.deletedAt),
),
});

View File

@@ -54,9 +54,8 @@ export const workspaceRelations = relations(workspaces, ({ one, many }) => ({
export const workspaceMembers = pgTable("workspace_members", {
id: bigserial("id", { mode: "number" }).primaryKey(),
publicId: varchar("publicId", { length: 12 }).notNull().unique(),
userId: uuid("userId")
.notNull()
.references(() => users.id),
email: varchar("email", { length: 255 }).notNull(),
userId: uuid("userId").references(() => users.id),
workspaceId: bigint("workspaceId", { mode: "number" })
.notNull()
.references(() => workspaces.id, { onDelete: "cascade" }),

9
pnpm-lock.yaml generated
View File

@@ -327,6 +327,9 @@ importers:
pg:
specifier: ^8.11.3
version: 8.13.1
uuid:
specifier: ^11.1.0
version: 11.1.0
zod:
specifier: 'catalog:'
version: 3.24.0
@@ -5740,6 +5743,10 @@ packages:
util@0.12.5:
resolution: {integrity: sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==}
uuid@11.1.0:
resolution: {integrity: sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==}
hasBin: true
uuid@8.0.0:
resolution: {integrity: sha512-jOXGuXZAWdsTH7eZLtyXMqUb9EcWMGZNbL9YcGBJl4MH4nrxHmZJhEHvyLFrkxo+28uLb/NYRcStH48fnD0Vzw==}
hasBin: true
@@ -12106,6 +12113,8 @@ snapshots:
is-typed-array: 1.1.13
which-typed-array: 1.1.16
uuid@11.1.0: {}
uuid@8.0.0: {}
uuid@9.0.1: {}