Skip to content
Draft
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
1 change: 1 addition & 0 deletions packages/app/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ BETTER_AUTH_URL=http://localhost:5173/api/auth
POLAR_ACCESS_TOKEN=your-polar-access-token
POLAR_WEBHOOK_SECRET=your-polar-webhook-secret
POLAR_PRO_PRODUCT_ID=your-polar-pro-product-id
POSTMARK_SERVER_TOKEN=your-postmark-server-token
LOCAL=true
PRODUCT_BETA=false
85 changes: 84 additions & 1 deletion packages/app/api/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const session = sqliteTable("session", {
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
activeOrganizationId: text("active_organization_id"),
});

export const account = sqliteTable("account", {
Expand Down Expand Up @@ -56,6 +57,84 @@ export const verification = sqliteTable("verification", {
updatedAt: integer("updated_at", { mode: "timestamp" }),
});

// ── Organizations ─────────────────────────────────────────────

export const organization = sqliteTable("organization", {
id: text("id").primaryKey(),
name: text("name").notNull(),
slug: text("slug").notNull().unique(),
logo: text("logo"),
metadata: text("metadata"),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
});

export const member = sqliteTable(
"member",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
role: text("role").notNull(),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
},
(t) => [index("member_org_idx").on(t.organizationId)],
);

export const invitation = sqliteTable(
"invitation",
{
id: text("id").primaryKey(),
email: text("email").notNull(),
inviterId: text("inviter_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
role: text("role"),
status: text("status").notNull(),
teamId: text("team_id"),
expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
},
(t) => [index("invitation_org_idx").on(t.organizationId)],
);

// ── Teams ─────────────────────────────────────────────────────

export const team = sqliteTable(
"team",
{
id: text("id").primaryKey(),
name: text("name").notNull(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }),
},
(t) => [index("team_org_idx").on(t.organizationId)],
);

export const teamMember = sqliteTable(
"teamMember",
{
id: text("id").primaryKey(),
teamId: text("team_id")
.notNull()
.references(() => team.id, { onDelete: "cascade" }),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
createdAt: integer("created_at", { mode: "timestamp" }),
},
(t) => [index("team_member_team_idx").on(t.teamId)],
);

// ── Projects ──────────────────────────────────────────────────

export const project = sqliteTable(
Expand All @@ -65,11 +144,15 @@ export const project = sqliteTable(
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
organizationId: text("organization_id").references(() => organization.id, {
onDelete: "cascade",
}),
teamId: text("team_id").references(() => team.id, { onDelete: "set null" }),
name: text("name").notNull(),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
},
(t) => [index("project_user_idx").on(t.userId)],
(t) => [index("project_user_idx").on(t.userId), index("project_org_idx").on(t.organizationId)],
);

// ── Toggles ────────────────────────────────────────────────────
Expand Down
4 changes: 4 additions & 0 deletions packages/app/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { projects } from "./routes/projects";
import { apiKeys } from "./routes/apiKeys";
import { dashboard } from "./routes/dashboard";
import { portal } from "./routes/portal";
import { organizations } from "./routes/organizations";
import type { Bindings, Variables } from "./types";
import { isProduction } from "./utils/isProduction";
import * as schema from "./db/schema";
Expand Down Expand Up @@ -227,4 +228,7 @@ app.route("/api/v1/projects", projects);
// Dashboard
app.route("/api/v1/dashboard", dashboard);

// Organizations
app.route("/api/v1/organizations", organizations);

export default app;
24 changes: 23 additions & 1 deletion packages/app/api/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { Polar } from "@polar-sh/sdk";
import { polar, checkout, portal, webhooks } from "@polar-sh/better-auth";
import * as schema from "../db/schema";
import { isProduction } from "../utils/isProduction";
import { apiKey } from "better-auth/plugins";
import { apiKey, organization } from "better-auth/plugins";
import { sendInvitationEmail } from "./email";
import type { AgnosticDatabaseInstance } from "../types";

type Env = Cloudflare.Env;
Expand All @@ -25,6 +26,11 @@ export function createAuth(env: Env, db: AgnosticDatabaseInstance<typeof schema>
session: schema.session,
account: schema.account,
apikey: schema.apikey,
organization: schema.organization,
member: schema.member,
invitation: schema.invitation,
team: schema.team,
teamMember: schema.teamMember,
},
}),
secret: env.BETTER_AUTH_SECRET,
Expand All @@ -39,6 +45,22 @@ export function createAuth(env: Env, db: AgnosticDatabaseInstance<typeof schema>
apiKey({
enableMetadata: true,
}),
organization({
teams: {
enabled: true,
},
async sendInvitationEmail(data) {
const baseUrl = env.BETTER_AUTH_URL.replace("/api/auth", "");
const inviteUrl = `${baseUrl}/invite/accept?token=${data.id}`;
await sendInvitationEmail({
to: data.email,
inviterName: data.inviter.user.name,
workspaceName: data.organization.name,
inviteUrl,
serverToken: env.POSTMARK_SERVER_TOKEN,
});
},
}),
polar({
client: polarClient,
// We disable automatic customer creation because we want to control when customers are created in Polar
Expand Down
83 changes: 83 additions & 0 deletions packages/app/api/lib/email.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const FROM_ADDRESS = "invites@toggles.tinytown.studio";
const FROM_NAME = "Toggles";

interface InvitationEmailOptions {
to: string;
inviterName: string;
workspaceName: string;
inviteUrl: string;
serverToken: string;
}

export async function sendInvitationEmail({
to,
inviterName,
workspaceName,
inviteUrl,
serverToken,
}: InvitationEmailOptions): Promise<void> {
const response = await fetch("https://api.postmarkapp.com/email", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-Postmark-Server-Token": serverToken,
},
body: JSON.stringify({
From: `${FROM_NAME} <${FROM_ADDRESS}>`,
To: to,
Subject: `${inviterName} invited you to ${workspaceName} on Toggles`,
HtmlBody: buildInvitationHtml({ inviterName, workspaceName, inviteUrl }),
TextBody: buildInvitationText({ inviterName, workspaceName, inviteUrl }),
MessageStream: "outbound",
}),
});

if (!response.ok) {
const body = await response.text();
throw new Error(`Postmark error ${response.status}: ${body}`);
}
}

function buildInvitationHtml({
inviterName,
workspaceName,
inviteUrl,
}: Omit<InvitationEmailOptions, "to" | "serverToken">): string {
return `
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; max-width: 480px; margin: 40px auto; color: #111;">
<h2 style="margin-bottom: 8px;">You've been invited</h2>
<p><strong>${inviterName}</strong> has invited you to join the <strong>${workspaceName}</strong> workspace on Toggles.</p>
<p>
<a href="${inviteUrl}" style="
display: inline-block;
padding: 12px 24px;
background: #111;
color: #fff;
text-decoration: none;
border-radius: 6px;
font-weight: 600;
">Accept invitation</a>
</p>
<p style="color: #666; font-size: 13px;">This invitation expires in 48 hours. If you did not expect this invitation you can ignore this email.</p>
</body>
</html>`.trim();
}

function buildInvitationText({
inviterName,
workspaceName,
inviteUrl,
}: Omit<InvitationEmailOptions, "to" | "serverToken">): string {
return [
`You've been invited to join the ${workspaceName} workspace on Toggles.`,
``,
`${inviterName} sent you this invitation.`,
``,
`Accept your invitation: ${inviteUrl}`,
``,
`This invitation expires in 48 hours. If you did not expect this invitation you can ignore this email.`,
].join("\n");
}
2 changes: 1 addition & 1 deletion packages/app/api/lib/plans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function getUserPlan(
userId: string,
): Promise<Plan> {
const row = await db
.select({ plan: schema.subscription.plan })
.select()
.from(schema.subscription)
.where(eq(schema.subscription.userId, userId))
.get();
Expand Down
Loading
Loading