Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "Invite" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"recipientEmail" TEXT NOT NULL,
"hostUserId" TEXT NOT NULL,
"orgId" INTEGER NOT NULL,

CONSTRAINT "Invite_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Invite_recipientEmail_orgId_key" ON "Invite"("recipientEmail", "orgId");

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_hostUserId_fkey" FOREIGN KEY ("hostUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Invite" ADD CONSTRAINT "Invite_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org"("id") ON DELETE CASCADE ON UPDATE CASCADE;
27 changes: 27 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,6 +83,27 @@ model RepoToConnection {
@@id([connectionId, repoId])
}

model Invite {
/// The globally unique invite id
id String @id @default(cuid())

/// Time of invite creation
createdAt DateTime @default(now())

/// The email of the recipient of the invite
recipientEmail String

/// The user that created the invite
host User @relation(fields: [hostUserId], references: [id], onDelete: Cascade)
hostUserId String

/// The organization the invite is for
org Org @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int

@@unique([recipientEmail, orgId])
}

model Org {
id Int @id @default(autoincrement())
name String
Expand All@@ -92,6 +113,9 @@ model Org {
connections Connection[]
repos Repo[]
secrets Secret[]

/// List of pending invites to this organization
invites Invite[]
}

enum OrgRole {
Expand DownExpand Up@@ -139,6 +163,9 @@ model User {
orgs UserToOrg[]
activeOrgId Int?

/// List of pending invites that the user has created
invites Invite[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand Down
57 changes: 56 additions & 1 deletion packages/web/src/actions.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import { gitlabSchema } from "@sourcebot/schemas/v3/gitlab.schema";
import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type";
import { encrypt } from "@sourcebot/crypto"
import { getConnection } from "./data/connection";
import { Prisma } from "@sourcebot/db";
import { Prisma, Invite } from "@sourcebot/db";

const ajv = new Ajv({
validateFormats: false,
Expand DownExpand Up@@ -301,3 +301,58 @@ const parseConnectionConfig = (connectionType: string, config: string) => {

return parsedConfig;
}

export const createInvite = async (email: string, userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => {
console.log("Creating invite for", email, userId, orgId);

try {
await prisma.invite.create({
data: {
recipientEmail: email,
hostUserId: userId,
orgId,
}
});
} catch (error) {
console.error("Failed to create invite:", error);
return unexpectedError("Failed to create invite");
}

return {
success: true,
}
}

export const redeemInvite = async (invite: Invite, userId: string): Promise<{ orgId: number } | ServiceError> => {
try {
await prisma.userToOrg.create({
data: {
userId,
orgId: invite.orgId,
role: "MEMBER",
}
});

await prisma.user.update({
where: {
id: userId,
},
data: {
activeOrgId: invite.orgId,
}
});

await prisma.invite.delete({
where: {
id: invite.id,
}
});

return {
orgId: invite.orgId,
}
} catch (error) {
console.error("Failed to redeem invite:", error);
return unexpectedError("Failed to redeem invite");
}
}
7 changes: 7 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -70,6 +70,13 @@ export const NavigationMenu = async () => {
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/settings" legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Settings
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenuBase>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/app/connections/page.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@ import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { prisma } from "@/prisma";
import { ConnectionList } from "./components/connectionList";
import { Header } from "./components/header";
import { Header } from "../components/header";
import { NewConnectionCard } from "./components/newConnectionCard";

export default async function ConnectionsPage() {
Expand Down
53 changes: 53 additions & 0 deletions packages/web/src/app/redeem/components/acceptInviteButton.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { redeemInvite } from "../../../actions";
import { isServiceError } from "@/lib/utils"
import { useToast } from "@/components/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Invite } from "@sourcebot/db"

interface AcceptInviteButtonProps {
invite: Invite
userId: string
}

export function AcceptInviteButton({ invite, userId }: AcceptInviteButtonProps) {
const [isLoading, setIsLoading] = useState(false)
const router = useRouter()
const { toast } = useToast()

const handleAcceptInvite = async () => {
setIsLoading(true)
try {
const res = await redeemInvite(invite, userId)
if (isServiceError(res)) {
console.log("Failed to redeem invite: ", res)
toast({
title: "Error",
description: "Failed to redeem invite. Please try again.",
variant: "destructive",
})
} else {
router.push("/")
}
} catch (error) {
console.error("Error redeeming invite:", error)
toast({
title: "Error",
description: "An unexpected error occurred. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}

return (
<Button onClick={handleAcceptInvite} disabled={isLoading}>
{isLoading ? "Accepting..." : "Accept Invite"}
</Button>
)
}

84 changes: 84 additions & 0 deletions packages/web/src/app/redeem/page.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
import { prisma } from "@/prisma";
import { notFound, redirect } from 'next/navigation';
import { NavigationMenu } from "../components/navigationMenu";
import { auth } from "@/auth";
import { getUser } from "@/data/user";
import { AcceptInviteButton } from "./components/acceptInviteButton"

interface RedeemPageProps {
searchParams?: {
invite_id?: string;
};
}

export default async function RedeemPage({ searchParams }: RedeemPageProps) {
const invite_id = searchParams?.invite_id;

if (!invite_id) {
notFound();
}

const invite = await prisma.invite.findUnique({
where: { id: invite_id },
});

if (!invite) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>This invite either expired or was revoked. Contact your organization owner.</h1>
</div>
</div>
);
}

const session = await auth();
let user = undefined;
if (session) {
user = await getUser(session.user.id);
}


// Auth case
if (user) {
if (user.email !== invite.recipientEmail) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Sorry this invite does not belong to you.</h1>
</div>
</div>
)
} else {
const orgName = await prisma.org.findUnique({
where: { id: invite.orgId },
select: { name: true },
});

if (!orgName) {
return (
<div>
<NavigationMenu />
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<h1>Organization not found. Please contact the invite sender.</h1>
</div>
</div>
)
}

return (
<div>
<NavigationMenu />
<div className="flex justify-between items-center h-screen px-6">
<h1 className="text-2xl font-bold">You've been invited to org {orgName.name}</h1>
<AcceptInviteButton invite={invite} userId={user.id} />
</div>
</div>
);
}
} else {
redirect(`/login?callbackUrl=${encodeURIComponent(`/redeem?invite_id=${invite_id}`)}`);
}
}
40 changes: 40 additions & 0 deletions packages/web/src/app/settings/components/inviteTable.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useMemo, useState } from "react";
import { User } from "@sourcebot/db";
import { DataTable } from "@/components/ui/data-table";
import { InviteColumnInfo, inviteTableColumns } from "./inviteTableColumns"

export interface InviteInfo {
id: string;
email: string;
createdAt: Date;
}

interface InviteTableProps {
initialInvites: InviteInfo[];
}

export const InviteTable = ({ initialInvites }: InviteTableProps) => {
const [invites, setInvites] = useState<InviteInfo[]>(initialInvites);

const inviteRows: InviteColumnInfo[] = useMemo(() => {
return invites.map(invite => {
return {
id: invite.id!,
email: invite.email!,
createdAt: invite.createdAt!,
}
})
}, [invites]);

return (
<div>
<DataTable
columns={inviteTableColumns()}
data={inviteRows}
searchKey="email"
searchPlaceholder="Search invites..."
/>
</div>
)
}
49 changes: 49 additions & 0 deletions packages/web/src/app/settings/components/inviteTableColumns.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
'use client'

import { Button } from "@/components/ui/button";
import { ColumnDef } from "@tanstack/react-table"
import { resolveServerPath } from "../../api/(client)/client";
import { createPathWithQueryParams } from "@/lib/utils";

export type InviteColumnInfo = {
id: string;
email: string;
createdAt: Date;
}

export const inviteTableColumns = (): ColumnDef<InviteColumnInfo>[] => {
return [
{
accessorKey: "email",
cell: ({ row }) => {
const invite = row.original;
return <div>{invite.email}</div>;
}
},
{
accessorKey: "createdAt",
cell: ({ row }) => {
const invite = row.original;
return invite.createdAt.toISOString();
}
},
{
accessorKey: "copy",
cell: ({ row }) => {
const invite = row.original;
return (
<Button
variant="link"
onClick={() => {
const basePath = `${window.location.origin}${resolveServerPath('/')}`;
const url = createPathWithQueryParams(`${basePath}redeem?invite_id=${invite.id}`);
navigator.clipboard.writeText(url);
}}
>
Copy
</Button>
)
}
}
]
}
Loading