🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
update account settings page
Bill Yangab5ab5246b2a
diff --git a/client/src/app/layout.tsx b/client/src/app/layout.tsxindex 100cf6620..8553f64e1 100644--- a/client/src/app/layout.tsx+++ b/client/src/app/layout.tsx@@ -9,6 +9,7 @@ import { redirect, usePathname } from "next/navigation";import { useEffect } from "react";import { userStore } from "../lib/userStore";import "./globals.css";+import { Toaster } from "../components/ui/sonner";const inter = Inter({ subsets: ["latin"] });@@ -38,6 +39,7 @@ export default function RootLayout({<bodyclassName={`${inter.className} h-full bg-background text-foreground`}>+ <Toaster />{/* The ldrs are very pretty but it's super annoying to load themhttps://github.com/GriffinJohnston/ldrs/blob/main/framework-guides.md#nextjs */}<scriptdiff --git a/client/src/app/settings/account/Account.tsx b/client/src/app/settings/account/Account.tsxindex 12ff7121b..0f26b2daf 100644--- a/client/src/app/settings/account/Account.tsx+++ b/client/src/app/settings/account/Account.tsx@@ -2,7 +2,6 @@ import { authClient } from "@/lib/auth";import {Card,CardContent,- CardFooter,CardHeader,CardTitle,} from "../../../components/ui/card";@@ -12,6 +11,8 @@ import { useState } from "react";import { Button } from "../../../components/ui/button";import { ChangePassword } from "./ChangePassword";import { DeleteAccount } from "./DeleteAccount";+import { toast } from "sonner";+import { changeUsername, changeEmail } from "@/hooks/api";export function Account({session,@@ -20,10 +21,71 @@ export function Account({}) {const [username, setUsername] = useState(session.data?.user.username ?? "");const [email, setEmail] = useState(session.data?.user.email ?? "");+ const [isUpdatingUsername, setIsUpdatingUsername] = useState(false);+ const [isUpdatingEmail, setIsUpdatingEmail] = useState(false);- const hasChanges =- username !== session.data?.user.username ||- email !== session.data?.user.email;+ const handleUsernameUpdate = async () => {+ if (!username) {+ toast.error("Username cannot be empty");+ return;+ }++ try {+ setIsUpdatingUsername(true);+ const response = await changeUsername(username);++ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || "Failed to update username");+ }++ toast.success("Username updated successfully");++ // Reload the page to refresh the session+ window.location.reload();+ } catch (error) {+ console.error("Error updating username:", error);+ toast.error(+ error instanceof Error ? error.message : "Failed to update username"+ );+ } finally {+ setIsUpdatingUsername(false);+ }+ };++ const handleEmailUpdate = async () => {+ if (!email) {+ toast.error("Email cannot be empty");+ return;+ }++ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {+ toast.error("Please enter a valid email address");+ return;+ }++ try {+ setIsUpdatingEmail(true);+ const response = await changeEmail(email);++ if (!response.ok) {+ const data = await response.json();+ throw new Error(data.error || "Failed to update email");+ }++ toast.success("Email updated successfully");++ // Reload the page to refresh the session+ window.location.reload();+ } catch (error) {+ console.error("Error updating email:", error);+ toast.error(+ error instanceof Error ? error.message : "Failed to update email"+ );+ } finally {+ setIsUpdatingEmail(false);+ }+ };return (<div className="flex flex-col gap-4">@@ -31,37 +93,80 @@ export function Account({<CardHeader><CardTitle className="text-xl">Account</CardTitle></CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="grid w-full items-center gap-1.5">- <Label htmlFor="username">Username</Label>- <Input- className="w-60"- id="username"- value={username}- onChange={({ target }) => setUsername(target.value)}- />+ <CardContent className="space-y-6">+ <div className="space-y-2">+ <h4 className="text-sm font-medium">Username</h4>+ <p className="text-xs text-neutral-500">+ Update your username displayed across the platform+ </p>+ <div className="flex space-x-2">+ <Input+ id="username"+ value={username}+ onChange={({ target }) => setUsername(target.value)}+ placeholder="username"+ />+ <Button+ variant="outline"+ onClick={handleUsernameUpdate}+ disabled={+ isUpdatingUsername || username === session.data?.user.username+ }+ >+ {isUpdatingUsername ? "Updating..." : "Update"}+ </Button>+ </div></div>- <div className="grid w-full items-center gap-1.5">- <Label htmlFor="email">Email</Label>- <Input- className="w-60"- id="email"- type="email"- value={email}- onChange={({ target }) => setEmail(target.value)}- />++ <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>+ <div className="flex space-x-2">+ <Input+ id="email"+ type="email"+ value={email}+ onChange={({ target }) => setEmail(target.value)}+ placeholder="[email protected]"+ />+ <Button+ variant="outline"+ onClick={handleEmailUpdate}+ disabled={isUpdatingEmail || email === session.data?.user.email}+ >+ {isUpdatingEmail ? "Updating..." : "Update"}+ </Button>+ </div></div></CardContent>- <CardFooter className="flex justify-end">- <Button variant={"accent"} disabled={!hasChanges}>- Save Changes- </Button>- </CardFooter></Card>- <Card className="p-2 pt-6">- <CardContent className="flex flex-col gap-4">- <ChangePassword />- <DeleteAccount />++ <Card className="p-2">+ <CardHeader>+ <CardTitle className="text-xl">Security</CardTitle>+ </CardHeader>+ <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>+ <div className="w-[200px]">+ <ChangePassword />+ </div>+ </div>++ <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>+ <div className="w-[200px]">+ <DeleteAccount />+ </div>+ </div></CardContent></Card></div>diff --git a/client/src/app/settings/account/ChangePassword.tsx b/client/src/app/settings/account/ChangePassword.tsxindex 44070cce5..6b4f99360 100644--- a/client/src/app/settings/account/ChangePassword.tsx+++ b/client/src/app/settings/account/ChangePassword.tsx@@ -4,127 +4,137 @@ import { authClient } from "../../../lib/auth";import {Dialog,DialogContent,+ DialogDescription,DialogFooter,DialogHeader,DialogTitle,DialogTrigger,+ DialogClose,} from "../../../components/ui/dialog";-import {- Alert,- AlertDescription,- AlertTitle,-} from "../../../components/ui/alert";-import { AlertCircle } from "lucide-react";import { Label } from "../../../components/ui/label";import { Input } from "../../../components/ui/input";+import { KeyRound } from "lucide-react";+import { toast } from "sonner";export function ChangePassword() {const [open, setOpen] = useState(false);const [currentPassword, setCurrentPassword] = useState("");const [newPassword, setNewPassword] = useState("");const [confirmPassword, setConfirmPassword] = useState("");- const [error, setError] = useState("");+ const [isSubmitting, setIsSubmitting] = useState(false);const passwordsMatch = newPassword === confirmPassword;+ const canSubmit =+ currentPassword && newPassword && confirmPassword && passwordsMatch;- const handleSubmit = async () => {- setError("");+ const resetForm = () => {+ setCurrentPassword("");+ setNewPassword("");+ setConfirmPassword("");+ setIsSubmitting(false);+ };- if (newPassword !== confirmPassword) {- setError("New password and confirm password do not match");+ const handleSubmit = async () => {+ if (!passwordsMatch) {+ toast.error("New password and confirm password do not match");return;}+try {+ setIsSubmitting(true);const response = await authClient.changePassword({currentPassword,newPassword,});if (response.error) {- setError(String(response.error.message));+ toast.error(`Error: ${response.error.message}`);return;}+ toast.success("Password changed successfully");setOpen(false);+ resetForm();} catch (error) {- setError(String(error));+ toast.error(`Error: ${error}`);+ } finally {+ setIsSubmitting(false);}};return (- <div>- <Dialog- open={open}- onOpenChange={(isOpen) => {- setOpen(isOpen);- setCurrentPassword("");- setNewPassword("");- setConfirmPassword("");- setError("");- }}- >- <DialogTrigger asChild>- <Button>Change Password</Button>- </DialogTrigger>- <DialogContent className="max-w-lg">- <DialogHeader>- <DialogTitle>Change Password</DialogTitle>- </DialogHeader>- <div className="grid w-full items-center gap-1.5">+ <Dialog+ open={open}+ onOpenChange={(isOpen) => {+ setOpen(isOpen);+ if (!isOpen) resetForm();+ }}+ >+ <DialogTrigger asChild>+ <Button variant="outline" className="w-full">+ <KeyRound className="h-4 w-4 mr-2" />+ Change Password+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>Change Password</DialogTitle>+ <DialogDescription>+ Update your password to keep your account secure+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4 py-4">+ <div className="space-y-2"><Label htmlFor="currentPassword">Current Password</Label><Input+ id="currentPassword"value={currentPassword}onChange={(e) => setCurrentPassword(e.target.value)}type="password"+ placeholder="Your current password"/></div>- <div className="grid w-full items-center gap-1.5">++ <div className="space-y-2"><Label htmlFor="newPassword">New Password</Label><Input+ id="newPassword"value={newPassword}onChange={(e) => setNewPassword(e.target.value)}type="password"+ placeholder="Your new password"/></div>- <div className="grid w-full items-center gap-1.5">++ <div className="space-y-2"><Label htmlFor="confirmPassword">Confirm Password</Label><Input+ id="confirmPassword"value={confirmPassword}onChange={(e) => setConfirmPassword(e.target.value)}type="password"+ placeholder="Confirm your new password"/>+ {!passwordsMatch && confirmPassword && (+ <p className="text-xs text-red-500">Passwords do not match</p>+ )}</div>- {error && (- <Alert variant="destructive">- <AlertCircle className="h-4 w-4" />- <AlertTitle>Error Changing Password</AlertTitle>- <AlertDescription>{error}</AlertDescription>- </Alert>- )}- <DialogFooter>- <Button- type="submit"- onClick={() => setOpen(false)}- variant={"ghost"}- >- Cancel- </Button>- <Button- type="submit"- onClick={handleSubmit}- disabled={- !currentPassword ||- !newPassword ||- !confirmPassword ||- !passwordsMatch- }- variant={"warning"}- >- Change- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>+ </div>++ <DialogFooter className="space-x-2">+ <DialogClose asChild>+ <Button variant="outline">Cancel</Button>+ </DialogClose>+ <Button+ onClick={handleSubmit}+ disabled={!canSubmit || isSubmitting}+ variant="accent"+ >+ {isSubmitting ? "Changing..." : "Change Password"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>);}diff --git a/client/src/app/settings/account/DeleteAccount.tsx b/client/src/app/settings/account/DeleteAccount.tsxindex 341c79878..bad617112 100644--- a/client/src/app/settings/account/DeleteAccount.tsx+++ b/client/src/app/settings/account/DeleteAccount.tsx@@ -1,85 +1,69 @@import { useState } from "react";import { Button } from "../../../components/ui/button";import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "../../../components/ui/dialog";+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "../../../components/ui/alert-dialog";import { authClient } from "../../../lib/auth";-import {- Alert,- AlertDescription,- AlertTitle,-} from "../../../components/ui/alert";-import { AlertCircle } from "lucide-react";+import { AlertTriangle } from "lucide-react";+import { toast } from "sonner";export function DeleteAccount() {- const [open, setOpen] = useState(false);- const [error, setError] = useState("");-- const handleSubmit = async () => {- setError("");+ const [isDeleting, setIsDeleting] = useState(false);+ const handleAccountDeletion = async () => {try {+ setIsDeleting(true);const response = await authClient.deleteUser({});if (response.error) {- setError(String(response.error.message));+ toast.error(`Failed to delete account: ${response.error.message}`);return;}- setOpen(false);+ toast.success("Account successfully deleted");+ // The user will be redirected to the login page by the auth system} catch (error) {- setError(String(error));+ toast.error(`Failed to delete account: ${error}`);+ } finally {+ setIsDeleting(false);}};return (- <div>- <Dialog- open={open}- onOpenChange={(isOpen) => {- setOpen(isOpen);- setError("");- }}- >- <DialogTrigger asChild>- <Button variant={"destructive"}>Delete Account</Button>- </DialogTrigger>- <DialogContent className="max-w-lg">- <DialogHeader>- <DialogTitle>Delete Your Account</DialogTitle>- <DialogDescription>This action cannot be undone.</DialogDescription>- </DialogHeader>- {error && (- <Alert variant="destructive">- <AlertCircle className="h-4 w-4" />- <AlertTitle>Error Changing Password</AlertTitle>- <AlertDescription>{error}</AlertDescription>- </Alert>- )}- <DialogFooter>- <Button- type="submit"- onClick={() => setOpen(false)}- variant={"ghost"}- >- Cancel- </Button>- <Button- type="submit"- onClick={handleSubmit}- variant={"destructive"}- >- Delete Account- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="destructive" className="w-full">+ <AlertTriangle className="h-4 w-4 mr-2" />+ Delete Account+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>+ <AlertDialogDescription>+ This action cannot be undone. This will permanently delete your+ account and remove all of your data from our servers.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={handleAccountDeletion}+ disabled={isDeleting}+ variant="destructive"+ >+ {isDeleting ? "Deleting..." : "Yes, delete my account"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>);}diff --git a/client/src/components/ui/sonner.tsx b/client/src/components/ui/sonner.tsxnew file mode 100644index 000000000..01893abab--- /dev/null+++ b/client/src/components/ui/sonner.tsx@@ -0,0 +1,32 @@+"use client";++import { useTheme } from "next-themes";+import { Toaster as Sonner } from "sonner";++type ToasterProps = React.ComponentProps<typeof Sonner>;++const Toaster = ({ ...props }: ToasterProps) => {+ const { theme = "system" } = useTheme();++ return (+ <Sonner+ theme={theme as ToasterProps["theme"]}+ className="toaster group"+ toastOptions={{+ classNames: {+ toast:+ "group toast group-[.toaster]:bg-white group-[.toaster]:text-neutral-950 group-[.toaster]:border-neutral-200 group-[.toaster]:shadow-lg dark:group-[.toaster]:bg-neutral-850 dark:group-[.toaster]:text-neutral-50 dark:group-[.toaster]:border-neutral-700",+ description:+ "group-[.toast]:text-neutral-500 dark:group-[.toast]:text-neutral-400",+ actionButton:+ "group-[.toast]:bg-neutral-900 group-[.toast]:text-neutral-50 dark:group-[.toast]:bg-neutral-50 dark:group-[.toast]:text-neutral-900",+ cancelButton:+ "group-[.toast]:bg-neutral-100 group-[.toast]:text-neutral-500 dark:group-[.toast]:bg-neutral-800 dark:group-[.toast]:text-neutral-400",+ },+ }}+ {...props}+ />+ );+};++export { Toaster };diff --git a/client/src/hooks/api.ts b/client/src/hooks/api.tsindex c41dbad1e..23732b018 100644--- a/client/src/hooks/api.ts+++ b/client/src/hooks/api.ts@@ -230,6 +230,30 @@ export function useSiteHasData(siteId: string) {return useGenericQuery<boolean>(`site-has-data/${siteId}`);}+export function changeUsername(newUsername: string) {+ return authedFetch(`${BACKEND_URL}/change-username`, {+ method: "POST",+ body: JSON.stringify({+ newUsername,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });+}++export function changeEmail(newEmail: string) {+ return authedFetch(`${BACKEND_URL}/change-email`, {+ method: "POST",+ body: JSON.stringify({+ newEmail,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });+}+// Updated type for grouped sessions from the APIexport type UserSessionsResponse = {session_id: string;diff --git a/server/src/api/changeEmail.ts b/server/src/api/changeEmail.tsnew file mode 100644index 000000000..1ce8c00e1--- /dev/null+++ b/server/src/api/changeEmail.ts@@ -0,0 +1,88 @@+import { fromNodeHeaders } from "better-auth/node";+import { FastifyReply, FastifyRequest } from "fastify";+import { eq } from "drizzle-orm";+import { db } from "../db/postgres/postgres.js";+import { users } from "../db/postgres/schema.js";+import { auth } from "../lib/auth.js";++interface ChangeEmailRequest {+ Body: {+ newEmail: string;+ };+}++export async function changeEmail(+ request: FastifyRequest<ChangeEmailRequest>,+ reply: FastifyReply+) {+ try {+ const { newEmail } = request.body;++ // Validate input+ if (!newEmail || newEmail.trim() === "") {+ return reply.status(400).send({+ error: "New email cannot be empty",+ });+ }++ // Validate email format+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+ if (!emailRegex.test(newEmail)) {+ return reply.status(400).send({+ error: "Invalid email format",+ });+ }++ // Get current user session+ const session = await auth!.api.getSession({+ headers: fromNodeHeaders(request.headers),+ });++ if (!session?.user.id) {+ return reply.status(401).send({ error: "Unauthorized" });+ }++ const userId = session.user.id;++ // Check if the email is already taken+ const existingUser = await db+ .select()+ .from(users)+ .where(eq(users.email, newEmail))+ .execute();++ if (existingUser.length > 0 && existingUser[0].id !== userId) {+ return reply.status(409).send({ error: "Email already exists" });+ }++ // Update the user's email+ await db+ .update(users)+ .set({+ email: newEmail,+ updatedAt: new Date(),+ // Note: In a production app, you might want to reset emailVerified to false here+ // and send a verification email to the new address+ // emailVerified: false,+ })+ .where(eq(users.id, userId))+ .execute();++ return reply.status(200).send({+ message: "Email updated successfully",+ email: newEmail,+ });+ } catch (error: any) {+ console.error("Error changing email:", error);++ // Handle specific errors+ if (+ error.message?.includes("unique constraint") &&+ error.message.includes("email")+ ) {+ return reply.status(409).send({ error: "Email already exists" });+ }++ return reply.status(500).send({ error: "Failed to update email" });+ }+}diff --git a/server/src/api/changeUsername.ts b/server/src/api/changeUsername.tsnew file mode 100644index 000000000..fb401ca63--- /dev/null+++ b/server/src/api/changeUsername.ts@@ -0,0 +1,77 @@+import { fromNodeHeaders } from "better-auth/node";+import { FastifyReply, FastifyRequest } from "fastify";+import { eq } from "drizzle-orm";+import { db } from "../db/postgres/postgres.js";+import { users } from "../db/postgres/schema.js";+import { auth } from "../lib/auth.js";++interface ChangeUsernameRequest {+ Body: {+ newUsername: string;+ };+}++export async function changeUsername(+ request: FastifyRequest<ChangeUsernameRequest>,+ reply: FastifyReply+) {+ try {+ const { newUsername } = request.body;++ // Validate input+ if (!newUsername || newUsername.trim() === "") {+ return reply.status(400).send({+ error: "New username cannot be empty",+ });+ }++ // Get current user session+ const session = await auth!.api.getSession({+ headers: fromNodeHeaders(request.headers),+ });++ if (!session?.user.id) {+ return reply.status(401).send({ error: "Unauthorized" });+ }++ const userId = session.user.id;++ // Check if the username is already taken+ const existingUser = await db+ .select()+ .from(users)+ .where(eq(users.username, newUsername))+ .execute();++ if (existingUser.length > 0 && existingUser[0].id !== userId) {+ return reply.status(409).send({ error: "Username already exists" });+ }++ // Update the user's username+ await db+ .update(users)+ .set({+ username: newUsername,+ updatedAt: new Date(),+ })+ .where(eq(users.id, userId))+ .execute();++ return reply.status(200).send({+ message: "Username updated successfully",+ username: newUsername,+ });+ } catch (error: any) {+ console.error("Error changing username:", error);++ // Handle specific errors+ if (+ error.message?.includes("unique constraint") &&+ error.message.includes("username")+ ) {+ return reply.status(409).send({ error: "Username already exists" });+ }++ return reply.status(500).send({ error: "Failed to update username" });+ }+}diff --git a/server/src/index.ts b/server/src/index.tsindex 7c61880d4..9c87c1ba1 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -6,6 +6,8 @@ import cron from "node-cron";import { dirname, join } from "path";import { Headers, HeadersInit } from "undici";import { fileURLToPath } from "url";+import { changeEmail } from "./api/changeEmail.js";+import { changeUsername } from "./api/changeUsername.js";import { getLiveUsercount } from "./api/getLiveUsercount.js";import { getOverview } from "./api/getOverview.js";import { getOverviewBucketed } from "./api/getOverviewBucketed.js";@@ -132,6 +134,10 @@ server.get("/get-sites", getSites);server.get("/list-users", listUsers);server.post("/create-account", createAccount);+// User management+server.post("/change-username", changeUsername);+server.post("/change-email", changeEmail);+// Track pageview endpointserver.post("/track/pageview", trackPageView);