feat: profile picture

This commit is contained in:
Henry
2025-01-21 22:41:04 +00:00
parent a162624eb8
commit ef8f42a460
16 changed files with 303 additions and 59 deletions

View File

@@ -14,6 +14,10 @@ const config = {
/** We already do linting and typechecking as separate tasks in CI */ /** We already do linting and typechecking as separate tasks in CI */
eslint: { ignoreDuringBuilds: true }, eslint: { ignoreDuringBuilds: true },
typescript: { ignoreBuildErrors: true }, typescript: { ignoreBuildErrors: true },
images: {
domains: [process.env.NEXT_PUBLIC_SUPABASE_STORAGE_URL ?? ""],
},
}; };
export default config; export default config;

View File

@@ -5,7 +5,7 @@ import FeedbackButton from "./FeedbackButton";
import SideNavigation from "./SideNavigation"; import SideNavigation from "./SideNavigation";
export default function Dashboard(props: { children: React.ReactNode }) { export default function Dashboard(props: { children: React.ReactNode }) {
const { data, isLoading } = api.auth.getUser.useQuery(); const { data, isLoading } = api.user.getUser.useQuery();
return ( return (
<> <>
@@ -28,7 +28,10 @@ export default function Dashboard(props: { children: React.ReactNode }) {
</div> </div>
<div className="flex h-full w-full"> <div className="flex h-full w-full">
<SideNavigation user={{ email: data?.email }} isLoading={isLoading} /> <SideNavigation
user={{ email: data?.email, image: data?.image }}
isLoading={isLoading}
/>
<div className="w-full overflow-hidden">{props.children}</div> <div className="w-full overflow-hidden">{props.children}</div>
</div> </div>
</div> </div>

View File

@@ -58,7 +58,7 @@ export default function SideNavigation({
<li key={item.name}> <li key={item.name}>
<ReactiveButton <ReactiveButton
href={item.href} href={item.href}
current={pathname?.includes(item.href)} current={pathname.includes(item.href)}
name={item.name} name={item.name}
json={item.icon} json={item.icon}
/> />
@@ -67,8 +67,8 @@ export default function SideNavigation({
</ul> </ul>
</div> </div>
<UserMenu <UserMenu
email={user?.email ?? ""} email={user.email ?? ""}
imageUrl={user?.image ?? undefined} imageUrl={user.image ?? undefined}
isLoading={isLoading} isLoading={isLoading}
/> />
</nav> </nav>

View File

@@ -21,17 +21,20 @@ export default function UserMenu({
email, email,
isLoading, isLoading,
}: UserMenuProps) { }: UserMenuProps) {
const db = createClient();
const router = useRouter(); const router = useRouter();
const { themePreference, switchTheme } = useTheme(); const { themePreference, switchTheme } = useTheme();
const handleLogout = async () => { const handleLogout = async () => {
const db = createClient();
await db.auth.signOut(); await db.auth.signOut();
router.push("/login"); router.push("/login");
}; };
const avatarUrl = imageUrl
? db.storage.from("avatars").getPublicUrl(imageUrl).data.publicUrl
: null;
return ( return (
<Menu as="div" className="relative inline-block w-full text-left"> <Menu as="div" className="relative inline-block w-full text-left">
<div> <div>
@@ -42,9 +45,9 @@ export default function UserMenu({
</div> </div>
) : ( ) : (
<Menu.Button className="flex w-full items-center rounded-md p-1.5 text-neutral-900 hover:bg-light-200 dark:text-dark-900 dark:hover:bg-dark-200 dark:hover:text-dark-1000"> <Menu.Button className="flex w-full items-center rounded-md p-1.5 text-neutral-900 hover:bg-light-200 dark:text-dark-900 dark:hover:bg-dark-200 dark:hover:text-dark-1000">
{imageUrl ? ( {avatarUrl ? (
<Image <Image
src={imageUrl ?? ""} src={avatarUrl}
className="h-8 w-8 rounded-full bg-gray-50" className="h-8 w-8 rounded-full bg-gray-50"
width={30} width={30}
height={30} height={30}

View File

@@ -24,6 +24,7 @@ export const env = createEnv({
*/ */
client: { client: {
NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME: z.string(), NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME: z.string(),
NEXT_PUBLIC_SUPABASE_STORAGE_URL: z.string(),
}, },
/** /**
* Destructure all variables from `process.env` to make sure they aren't tree-shaken away. * Destructure all variables from `process.env` to make sure they aren't tree-shaken away.
@@ -32,6 +33,8 @@ export const env = createEnv({
NODE_ENV: process.env.NODE_ENV, NODE_ENV: process.env.NODE_ENV,
NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME: NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME:
process.env.NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME, process.env.NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME,
NEXT_PUBLIC_SUPABASE_STORAGE_URL:
process.env.NEXT_PUBLIC_SUPABASE_STORAGE_URL,
}, },
skipValidation: skipValidation:
!!process.env.CI || process.env.npm_lifecycle_event === "lint", !!process.env.CI || process.env.npm_lifecycle_event === "lint",

View File

@@ -1,4 +1,5 @@
import { useState } from "react"; import { useState } from "react";
// import { useRouter } from "next/navigation"; // import { useRouter } from "next/navigation";
import { Auth } from "~/components/AuthForm"; import { Auth } from "~/components/AuthForm";
import { PageHead } from "~/components/PageHead"; import { PageHead } from "~/components/PageHead";
@@ -19,7 +20,7 @@ export default function LoginPage() {
// .split("; ") // .split("; ")
// .some((cookie) => cookie.includes("auth-token")); // .some((cookie) => cookie.includes("auth-token"));
// const { data } = api.auth.getUser.useQuery(undefined, { // const { data } = api.user.getUser.useQuery(undefined, {
// enabled: authCookieExists ? true : false, // enabled: authCookieExists ? true : false,
// }); // });

View File

@@ -1,7 +1,9 @@
import { useState } from "react"; import { useState } from "react";
// import { useRouter } from "next/navigation"; // import { useRouter } from "next/navigation";
import { Auth } from "~/components/AuthForm"; import { Auth } from "~/components/AuthForm";
import { PageHead } from "~/components/PageHead"; import { PageHead } from "~/components/PageHead";
// import { api } from "~/utils/api"; // import { api } from "~/utils/api";
export default function SignupPage() { export default function SignupPage() {
@@ -18,7 +20,7 @@ export default function SignupPage() {
// .split("; ") // .split("; ")
// .some((cookie) => cookie.includes("auth-token")); // .some((cookie) => cookie.includes("auth-token"));
// const { data } = api.auth.getUser.useQuery(undefined, { // const { data } = api.user.getUser.useQuery(undefined, {
// enabled: authCookieExists ? true : false, // enabled: authCookieExists ? true : false,
// }); // });

View File

@@ -157,7 +157,7 @@ export default function BoardPage() {
type="text" type="text"
{...register("name")} {...register("name")}
onBlur={handleSubmit(onSubmit)} onBlur={handleSubmit(onSubmit)}
className="block border-0 bg-transparent p-0 py-0 font-medium leading-[2.3rem] tracking-tight text-neutral-900 focus:ring-0 focus-visible:outline-none dark:text-dark-1000 sm:text-[1.2rem]" className="block border-0 bg-transparent p-0 py-0 font-bold leading-[2.3rem] tracking-tight text-neutral-900 focus:ring-0 focus-visible:outline-none dark:text-dark-1000 sm:text-[1.2rem]"
/> />
</form> </form>
)} )}

View File

@@ -21,7 +21,7 @@ export default function HomeView() {
? Cookies.get(env.NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME) ? Cookies.get(env.NEXT_PUBLIC_SUPABASE_AUTH_COOKIE_NAME)
: null; : null;
const { data } = api.auth.getUser.useQuery(undefined, { const { data } = api.user.getUser.useQuery(undefined, {
enabled: !!token, enabled: !!token,
}); });

View File

@@ -0,0 +1,113 @@
import Image from "next/image";
import { useState } from "react";
import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api";
import createClient from "~/utils/supabase/client";
export default function Avatar({
userId,
userImage,
}: {
userId: string | undefined;
userImage: string | null | undefined;
}) {
const supabase = createClient();
const utils = api.useUtils();
const { showPopup } = usePopup();
const [uploading, setUploading] = useState(false);
const updateUser = api.user.update.useMutation({
onSuccess: async () => {
try {
await utils.user.getUser.refetch();
} catch (e) {
console.error(e);
throw e;
}
},
onError: () => {
showPopup({
header: "Error updating profile image",
message: "Please try again later, or contact customer support.",
icon: "error",
});
},
});
const avatarUrl = userImage
? supabase.storage.from("avatars").getPublicUrl(userImage).data.publicUrl
: null;
const uploadAvatar = async (event: React.ChangeEvent<HTMLInputElement>) => {
try {
setUploading(true);
if (!event.target.files || event.target.files.length === 0) {
throw new Error("You must select an image to upload.");
}
if (!userId) {
throw new Error("User ID is required.");
}
const file = event.target.files[0];
if (!file) {
throw new Error("No file selected.");
}
const fileExt = file.name.split(".").pop();
const fileName = `${userId}/avatar.${fileExt}`;
const filePath = `${fileName}`;
const { error: uploadError } = await supabase.storage
.from("avatars")
.upload(filePath, file, { upsert: true });
if (uploadError) {
throw uploadError;
}
updateUser.mutate({ image: filePath });
} catch (error) {
console.error(error);
} finally {
setUploading(false);
}
};
return (
<div>
<div className="relative">
<input
className="absolute z-10 h-16 w-16 cursor-pointer rounded-full opacity-0"
type="file"
id="single"
accept="image/*"
onChange={uploadAvatar}
disabled={uploading}
/>
{avatarUrl ? (
<Image
src={avatarUrl}
alt="Avatar"
width={64}
height={64}
className="rounded-full"
/>
) : (
<span className="inline-block h-16 w-16 overflow-hidden rounded-full bg-light-400 dark:bg-dark-400">
<svg
className="h-full w-full text-dark-700"
fill="currentColor"
viewBox="0 0 24 24"
>
<path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
</span>
)}
</div>
</div>
);
}

View File

@@ -6,6 +6,8 @@ import { NewWorkspaceForm } from "~/components/NewWorkspaceForm";
import { PageHead } from "~/components/PageHead"; import { PageHead } from "~/components/PageHead";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
import { useWorkspace } from "~/providers/workspace"; import { useWorkspace } from "~/providers/workspace";
import { api } from "~/utils/api";
import Avatar from "./components/Avatar";
import { DeleteWorkspaceConfirmation } from "./components/DeleteWorkspaceConfirmation"; import { DeleteWorkspaceConfirmation } from "./components/DeleteWorkspaceConfirmation";
import { PremiumUsernameConfirmation } from "./components/PremiumUsernameConfirmation"; import { PremiumUsernameConfirmation } from "./components/PremiumUsernameConfirmation";
import UpdateWorkspaceDescriptionForm from "./components/UpdateWorkspaceDescriptionForm"; import UpdateWorkspaceDescriptionForm from "./components/UpdateWorkspaceDescriptionForm";
@@ -16,6 +18,8 @@ export default function SettingsPage() {
const { modalContentType, openModal } = useModal(); const { modalContentType, openModal } = useModal();
const { workspace } = useWorkspace(); const { workspace } = useWorkspace();
const { data } = api.user.getUser.useQuery();
const handleOpenBillingPortal = async () => { const handleOpenBillingPortal = async () => {
try { try {
const response = await fetch("/api/stripe/create_billing_session", { const response = await fetch("/api/stripe/create_billing_session", {
@@ -47,6 +51,13 @@ export default function SettingsPage() {
</h1> </h1>
</div> </div>
<div className="mb-8 border-t border-light-300 dark:border-dark-300">
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
Profile picture
</h2>
<Avatar userId={data?.id} userImage={data?.image} />
</div>
<div className="mb-8 border-t border-light-300 dark:border-dark-300"> <div className="mb-8 border-t border-light-300 dark:border-dark-300">
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000"> <h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
Workspace name Workspace name

View File

@@ -5,6 +5,7 @@ import { importRouter } from "./routers/import";
import { labelRouter } from "./routers/label"; import { labelRouter } from "./routers/label";
import { listRouter } from "./routers/list"; import { listRouter } from "./routers/list";
import { memberRouter } from "./routers/member"; import { memberRouter } from "./routers/member";
import { userRouter } from "./routers/user";
import { workspaceRouter } from "./routers/workspace"; import { workspaceRouter } from "./routers/workspace";
import { createTRPCRouter } from "./trpc"; import { createTRPCRouter } from "./trpc";
@@ -16,6 +17,7 @@ export const appRouter = createTRPCRouter({
list: listRouter, list: listRouter,
member: memberRouter, member: memberRouter,
import: importRouter, import: importRouter,
user: userRouter,
workspace: workspaceRouter, workspace: workspaceRouter,
}); });

View File

@@ -1,52 +1,9 @@
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { z } from "zod"; import { z } from "zod";
import * as userRepo from "@kan/db/repository/user.repo"; import { createTRPCRouter, publicProcedure } from "../trpc";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const authRouter = createTRPCRouter({ export const authRouter = createTRPCRouter({
getUser: protectedProcedure
.meta({
openapi: {
method: "GET",
path: "/users/me",
summary: "Get user",
description:
"Retrieves the currently authenticated user's profile information",
tags: ["Users"],
protect: true,
},
})
.input(z.void())
.output(
z.object({
id: z.string(),
email: z.string(),
name: z.string().nullable(),
stripeCustomerId: z.string().nullable(),
}),
)
.query(async ({ ctx }) => {
const userId = ctx.user?.id;
if (!userId)
throw new TRPCError({
message: `User not authenticated`,
code: "UNAUTHORIZED",
});
const result = await userRepo.getById(ctx.db, userId);
if (!result?.name) {
throw new TRPCError({
message: `User not found`,
code: "NOT_FOUND",
});
}
return result;
}),
loginWithEmail: publicProcedure loginWithEmail: publicProcedure
.meta({ .meta({
openapi: { openapi: {

View File

@@ -0,0 +1,93 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import * as userRepo from "@kan/db/repository/user.repo";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const userRouter = createTRPCRouter({
getUser: protectedProcedure
.meta({
openapi: {
method: "GET",
path: "/users/me",
summary: "Get user",
description:
"Retrieves the currently authenticated user's profile information",
tags: ["Users"],
protect: true,
},
})
.input(z.void())
.output(
z.object({
id: z.string(),
email: z.string(),
name: z.string().nullable(),
image: z.string().nullable(),
stripeCustomerId: z.string().nullable(),
}),
)
.query(async ({ ctx }) => {
const userId = ctx.user?.id;
if (!userId)
throw new TRPCError({
message: `User not authenticated`,
code: "UNAUTHORIZED",
});
const result = await userRepo.getById(ctx.db, userId);
if (!result?.name) {
throw new TRPCError({
message: `User not found`,
code: "NOT_FOUND",
});
}
return result;
}),
update: protectedProcedure
.meta({
openapi: {
method: "PUT",
path: "/users",
summary: "Update user",
description:
"Updates the currently authenticated user's profile information",
tags: ["Users"],
protect: true,
},
})
.input(
z.object({
image: z.string(),
}),
)
.output(
z.object({
image: z.string().nullable(),
}),
)
.mutation(async ({ ctx, input }) => {
const userId = ctx.user?.id;
if (!userId)
throw new TRPCError({
message: `User not authenticated`,
code: "UNAUTHORIZED",
});
const result = await userRepo.update(ctx.adminDb, userId, input);
if (!result) {
throw new TRPCError({
message: `User not found`,
code: "NOT_FOUND",
});
}
return result;
}),
});

View File

@@ -713,3 +713,40 @@ TO authenticated
USING ( USING (
"createdBy" = auth.uid() "createdBy" = auth.uid()
); );
/* BUCKETS */
insert into storage.buckets
(id, name, public)
values
('avatars', 'avatars', true);
alter table storage.objects enable row level security;
CREATE POLICY "Users can upload their own avatar"
ON storage.objects FOR INSERT
TO authenticated
WITH CHECK (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
CREATE POLICY "Users can update their own avatar"
ON storage.objects FOR UPDATE
TO authenticated
USING (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
CREATE POLICY "Users can delete their own avatar"
ON storage.objects FOR DELETE
TO authenticated
USING (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
CREATE POLICY "Avatar images are publicly accessible"
ON storage.objects FOR SELECT
TO anon, authenticated
USING (bucket_id = 'avatars');

View File

@@ -5,7 +5,7 @@ import type { Database } from "@kan/db/types/database.types";
export const getById = async (db: SupabaseClient<Database>, userId: string) => { export const getById = async (db: SupabaseClient<Database>, userId: string) => {
const { data } = await db const { data } = await db
.from("user") .from("user")
.select(`id, name, email, stripeCustomerId`) .select(`id, name, email, image, stripeCustomerId`)
.eq("id", userId) .eq("id", userId)
.limit(1) .limit(1)
.single(); .single();
@@ -44,3 +44,18 @@ export const create = async (
return data; return data;
}; };
export const update = async (
db: SupabaseClient<Database>,
userId: string,
updates: { image: string | null },
) => {
const { data } = await db
.from("user")
.update({ image: updates.image })
.eq("id", userId)
.select(`image`)
.single();
return data;
};