fix: reenable member invites
This commit is contained in:
@@ -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;
|
||||
}),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
2062
packages/db/migrations/meta/20250522083748_snapshot.json
Normal file
2062
packages/db/migrations/meta/20250522083748_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,13 @@
|
||||
"when": 1746693478656,
|
||||
"tag": "20250508083758_SetupTables",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1747903068807,
|
||||
"tag": "20250522083748_AddEmailToWorkspaceMembers",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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": {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -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" }),
|
||||
|
||||
Reference in New Issue
Block a user