Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Implement 'Get My Organizations' API endpoint and update documentation

Bill Yangbc0b89180c53
diff --git a/docs/content/docs/api/organizations.mdx b/docs/content/docs/api/organizations.mdx
index ebf3fb05e..22c669b01 100644
--- a/docs/content/docs/api/organizations.mdx
+++ b/docs/content/docs/api/organizations.mdx
@@ -12,6 +12,10 @@ See the [API Reference](/docs/api/getting-started) for authentication details.
## Endpoints
<div className="flex flex-col gap-2 my-6">
+ <a href="#get-my-organizations" className="flex items-center gap-3 p-3 rounded-lg bg-fd-secondary/50 hover:bg-fd-secondary transition-colors no-underline">
+ <span className="px-2 py-1 text-xs font-bold rounded bg-green-500/20 text-green-600 dark:text-green-400">GET</span>
+ <code className="text-sm">/api/organizations</code>
+ </a>
<a href="#get-organization-sites" className="flex items-center gap-3 p-3 rounded-lg bg-fd-secondary/50 hover:bg-fd-secondary transition-colors no-underline">
<span className="px-2 py-1 text-xs font-bold rounded bg-green-500/20 text-green-600 dark:text-green-400">GET</span>
<code className="text-sm">/api/organizations/:organizationId/sites</code>
@@ -32,6 +36,294 @@ See the [API Reference](/docs/api/getting-started) for authentication details.
---
+## Get My Organizations
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/organizations
+```
+
+Returns all organizations the authenticated user is a member of, including all members for each organization. Excludes subscription and billing information. Supports both session cookies and API key (Bearer token) authentication.
+
+### Response
+
+Returns an array of organization objects.
+
+<TypeTable
+ type={{
+ id: {
+ description: 'Organization ID',
+ type: 'string',
+ },
+ name: {
+ description: 'Organization name',
+ type: 'string',
+ },
+ slug: {
+ description: 'Organization slug',
+ type: 'string',
+ },
+ logo: {
+ description: 'Organization logo URL',
+ type: 'string | null',
+ },
+ createdAt: {
+ description: 'Organization creation timestamp',
+ type: 'string',
+ typeDescription: 'ISO 8601 datetime',
+ },
+ role: {
+ description: 'Your role in the organization',
+ type: 'string',
+ typeDescription: '"owner" | "admin" | "member"',
+ },
+ members: {
+ description: 'Array of organization members',
+ type: 'array',
+ },
+ }}
+/>
+
+#### Member Object
+
+Each member in the `members` array contains:
+
+<TypeTable
+ type={{
+ id: {
+ description: 'Member record ID',
+ type: 'string',
+ },
+ role: {
+ description: 'Member role in the organization',
+ type: 'string',
+ typeDescription: '"owner" | "admin" | "member"',
+ },
+ userId: {
+ description: 'User ID',
+ type: 'string',
+ },
+ createdAt: {
+ description: 'Timestamp when member was added',
+ type: 'string',
+ typeDescription: 'ISO 8601 datetime',
+ },
+ user: {
+ description: 'User details',
+ type: 'object',
+ },
+ }}
+/>
+
+#### User Object
+
+<TypeTable
+ type={{
+ id: {
+ description: 'User ID',
+ type: 'string',
+ },
+ name: {
+ description: 'User display name',
+ type: 'string',
+ },
+ email: {
+ description: 'User email address',
+ type: 'string',
+ },
+ }}
+/>
+
+</div>
+<div className="flex flex-col gap-4">
+
+<Tabs items={['cURL', 'JavaScript', 'Python', 'PHP', 'Ruby', 'Go', 'Rust', 'Java', '.NET']}>
+ <Tab value="cURL">
+```bash title="Request"
+curl -X GET "https://api.rybbit.io/api/organizations" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://api.rybbit.io/api/organizations',
+ {
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.get(
+ 'https://api.rybbit.io/api/organizations',
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, "https://api.rybbit.io/api/organizations");
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here'
+]);
+
+$response = curl_exec($ch);
+curl_close($ch);
+
+$data = json_decode($response, true);
+```
+ </Tab>
+ <Tab value="Ruby">
+```ruby title="Request"
+require 'net/http'
+require 'json'
+
+uri = URI('https://api.rybbit.io/api/organizations')
+req = Net::HTTP::Get.new(uri)
+req['Authorization'] = 'Bearer your_api_key_here'
+
+res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
+data = JSON.parse(res.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+req, _ := http.NewRequest("GET", "https://api.rybbit.io/api/organizations", nil)
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+
+client := &http.Client{}
+resp, _ := client.Do(req)
+defer resp.Body.Close()
+
+var data []map[string]interface{}
+json.NewDecoder(resp.Body).Decode(&data)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let client = reqwest::Client::new();
+let res = client
+ .get("https://api.rybbit.io/api/organizations")
+ .header("Authorization", "Bearer your_api_key_here")
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://api.rybbit.io/api/organizations"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .GET()
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var response = await client.GetAsync("https://api.rybbit.io/api/organizations");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+[
+ {
+ "id": "org_123",
+ "name": "Acme Inc",
+ "slug": "acme-inc",
+ "logo": "https://example.com/logo.png",
+ "createdAt": "2024-01-15T10:30:00.000Z",
+ "role": "owner",
+ "members": [
+ {
+ "id": "member_abc123",
+ "role": "owner",
+ "userId": "user_xyz789",
+ "createdAt": "2024-01-15T10:30:00.000Z",
+ "user": {
+ "id": "user_xyz789",
+ "name": "John Doe",
+ "email": "[email protected]"
+ }
+ },
+ {
+ "id": "member_def456",
+ "role": "member",
+ "userId": "user_abc456",
+ "createdAt": "2024-02-20T14:15:00.000Z",
+ "user": {
+ "id": "user_abc456",
+ "name": "Jane Smith",
+ "email": "[email protected]"
+ }
+ }
+ ]
+ },
+ {
+ "id": "org_456",
+ "name": "Tech Startup",
+ "slug": "tech-startup",
+ "logo": null,
+ "createdAt": "2024-03-10T08:00:00.000Z",
+ "role": "admin",
+ "members": [
+ {
+ "id": "member_ghi789",
+ "role": "owner",
+ "userId": "user_owner123",
+ "createdAt": "2024-03-10T08:00:00.000Z",
+ "user": {
+ "id": "user_owner123",
+ "name": "Alice Johnson",
+ "email": "[email protected]"
+ }
+ },
+ {
+ "id": "member_jkl012",
+ "role": "admin",
+ "userId": "user_xyz789",
+ "createdAt": "2024-03-12T09:30:00.000Z",
+ "user": {
+ "id": "user_xyz789",
+ "name": "John Doe",
+ "email": "[email protected]"
+ }
+ }
+ ]
+ }
+]
+```
+
+</div>
+</div>
+
+---
+
## Get Organization Sites
<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
diff --git a/server/src/api/user/getMyOrganizations.ts b/server/src/api/user/getMyOrganizations.ts
new file mode 100644
index 000000000..682c40db1
--- /dev/null
+++ b/server/src/api/user/getMyOrganizations.ts
@@ -0,0 +1,74 @@
+import { FastifyRequest, FastifyReply } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { eq } from "drizzle-orm";
+import { member, organization, user } from "../../db/postgres/schema.js";
+import { getUserIdFromRequest } from "../../lib/auth-utils.js";
+
+export const getMyOrganizations = async (request: FastifyRequest, reply: FastifyReply) => {
+ try {
+ const userId = await getUserIdFromRequest(request);
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // First, get all organizations the user is a member of
+ const userOrganizations = await db
+ .select({
+ id: organization.id,
+ name: organization.name,
+ slug: organization.slug,
+ logo: organization.logo,
+ createdAt: organization.createdAt,
+ role: member.role,
+ })
+ .from(member)
+ .innerJoin(organization, eq(member.organizationId, organization.id))
+ .where(eq(member.userId, userId));
+
+ // For each organization, get all members with user details
+ const organizationsWithMembers = await Promise.all(
+ userOrganizations.map(async org => {
+ const organizationMembers = await db
+ .select({
+ id: member.id,
+ role: member.role,
+ userId: member.userId,
+ organizationId: member.organizationId,
+ createdAt: member.createdAt,
+ // User fields
+ userName: user.name,
+ userEmail: user.email,
+ userActualId: user.id,
+ })
+ .from(member)
+ .leftJoin(user, eq(member.userId, user.id))
+ .where(eq(member.organizationId, org.id));
+
+ return {
+ id: org.id,
+ name: org.name,
+ slug: org.slug,
+ logo: org.logo,
+ createdAt: org.createdAt,
+ role: org.role,
+ members: organizationMembers.map(m => ({
+ id: m.id,
+ role: m.role,
+ userId: m.userId,
+ createdAt: m.createdAt,
+ user: {
+ id: m.userActualId,
+ name: m.userName,
+ email: m.userEmail,
+ },
+ })),
+ };
+ })
+ );
+
+ return reply.send(organizationsWithMembers);
+ } catch (error) {
+ console.error("Error fetching organizations with members:", error);
+ return reply.status(500).send({ error: "Failed to fetch organizations" });
+ }
+};
diff --git a/server/src/api/user/index.ts b/server/src/api/user/index.ts
index cc2c81fef..c02f957e9 100644
--- a/server/src/api/user/index.ts
+++ b/server/src/api/user/index.ts
@@ -1,6 +1,7 @@
// Organization Management
export { addUserToOrganization } from "./addUserToOrganization.js";
export { getUserOrganizations } from "./getUserOrganizations.js";
+export { getMyOrganizations } from "./getMyOrganizations.js";
export { listOrganizationMembers } from "./listOrganizationMembers.js";
// Account Settings
diff --git a/server/src/index.ts b/server/src/index.ts
index 89e9b8d93..29b158960 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -91,6 +91,7 @@ import {
addUserToOrganization,
createApiKey,
deleteApiKey,
+ getMyOrganizations,
getUserOrganizations,
listApiKeys,
listOrganizationMembers,
@@ -312,6 +313,7 @@ async function sitesRoutes(fastify: FastifyInstance) {
async function organizationsRoutes(fastify: FastifyInstance) {
// Organizations
+ fastify.get("/organizations", authOnly, getMyOrganizations);
fastify.get("/organizations/:organizationId/sites", orgMember, getSitesFromOrg);
fastify.post("/organizations/:organizationId/sites", orgAdminParams, addSite);
fastify.get("/organizations/:organizationId/members", orgMember, listOrganizationMembers);
diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.ts
index 4d8661de7..b7fb64462 100644
--- a/server/src/lib/auth-utils.ts
+++ b/server/src/lib/auth-utils.ts
@@ -167,6 +167,36 @@ export async function checkApiKey(
return { valid: false, role: null };
}
+export async function getUserIdFromRequest(req: FastifyRequest): Promise<string | null> {
+ // First, check for session-based auth
+ const session = await getSessionFromReq(req);
+ if (session?.user?.id) {
+ return session.user.id;
+ }
+
+ // Fall back to API key auth
+ const authHeader = req.headers["authorization"];
+ const bearerToken =
+ authHeader && typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.substring(7) : null;
+ const queryApiKey = (req.query as any)?.api_key;
+ const apiKey = bearerToken || queryApiKey;
+
+ if (apiKey && typeof apiKey === "string") {
+ try {
+ const result = await auth.api.verifyApiKey({
+ body: { key: apiKey },
+ });
+ if (result.valid && result.key?.userId) {
+ return result.key.userId;
+ }
+ } catch (error) {
+ logger.error(error, "Error verifying API key");
+ }
+ }
+
+ return null;
+}
+
// for routes that are potentially public
export async function getUserHasAccessToSitePublic(req: FastifyRequest, siteId: string | number) {
const [userSites, config] = await Promise.all([getSitesUserHasAccessTo(req), siteConfig.getConfig(siteId)]);