Skip to content

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

Refactor AccountInner and Organization components for improved readab… (#484)

Bill Yangc306cab025fe
diff --git a/client/package.json b/client/package.json
index 8f89d5a09..c279a4739 100644
--- a/client/package.json
+++ b/client/package.json
@@ -1,6 +1,6 @@
{
"name": "client",
- "version": "1.4.2",
+ "version": "1.5.0",
"private": true,
"scripts": {
"dev": "next dev -p 3002 --turbopack",
diff --git a/client/src/api/admin/organizations.ts b/client/src/api/admin/organizations.ts
index d5e81c39b..90a3e9578 100644
--- a/client/src/api/admin/organizations.ts
+++ b/client/src/api/admin/organizations.ts
@@ -16,9 +16,11 @@ function getUserOrganizations(): Promise<UserOrganization[]> {
return authedFetch("/user/organizations");
}
+export const USER_ORGANIZATIONS_QUERY_KEY = "userOrganizations";
+
export function useUserOrganizations() {
return useQuery({
- queryKey: ["userOrganizations"],
+ queryKey: [USER_ORGANIZATIONS_QUERY_KEY],
queryFn: getUserOrganizations,
});
}
diff --git a/client/src/app/account/components/AccountInner.tsx b/client/src/app/account/components/AccountInner.tsx
index dc6f269d5..ed17e8fef 100644
--- a/client/src/app/account/components/AccountInner.tsx
+++ b/client/src/app/account/components/AccountInner.tsx
@@ -4,21 +4,13 @@ import { authClient } from "@/lib/auth";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from "../../../components/ui/card";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
import { Input } from "../../../components/ui/input";
import { ChangePassword } from "./ChangePassword";
import { DeleteAccount } from "./DeleteAccount";
+import { validateEmail } from "../../../lib/auth-utils";
-export function AccountInner({
- session,
-}: {
- session: ReturnType<typeof authClient.useSession>;
-}) {
+export function AccountInner({ session }: { session: ReturnType<typeof authClient.useSession> }) {
const [email, setEmail] = useState(session.data?.user.email ?? "");
const [name, setName] = useState(session.data?.user.name ?? "");
const [isUpdatingEmail, setIsUpdatingEmail] = useState(false);
@@ -44,9 +36,7 @@ export function AccountInner({
globalThis.location.reload();
} catch (error) {
console.error("Error updating name:", error);
- toast.error(
- error instanceof Error ? error.message : "Failed to update name"
- );
+ toast.error(error instanceof Error ? error.message : "Failed to update name");
} finally {
setIsUpdatingName(false);
}
@@ -58,7 +48,7 @@ export function AccountInner({
return;
}
- if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
+ if (!validateEmail(email)) {
toast.error("Please enter a valid email address");
return;
}
@@ -79,9 +69,7 @@ export function AccountInner({
globalThis.location.reload();
} catch (error) {
console.error("Error updating email:", error);
- toast.error(
- error instanceof Error ? error.message : "Failed to update email"
- );
+ toast.error(error instanceof Error ? error.message : "Failed to update email");
} finally {
setIsUpdatingEmail(false);
}
@@ -96,16 +84,9 @@ export function AccountInner({
<CardContent className="space-y-6">
<div className="space-y-2">
<h4 className="text-sm font-medium">Name</h4>
- <p className="text-xs text-neutral-500">
- Update your name displayed across the platform
- </p>
+ <p className="text-xs text-neutral-500">Update your name displayed across the platform</p>
<div className="flex space-x-2">
- <Input
- id="name"
- value={name}
- onChange={({ target }) => setName(target.value)}
- placeholder="name"
- />
+ <Input id="name" value={name} onChange={({ target }) => setName(target.value)} placeholder="name" />
<Button
variant="outline"
onClick={handleNameUpdate}
@@ -117,9 +98,7 @@ export function AccountInner({
</div>
<div className="space-y-2">
<h4 className="text-sm font-medium">Email</h4>
- <p className="text-xs text-neutral-500">
- Update your email address for account notifications
- </p>
+ <p className="text-xs text-neutral-500">Update your email address for account notifications</p>
<div className="flex space-x-2">
<Input
id="email"
@@ -147,9 +126,7 @@ export function AccountInner({
<CardContent className="space-y-6">
<div className="space-y-2">
<h4 className="text-sm font-medium">Password</h4>
- <p className="text-xs text-neutral-500">
- Change your account password
- </p>
+ <p className="text-xs text-neutral-500">Change your account password</p>
<div className="w-[200px]">
<ChangePassword />
</div>
@@ -157,9 +134,7 @@ export function AccountInner({
<div className="space-y-2">
<h4 className="text-sm font-medium text-red-500">Danger Zone</h4>
- <p className="text-xs text-neutral-500">
- Permanently delete your account and all associated data
- </p>
+ <p className="text-xs text-neutral-500">Permanently delete your account and all associated data</p>
<div className="w-[200px]">
<DeleteAccount />
</div>
diff --git a/client/src/app/organization/layout.tsx b/client/src/app/organization/layout.tsx
index a3b139c93..66abd2880 100644
--- a/client/src/app/organization/layout.tsx
+++ b/client/src/app/organization/layout.tsx
@@ -1,24 +1,22 @@
"use client";
-import { StandardPage } from "../../components/StandardPage";
+import { CreditCard, Users } from "lucide-react";
+import { usePathname, useRouter } from "next/navigation";
+import { useState } from "react";
+import { CreateOrganizationDialog } from "../../components/CreateOrganizationDialog";
import { OrganizationSelector } from "../../components/OrganizationSelector";
+import { StandardPage } from "../../components/StandardPage";
+import { Button } from "../../components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "../../components/ui/tabs";
-import { useRouter, usePathname } from "next/navigation";
-import { Users, CreditCard } from "lucide-react";
import { IS_CLOUD } from "../../lib/const";
-export default function OrganizationLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default function OrganizationLayout({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
+ const [createOrgDialogOpen, setCreateOrgDialogOpen] = useState(false);
// Determine active tab from pathname
- const activeTab = pathname.includes("/subscription")
- ? "subscription"
- : "members";
+ const activeTab = pathname.includes("/subscription") ? "subscription" : "members";
const handleTabChange = (value: string) => {
if (value === "members") {
@@ -32,15 +30,18 @@ export default function OrganizationLayout({
<StandardPage>
<div className="space-y-6">
<div>
- <h1 className="text-3xl font-bold tracking-tight">
- Organization Settings
- </h1>
- <p className="text-gray-500 dark:text-gray-400">
- Manage your organization settings and members
- </p>
+ <h1 className="text-3xl font-bold tracking-tight">Organization Settings</h1>
+ <p className="text-gray-500 dark:text-gray-400">Manage your organization settings and members</p>
</div>
- <OrganizationSelector />
+ <div className="flex items-center gap-2">
+ <OrganizationSelector />
+ <CreateOrganizationDialog
+ open={createOrgDialogOpen}
+ onOpenChange={setCreateOrgDialogOpen}
+ trigger={<Button>New Organization</Button>}
+ />
+ </div>
<Tabs value={activeTab} onValueChange={handleTabChange}>
<TabsList>
@@ -49,10 +50,7 @@ export default function OrganizationLayout({
Members
</TabsTrigger>
{IS_CLOUD && (
- <TabsTrigger
- value="subscription"
- className="flex items-center gap-2"
- >
+ <TabsTrigger value="subscription" className="flex items-center gap-2">
<CreditCard size={16} />
Subscription
</TabsTrigger>
diff --git a/client/src/app/organization/members/components/CreateUserDialog.tsx b/client/src/app/organization/members/components/CreateUserDialog.tsx
new file mode 100644
index 000000000..df5bf1afd
--- /dev/null
+++ b/client/src/app/organization/members/components/CreateUserDialog.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { UserPlus } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Alert } from "../../../../components/ui/alert";
+import { authClient } from "../../../../lib/auth";
+import { authedFetch } from "../../../../api/utils";
+import { validateEmail } from "../../../../lib/auth-utils";
+
+interface CreateUserDialogProps {
+ organizationId: string;
+ onSuccess: () => void;
+}
+
+export function CreateUserDialog({ organizationId, onSuccess }: CreateUserDialogProps) {
+ const [email, setEmail] = useState("");
+ const [name, setName] = useState("");
+ const [password, setPassword] = useState("");
+ const [role, setRole] = useState<"admin" | "member">("member");
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [open, setOpen] = useState(false);
+ const [error, setError] = useState("");
+
+ const resetState = (open = false) => {
+ setOpen(open);
+ setError("");
+ setEmail("");
+ setName("");
+ setPassword("");
+ setRole("member");
+ };
+
+ const handleInvite = async () => {
+ if (!email) {
+ setError("Email is required");
+ return;
+ }
+
+ if (!validateEmail(email)) {
+ setError("Please enter a valid email address");
+ return;
+ }
+
+ if (password.length < 8) {
+ setError("Password must be at least 8 characters long");
+ return;
+ }
+
+ setIsLoading(true);
+ try {
+ await authClient.admin.createUser({
+ email,
+ name: name || email,
+ password,
+ });
+
+ await authedFetch("/add-user-to-organization", undefined, {
+ method: "POST",
+ data: {
+ email,
+ role,
+ organizationId,
+ },
+ });
+
+ toast.success(`User created successfully`);
+ onSuccess();
+ resetState();
+ } catch (error: any) {
+ setError(error.message || "Failed to create user");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={resetState}>
+ <DialogTrigger asChild>
+ <Button size="sm" variant="outline">
+ <UserPlus className="h-4 w-4 mr-1" />
+ Create User
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Create a new user</DialogTitle>
+ <DialogDescription>Create a new user for this organization.</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-4">
+ <div className="grid gap-2">
+ <Label htmlFor="email">Email</Label>
+ <Input
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ value={email}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="name">Name</Label>
+ <Input
+ id="name"
+ type="text"
+ placeholder="John Doe"
+ value={name}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="password">Password</Label>
+ <Input
+ id="password"
+ type="password"
+ placeholder="********"
+ value={password}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="role">Role</Label>
+ <Select value={role} onValueChange={(value) => setRole(value as "admin" | "member")}>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a role" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="admin">Admin</SelectItem>
+ <SelectItem value="member">Member</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ {error && <Alert variant="destructive">{error}</Alert>}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => resetState(false)}>
+ Cancel
+ </Button>
+ <Button onClick={handleInvite} disabled={isLoading} variant="success">
+ {isLoading ? "Inviting..." : "Invite"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx b/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
index bba951d85..24c541f39 100644
--- a/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
+++ b/client/src/app/organization/members/components/DeleteOrganizationDialog.tsx
@@ -14,19 +14,19 @@ import { AlertTriangle, Trash } from "lucide-react";
import { authClient } from "@/lib/auth";
import { toast } from "sonner";
import { Organization } from "../page";
+import { USER_ORGANIZATIONS_QUERY_KEY } from "../../../../api/admin/organizations";
+import { useQueryClient } from "@tanstack/react-query";
interface DeleteOrganizationDialogProps {
organization: Organization;
onSuccess: () => void;
}
-export function DeleteOrganizationDialog({
- organization,
- onSuccess,
-}: DeleteOrganizationDialogProps) {
+export function DeleteOrganizationDialog({ organization, onSuccess }: DeleteOrganizationDialogProps) {
const [isLoading, setIsLoading] = useState(false);
const [open, setOpen] = useState(false);
const [confirmText, setConfirmText] = useState("");
+ const queryClient = useQueryClient();
const handleDelete = async () => {
if (confirmText !== organization.name) {
@@ -41,6 +41,10 @@ export function DeleteOrganizationDialog({
});
toast.success("Organization deleted successfully");
+ queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });
+ authClient.organization.setActive({
+ organizationId: null,
+ });
setOpen(false);
onSuccess();
} catch (error: any) {
@@ -60,13 +64,12 @@ export function DeleteOrganizationDialog({
</DialogTrigger>
<DialogContent className="max-w-lg">
<DialogHeader>
- <DialogTitle className="text-destructive flex items-center gap-2">
+ <DialogTitle className="text-red-400 flex items-center gap-2">
<AlertTriangle className="h-5 w-5" />
Delete Organization
</DialogTitle>
<DialogDescription>
- This action cannot be undone. This will permanently delete the
- organization and remove all associated data.
+ This action cannot be undone. This will permanently delete the organization and remove all associated data.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
@@ -75,9 +78,7 @@ export function DeleteOrganizationDialog({
</p>
<Input
value={confirmText}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
- setConfirmText(e.target.value)
- }
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setConfirmText(e.target.value)}
placeholder={organization.name}
/>
</div>
diff --git a/client/src/app/organization/members/components/RemoveMemberDialog.tsx b/client/src/app/organization/members/components/RemoveMemberDialog.tsx
index 2ced5cff4..51526076a 100644
--- a/client/src/app/organization/members/components/RemoveMemberDialog.tsx
+++ b/client/src/app/organization/members/components/RemoveMemberDialog.tsx
@@ -1,16 +1,18 @@
"use client";
-import { useState } from "react";
import { Button } from "@/components/ui/button";
-import { Dialog } from "@/components/ui/dialog";
-import { DialogContent } from "@/components/ui/dialog";
-import { DialogHeader } from "@/components/ui/dialog";
-import { DialogTitle } from "@/components/ui/dialog";
-import { DialogTrigger } from "@/components/ui/dialog";
-import { DialogFooter } from "@/components/ui/dialog";
-import { DialogDescription } from "@/components/ui/dialog";
-import { UserMinus } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
import { authClient } from "@/lib/auth";
+import { UserMinus } from "lucide-react";
+import { useState } from "react";
import { toast } from "sonner";
import { Member } from "../page";
@@ -20,11 +22,7 @@ interface RemoveMemberDialogProps {
onSuccess: () => void;
}
-export function RemoveMemberDialog({
- member,
- organizationId,
- onSuccess,
-}: RemoveMemberDialogProps) {
+export function RemoveMemberDialog({ member, organizationId, onSuccess }: RemoveMemberDialogProps) {
const [isLoading, setIsLoading] = useState(false);
const [open, setOpen] = useState(false);
@@ -58,19 +56,14 @@ export function RemoveMemberDialog({
<DialogHeader>
<DialogTitle>Remove Member</DialogTitle>
<DialogDescription>
- Are you sure you want to remove {member.user.name} from the
- organization?
+ Are you sure you want to remove {member.user.name} from the organization?
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
- <Button
- variant="destructive"
- onClick={handleRemove}
- disabled={isLoading}
- >
+ <Button variant="destructive" onClick={handleRemove} disabled={isLoading}>
{isLoading ? "Removing..." : "Remove Member"}
</Button>
</DialogFooter>
diff --git a/client/src/app/organization/members/page.tsx b/client/src/app/organization/members/page.tsx
index d4d1603a1..50057b9bd 100644
--- a/client/src/app/organization/members/page.tsx
+++ b/client/src/app/organization/members/page.tsx
@@ -1,19 +1,7 @@
"use client";
import { DateTime } from "luxon";
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
-} from "../../../components/ui/card";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "../../../components/ui/table";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../components/ui/table";
import { authClient } from "../../../lib/auth";
import { useOrganizationMembers } from "../../../api/admin/auth";
@@ -25,6 +13,8 @@ import { EditOrganizationDialog } from "./components/EditOrganizationDialog";
import { DeleteOrganizationDialog } from "./components/DeleteOrganizationDialog";
import { RemoveMemberDialog } from "./components/RemoveMemberDialog";
import { Invitations } from "./components/Invitations";
+import { IS_CLOUD } from "../../../lib/const";
+import { CreateUserDialog } from "./components/CreateUserDialog";
// Types for our component
export type Organization = {
@@ -59,17 +49,11 @@ function Organization({
createdAt: Date;
};
}) {
- const {
- data: members,
- refetch,
- isLoading: membersLoading,
- } = useOrganizationMembers(org.id);
+ const { data: members, refetch, isLoading: membersLoading } = useOrganizationMembers(org.id);
const { refetch: refetchInvitations } = useOrganizationInvitations(org.id);
const { data } = authClient.useSession();
- const isOwner = members?.data.find(
- (member) => member.role === "owner" && member.userId === data?.user?.id
- );
+ const isOwner = members?.data.find((member) => member.role === "owner" && member.userId === data?.user?.id);
const handleRefresh = () => {
refetch();
@@ -86,18 +70,13 @@ function Organization({
<div className="flex items-center gap-2">
{isOwner && (
<>
- <InviteMemberDialog
- organizationId={org.id}
- onSuccess={handleRefresh}
- />
- <EditOrganizationDialog
- organization={org}
- onSuccess={handleRefresh}
- />
- <DeleteOrganizationDialog
- organization={org}
- onSuccess={handleRefresh}
- />
+ {IS_CLOUD ? (
+ <InviteMemberDialog organizationId={org.id} onSuccess={handleRefresh} />
+ ) : (
+ <CreateUserDialog organizationId={org.id} onSuccess={handleRefresh} />
+ )}
+ <EditOrganizationDialog organization={org} onSuccess={handleRefresh} />
+ <DeleteOrganizationDialog organization={org} onSuccess={handleRefresh} />
</>
)}
</div>
@@ -144,9 +123,7 @@ function Organization({
<TableRow key={member.id}>
<TableCell>{member.user?.name || "—"}</TableCell>
<TableCell>{member.user?.email}</TableCell>
- <TableCell className="capitalize">
- {member.role}
- </TableCell>
+ <TableCell className="capitalize">{member.role}</TableCell>
<TableCell>
{DateTime.fromSQL(member.createdAt, { zone: "utc" })
.toLocal()
@@ -155,11 +132,7 @@ function Organization({
{isOwner && (
<TableCell className="text-right">
{member.role !== "owner" && (
- <RemoveMemberDialog
- member={member}
- organizationId={org.id}
- onSuccess={handleRefresh}
- />
+ <RemoveMemberDialog member={member} organizationId={org.id} onSuccess={handleRefresh} />
)}
</TableCell>
)}
@@ -167,10 +140,7 @@ function Organization({
))}
{(!members?.data || members.data.length === 0) && (
<TableRow>
- <TableCell
- colSpan={isOwner ? 5 : 4}
- className="text-center py-6 text-muted-foreground"
- >
+ <TableCell colSpan={isOwner ? 5 : 4} className="text-center py-6 text-muted-foreground">
No members found
</TableCell>
</TableRow>
@@ -190,8 +160,7 @@ function Organization({
// Main Organizations component
export default function MembersPage() {
useSetPageTitle("Rybbit · Organization Members");
- const { data: activeOrganization, isPending } =
- authClient.useActiveOrganization();
+ const { data: activeOrganization, isPending } = authClient.useActiveOrganization();
if (isPending) {
return (
diff --git a/client/src/app/signup/page.tsx b/client/src/app/signup/page.tsx
index 48f824da7..5e76472e5 100644
--- a/client/src/app/signup/page.tsx
+++ b/client/src/app/signup/page.tsx
@@ -9,16 +9,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { motion } from "framer-motion";
-import {
- AppWindow,
- ArrowLeft,
- ArrowRight,
- Building2,
- Check,
- Code,
- Sparkles,
- User,
-} from "lucide-react";
+import { AppWindow, ArrowLeft, ArrowRight, Building2, Check, Code, Sparkles, User } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
@@ -90,8 +81,7 @@ export default function SignupPage() {
// Validate domain
const isValidDomain = (domain: string): boolean => {
- const domainRegex =
- /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
+ const domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
return domainRegex.test(domain);
};
@@ -167,20 +157,14 @@ export default function SignupPage() {
try {
// Validate domain
if (!isValidDomain(domain)) {
- setError(
- "Invalid domain format. Must be a valid domain like example.com or sub.example.com"
- );
+ setError("Invalid domain format. Must be a valid domain like example.com or sub.example.com");
setIsLoading(false);
return;
}
try {
const normalizedDomain = normalizeDomain(domain);
- const response = await addSite(
- normalizedDomain,
- normalizedDomain,
- organizationId
- );
+ const response = await addSite(normalizedDomain, normalizedDomain, organizationId);
setSiteId(response.siteId);
setCurrentStep(4);
} catch (error) {
@@ -214,11 +198,7 @@ export default function SignupPage() {
switch (currentStep) {
case 1:
return (
- <motion.div
- initial="hidden"
- animate="visible"
- variants={contentVariants}
- >
+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>
<h2 className="text-2xl font-semibold mb-6">Create your account</h2>
<div className="space-y-4">
<AuthInput
@@ -277,11 +257,7 @@ export default function SignupPage() {
);
case 2:
return (
- <motion.div
- initial="hidden"
- animate="visible"
- variants={contentVariants}
- >
+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>
<h2 className="text-2xl font-semibold mb-6 flex items-center gap-2">
<Building2 className="h-6 w-6 text-emerald-500" />
Create your organization
@@ -300,7 +276,7 @@ export default function SignupPage() {
/>
</div>
- <div className="space-y-2">
+ {/* <div className="space-y-2">
<Label htmlFor="orgSlug">Organization Slug</Label>
<Input
id="orgSlug"
@@ -318,7 +294,7 @@ export default function SignupPage() {
required
className="h-10 transition-all bg-neutral-800/50 border-neutral-700"
/>
- </div>
+ </div> */}
<div className="flex flex-col gap-4 pt-4">
<Button
@@ -330,10 +306,7 @@ export default function SignupPage() {
Continue
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
- <Button
- className="w-full transition-all duration-300 h-11"
- onClick={() => router.push("/")}
- >
+ <Button className="w-full transition-all duration-300 h-11" onClick={() => router.push("/")}>
I'm joining someone else's organization
</Button>
</div>
@@ -342,11 +315,7 @@ export default function SignupPage() {
);
case 3:
return (
- <motion.div
- initial="hidden"
- animate="visible"
- variants={contentVariants}
- >
+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>
<h2 className="text-2xl font-semibold mb-6 flex items-center gap-2">
<AppWindow className="h-6 w-6 text-emerald-500" />
Add your first website
@@ -363,9 +332,7 @@ export default function SignupPage() {
required
className="h-10 transition-all bg-neutral-800/50 border-neutral-700"
/>
- <p className="text-xs text-muted-foreground">
- Enter the domain of the website you want to track
- </p>
+ <p className="text-xs text-muted-foreground">Enter the domain of the website you want to track</p>
</div>
<div className="flex justify-between pt-4">
@@ -384,11 +351,7 @@ export default function SignupPage() {
);
case 4:
return (
- <motion.div
- initial="hidden"
- animate="visible"
- variants={contentVariants}
- >
+ <motion.div initial="hidden" animate="visible" variants={contentVariants}>
<h2 className="text-2xl font-semibold mb-6 flex items-center gap-2">
<Code className="h-6 w-6 text-emerald-500" />
Add tracking code to your website
@@ -399,20 +362,15 @@ export default function SignupPage() {
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-emerald-600 text-primary-foreground">
<Check className="h-4 w-4" />
</div>
- <p className="text-base font-medium">
- Your account is ready!
- </p>
+ <p className="text-base font-medium">Your account is ready!</p>
</div>
<p className="text-sm text-muted-foreground ml-11">
- To start collecting analytics data, add this tracking code to
- your website.
+ To start collecting analytics data, add this tracking code to your website.
</p>
</div>
<div className="flex flex-col gap-2">
- <Label>
- Place this snippet in the &lt;head&gt; of your website
- </Label>
+ <Label>Place this snippet in the &lt;head&gt; of your website</Label>
<div className="border border-neutral-700 rounded-lg overflow-hidden">
<CodeSnippet
language="HTML"
@@ -423,8 +381,7 @@ export default function SignupPage() {
<div className="rounded-lg bg-muted p-4 border border-neutral-700 backdrop-blur-sm bg-neutral-800/20">
<p className="text-sm text-muted-foreground">
- Once you've added the tracking code, it may take a few minutes
- for data to appear in your dashboard.
+ Once you've added the tracking code, it may take a few minutes for data to appear in your dashboard.
</p>
</div>
@@ -468,15 +425,12 @@ export default function SignupPage() {
<Card className="w-full max-w-sm p-1">
<CardHeader>
<Image src="/rybbit.svg" alt="Rybbit" width={32} height={32} />
- <CardTitle className="text-2xl flex justify-center">
- Sign Up Disabled
- </CardTitle>
+ <CardTitle className="text-2xl flex justify-center">Sign Up Disabled</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-6">
<p className="text-center">
- New account registration is currently disabled. If you have an
- account, you can{" "}
+ New account registration is currently disabled. If you have an account, you can{" "}
<Link href="/login" className="underline">
sign in
</Link>
@@ -518,12 +472,7 @@ export default function SignupPage() {
</div>
<div className="relative z-10 flex flex-col space-y-4">
<a href="https://rybbit.io" target="_blank">
- <Image
- src="/rybbit-text.svg"
- alt="Rybbit"
- width={120}
- height={27}
- />
+ <Image src="/rybbit-text.svg" alt="Rybbit" width={120} height={27} />
</a>
{[1, 2, 3, 4].map((step) => (
@@ -548,11 +497,7 @@ export default function SignupPage() {
: "bg-muted-foreground/20 text-muted-foreground"
)}
>
- {currentStep > step ? (
- <Check className="h-4 w-4" />
- ) : (
- getStepIcon(step)
- )}
+ {currentStep > step ? <Check className="h-4 w-4" /> : getStepIcon(step)}
</div>
<span>
{step === 1 && "Create account"}
diff --git a/client/src/components/CreateOrganizationDialog.tsx b/client/src/components/CreateOrganizationDialog.tsx
index d862ea1e2..bb1be7ae7 100644
--- a/client/src/components/CreateOrganizationDialog.tsx
+++ b/client/src/components/CreateOrganizationDialog.tsx
@@ -11,10 +11,12 @@ import { DialogFooter } from "./ui/dialog";
import { DialogDescription } from "./ui/dialog";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
-import { Building2 } from "lucide-react";
+import { AlertCircle, Building2 } from "lucide-react";
import { authClient } from "../lib/auth";
import { toast } from "sonner";
-import { useMutation } from "@tanstack/react-query";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { USER_ORGANIZATIONS_QUERY_KEY } from "../api/admin/organizations";
+import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
interface CreateOrganizationDialogProps {
open: boolean;
@@ -23,15 +25,11 @@ interface CreateOrganizationDialogProps {
trigger?: React.ReactNode;
}
-export function CreateOrganizationDialog({
- open,
- onOpenChange,
- onSuccess,
- trigger,
-}: CreateOrganizationDialogProps) {
+export function CreateOrganizationDialog({ open, onOpenChange, onSuccess, trigger }: CreateOrganizationDialogProps) {
const [name, setName] = useState("");
const [slug, setSlug] = useState("");
const [error, setError] = useState<string>("");
+ const queryClient = useQueryClient();
// Generate slug from name when name changes
const handleNameChange = (value: string) => {
@@ -54,6 +52,8 @@ export function CreateOrganizationDialog({
slug,
});
+ queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });
+
if (error) {
throw new Error(error.message || "Failed to create organization");
}
@@ -106,9 +106,7 @@ export function CreateOrganizationDialog({
<Building2 className="h-6 w-6" />
Create Your Organization
</DialogTitle>
- <DialogDescription>
- Set up your organization to get started with Rybbit
- </DialogDescription>
+ <DialogDescription>Set up your organization to get started with Rybbit</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-4">
@@ -124,7 +122,7 @@ export function CreateOrganizationDialog({
/>
</div>
- <div className="space-y-2">
+ {/* <div className="space-y-2">
<Label htmlFor="slug">
Organization Slug
<span className="text-xs text-muted-foreground ml-2">
@@ -149,31 +147,23 @@ export function CreateOrganizationDialog({
<p className="text-xs text-muted-foreground">
This will be used in your URL: rybbit.io/{slug}
</p>
- </div>
+ </div> */}
{error && (
- <div className="bg-destructive/15 text-destructive p-3 rounded-md text-sm">
- {error}
- </div>
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Error</AlertTitle>
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
)}
</div>
<DialogFooter>
- <Button
- variant="outline"
- type="button"
- onClick={() => onOpenChange(false)}
- >
+ <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
Cancel
</Button>
- <Button
- type="submit"
- variant="success"
- disabled={createOrgMutation.isPending || !name || !slug}
- >
- {createOrgMutation.isPending
- ? "Creating..."
- : "Create Organization"}
+ <Button type="submit" variant="success" disabled={createOrgMutation.isPending || !name || !slug}>
+ {createOrgMutation.isPending ? "Creating..." : "Create Organization"}
</Button>
</DialogFooter>
</form>
diff --git a/client/src/components/TopBar.tsx b/client/src/components/TopBar.tsx
index 4ea4278ff..db6172ce3 100644
--- a/client/src/components/TopBar.tsx
+++ b/client/src/components/TopBar.tsx
@@ -7,13 +7,9 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { authClient } from "../lib/auth";
import { Button } from "./ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "./ui/dropdown-menu";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./ui/dropdown-menu";
import { Skeleton } from "./ui/skeleton";
+import { IS_CLOUD } from "../lib/const";
export function TopBar() {
const { data: session, isPending } = authClient.useSession();
@@ -25,12 +21,7 @@ export function TopBar() {
<div className="flex items-center justify-between flex-1">
<div className="flex items-center space-x-4">
<Link href={session ? "/" : "https://rybbit.io"}>
- <Image
- src="/rybbit-text.svg"
- alt="Rybbit"
- width={100}
- height={22}
- />
+ <Image src="/rybbit-text.svg" alt="Rybbit" width={100} height={22} />
</Link>
</div>
{session ? (
@@ -60,7 +51,7 @@ export function TopBar() {
>
Sign out
</DropdownMenuItem>
- {session?.user.role === "admin" && (
+ {session?.user.role === "admin" && IS_CLOUD && (
<Link href="/admin" passHref>
<DropdownMenuItem>Admin</DropdownMenuItem>
</Link>
@@ -72,8 +63,7 @@ export function TopBar() {
) : (
<Link
href={
- typeof window !== "undefined" &&
- globalThis.location.hostname === "demo.rybbit.io"
+ typeof window !== "undefined" && globalThis.location.hostname === "demo.rybbit.io"
? "https://app.rybbit.io/signup"
: "/signup"
}
diff --git a/client/src/lib/auth-utils.ts b/client/src/lib/auth-utils.ts
new file mode 100644
index 000000000..95cd6af79
--- /dev/null
+++ b/client/src/lib/auth-utils.ts
@@ -0,0 +1,3 @@
+export function validateEmail(email: string) {
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
+}
diff --git a/docs/src/content/inviting-users.mdx b/docs/src/content/inviting-users.mdx
index 11fbd2832..0ee2b2f5d 100644
--- a/docs/src/content/inviting-users.mdx
+++ b/docs/src/content/inviting-users.mdx
@@ -3,7 +3,11 @@ import { Callout } from 'nextra/components'
# Inviting Users
-Currently only the cloud version of Rybbit supports inviting users.
+You can invite your team members to your Rybbit organization as either an admin or a member.
+
+<Callout type="info">
+ On self-hosted instances, this workflow is slightly different. Instead of inviting users, you can create a new user and set their password directly since self-hosted instances don't send emails.
+</Callout>
<Steps>
@@ -28,4 +32,3 @@ Click the "Invite" button. The user will receive an email with a link to sign up
<Callout type="info">
Currently, each user can only be in one organization.
</Callout>
-
diff --git a/server/src/api/user/addUserToOrganization.ts b/server/src/api/user/addUserToOrganization.ts
new file mode 100644
index 000000000..108d84887
--- /dev/null
+++ b/server/src/api/user/addUserToOrganization.ts
@@ -0,0 +1,82 @@
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { db } from "../../db/postgres/postgres.js";
+import { member, user } from "../../db/postgres/schema.js";
+
+import { randomBytes } from "crypto";
+import { getUserIsInOrg } from "../../lib/auth-utils.js";
+
+function generateId(len = 32) {
+ const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ const bytes = randomBytes(len);
+ let id = "";
+ for (let i = 0; i < len; i++) {
+ id += alphabet[bytes[i] % alphabet.length];
+ }
+ return id;
+}
+
+interface AddUserToOrganization {
+ Body: {
+ email: string;
+ role: string;
+ organizationId: string;
+ };
+}
+
+export async function addUserToOrganization(request: FastifyRequest<AddUserToOrganization>, reply: FastifyReply) {
+ try {
+ const { email, role, organizationId } = request.body;
+
+ const userIsInOrg = await getUserIsInOrg(request, organizationId);
+ if (!userIsInOrg || (userIsInOrg.role !== "admin" && userIsInOrg.role !== "owner")) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Validate input
+ if (!email || !role || !organizationId) {
+ return reply.status(400).send({
+ error: "Missing required fields: email, role, and organizationId",
+ });
+ }
+
+ if (role !== "admin" && role !== "member" && role !== "owner") {
+ return reply.status(400).send({
+ error: "Role must be either admin, member, or owner",
+ });
+ }
+
+ const foundUser = await db.query.user.findFirst({
+ where: eq(user.email, email),
+ });
+
+ if (!foundUser) {
+ return reply.status(404).send({ error: "User not found" });
+ }
+
+ const foundMember = await db.query.member.findMany({
+ where: eq(member.userId, foundUser.id),
+ });
+
+ if (foundMember.length > 0) {
+ return reply.status(400).send({ error: "user is already in an organization" });
+ }
+
+ await db.insert(member).values([
+ {
+ userId: foundUser.id,
+ organizationId: organizationId,
+ role: role,
+ id: generateId(),
+ createdAt: new Date().toISOString(),
+ },
+ ]);
+
+ return reply.status(201).send({
+ message: "User added to organization successfully",
+ });
+ } catch (error: any) {
+ console.error(String(error));
+ return reply.status(500).send({ error: String(error) });
+ }
+}
diff --git a/server/src/api/user/listOrganizationMembers.ts b/server/src/api/user/listOrganizationMembers.ts
index 9bce903cb..5ed739c0e 100644
--- a/server/src/api/user/listOrganizationMembers.ts
+++ b/server/src/api/user/listOrganizationMembers.ts
@@ -1,8 +1,7 @@
-import { FastifyRequest, FastifyReply } from "fastify";
+import { and, eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { member, user } from "../../db/postgres/schema.js";
-import { eq, and } from "drizzle-orm";
-import { auth } from "../../lib/auth.js";
import { getSessionFromReq } from "../../lib/auth-utils.js";
interface ListOrganizationMembersRequest {
@@ -21,7 +20,7 @@ interface UserInfo {
export async function listOrganizationMembers(
request: FastifyRequest<ListOrganizationMembersRequest>,
- reply: FastifyReply
+ reply: FastifyReply,
) {
try {
const { organizationId } = request.params;
@@ -37,10 +36,7 @@ export async function listOrganizationMembers(
// Check if user is a member of this organization
const userMembership = await db.query.member.findFirst({
- where: and(
- eq(member.userId, session.user.id),
- eq(member.organizationId, organizationId)
- ),
+ where: and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)),
});
if (!userMembership) {
diff --git a/server/src/db/postgres/initPostgres.ts b/server/src/db/postgres/initPostgres.ts
new file mode 100644
index 000000000..6b6ab073a
--- /dev/null
+++ b/server/src/db/postgres/initPostgres.ts
@@ -0,0 +1,17 @@
+import { asc, eq } from "drizzle-orm";
+import { db } from "./postgres.js";
+import { user } from "./schema.js";
+
+export const initPostgres = async () => {
+ try {
+ // Find the oldest user by createdAt timestamp
+ const oldestUser = await db.select().from(user).orderBy(asc(user.createdAt)).limit(1);
+
+ if (oldestUser.length > 0) {
+ // Update the oldest user's role to admin
+ await db.update(user).set({ role: "admin" }).where(eq(user.id, oldestUser[0].id));
+ }
+ } catch (error) {
+ console.error("Error initializing postgres:", error);
+ }
+};
diff --git a/server/src/index.ts b/server/src/index.ts
index f1c2e10da..d281b843b 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -68,6 +68,8 @@ import { IS_CLOUD } from "./lib/const.js";
import { siteConfig } from "./lib/siteConfig.js";
import { trackEvent } from "./services/tracker/trackEvent.js";
import { extractSiteId, isSitePublic } from "./utils.js";
+import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
+import { initPostgres } from "./db/postgres/initPostgres.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -283,6 +285,7 @@ server.get("/api/site/:siteId/api-config", getSiteApiConfig);
server.post("/api/site/:siteId/api-config", updateSiteApiConfig);
server.get("/api/list-organization-members/:organizationId", listOrganizationMembers);
server.get("/api/user/organizations", getUserOrganizations);
+server.post("/api/add-user-to-organization", addUserToOrganization);
if (IS_CLOUD) {
// Stripe Routes
@@ -304,12 +307,7 @@ server.get("/api/health", { logLevel: "silent" }, (_, reply) => reply.send("OK")
const start = async () => {
try {
console.info("Starting server...");
- // Initialize the database
- await Promise.all([initializeClickhouse()]);
- await loadAllowedDomains();
-
- // Load site configurations cache
- await siteConfig.loadSiteConfigs();
+ await Promise.all([initializeClickhouse(), loadAllowedDomains(), siteConfig.loadSiteConfigs(), initPostgres()]);
// Start the server
await server.listen({ port: 3001, host: "0.0.0.0" });
diff --git a/server/src/lib/allowedDomains.ts b/server/src/lib/allowedDomains.ts
index 37f899fff..57172574d 100644
--- a/server/src/lib/allowedDomains.ts
+++ b/server/src/lib/allowedDomains.ts
@@ -32,6 +32,7 @@ export const loadAllowedDomains = async () => {
normalizeOrigin(process.env.BASE_URL || ""),
...domains.map(({ domain }) => normalizeOrigin(domain)),
];
+ initAuth(allowList);
} catch (error) {
console.error("Error loading allowed domains:", error);
// Set default values in case of error
diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.ts
index 4684e5291..004d33880 100644
--- a/server/src/lib/auth-utils.ts
+++ b/server/src/lib/auth-utils.ts
@@ -1,7 +1,7 @@
import { FastifyRequest } from "fastify";
import { auth } from "./auth.js";
import { sites, member, user } from "../db/postgres/schema.js";
-import { inArray, eq } from "drizzle-orm";
+import { inArray, eq, and } from "drizzle-orm";
import { db } from "../db/postgres/postgres.js";
import { isSitePublic } from "../utils.js";
import NodeCache from "node-cache";
@@ -124,3 +124,18 @@ export async function getUserHasAdminAccessToSite(req: FastifyRequest, siteId: s
const sites = await getSitesUserHasAccessTo(req, true);
return sites.some((site) => site.siteId === Number(siteId));
}
+
+export async function getUserIsInOrg(req: FastifyRequest, organizationId: string) {
+ const session = await getSessionFromReq(req);
+
+ if (!session?.user.id) {
+ return false;
+ }
+
+ // Check if user is a member of this organization
+ const userMembership = await db.query.member.findFirst({
+ where: and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)),
+ });
+
+ return userMembership;
+}
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index bfce25b0f..0a6dbef65 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -1,13 +1,15 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
-import { admin, organization, emailOTP } from "better-auth/plugins";
+import { admin, emailOTP, organization } from "better-auth/plugins";
import dotenv from "dotenv";
-import { eq } from "drizzle-orm";
+import { asc, eq } from "drizzle-orm";
import pg from "pg";
+
import { db } from "../db/postgres/postgres.js";
import * as schema from "../db/postgres/schema.js";
+import { user } from "../db/postgres/schema.js";
import { DISABLE_SIGNUP } from "./const.js";
-import { sendInvitationEmail, sendEmail } from "./resend.js";
+import { sendEmail, sendInvitationEmail } from "./resend.js";
dotenv.config();
@@ -26,7 +28,7 @@ const pluginList = [
invitation.email,
invitation.inviter.user.email,
invitation.organization.name,
- inviteLink
+ inviteLink,
);
},
}),
@@ -93,6 +95,8 @@ export let auth: AuthType | null = betterAuth({
}),
emailAndPassword: {
enabled: true,
+ // Disable email verification for now
+ requireEmailVerification: false,
disableSignUp: DISABLE_SIGNUP,
},
socialProviders: {
@@ -122,6 +126,20 @@ export let auth: AuthType | null = betterAuth({
path: "/",
},
},
+ databaseHooks: {
+ user: {
+ create: {
+ after: async () => {
+ const users = await db.select().from(schema.user).orderBy(asc(user.createdAt));
+
+ // If this is the first user, make them an admin
+ if (users.length === 1) {
+ await db.update(user).set({ role: "admin" }).where(eq(user.id, users[0].id));
+ }
+ },
+ },
+ },
+ },
});
export function initAuth(allowedOrigins: string[]) {
@@ -178,21 +196,14 @@ export function initAuth(allowedOrigins: string[]) {
// i dont think this works
beforeDelete: async (user) => {
// Delete all memberships for this user first
- console.log(
- `Cleaning up memberships for user ${user.id} before deletion`
- );
+ console.log(`Cleaning up memberships for user ${user.id} before deletion`);
try {
// Delete member records for this user
- await db
- .delete(schema.member)
- .where(eq(schema.member.userId, user.id));
+ await db.delete(schema.member).where(eq(schema.member.userId, user.id));
console.log(`Successfully removed memberships for user ${user.id}`);
} catch (error) {
- console.error(
- `Error removing memberships for user ${user.id}:`,
- error
- );
+ console.error(`Error removing memberships for user ${user.id}:`, error);
throw error; // Re-throw to prevent user deletion if cleanup fails
}
},
@@ -210,5 +221,19 @@ export function initAuth(allowedOrigins: string[]) {
path: "/",
},
},
+ databaseHooks: {
+ user: {
+ create: {
+ after: async () => {
+ const users = await db.select().from(schema.user).orderBy(asc(user.createdAt));
+
+ // If this is the first user, make them an admin
+ if (users.length === 1) {
+ await db.update(user).set({ role: "admin" }).where(eq(user.id, users[0].id));
+ }
+ },
+ },
+ },
+ },
});
}