-
Notifications
You must be signed in to change notification settings - Fork 38
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Set custom avatar picture in user profile (#1119)
* Add API endpoint to upload user profile picture * Add first version of image upload component * Improve avatar uploader component * Update user profile picture in session when needed * Simplify the /account/me API endpoint * Switch Next image pipeline to correct user data blob storage
- Loading branch information
Showing
6 changed files
with
238 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
import { useEffect, useRef, useState } from "react"; | ||
import Image from "next/image"; | ||
|
||
import { type PutBlobResult } from "@vercel/blob"; | ||
import clsx from "clsx"; | ||
|
||
import { FormError } from "~/components/form/FormError"; | ||
import { defaultAvatarUrl } from "~/src/utils"; | ||
|
||
type Props = { | ||
currentImageUrl?: string; | ||
onImageChange: (uploadedImageUrl: string | undefined) => void; | ||
}; | ||
|
||
export function AvatarUploader({ currentImageUrl, onImageChange }: Props) { | ||
const [previewImageUrl, setPreviewImageUrl] = useState(currentImageUrl); | ||
const [errorMessage, setErrorMessage] = useState(""); | ||
const [uploading, setUploading] = useState(false); | ||
|
||
useEffect(() => { | ||
setPreviewImageUrl(currentImageUrl); | ||
}, [currentImageUrl]); | ||
|
||
const handleUpload = async (file: File, imageDataUrl: string) => { | ||
setUploading(true); | ||
setErrorMessage(""); | ||
setPreviewImageUrl(imageDataUrl); | ||
|
||
const response = await fetch( | ||
`/account/profile-picture?filename=${file.name}`, | ||
{ | ||
method: "POST", | ||
body: file, | ||
}, | ||
); | ||
|
||
if (response.ok) { | ||
const newBlob = (await response.json()) as PutBlobResult; | ||
onImageChange(newBlob.url); | ||
} else { | ||
setErrorMessage("Něco se nepovedlo, zkus to prosím ještě jednou?"); | ||
} | ||
|
||
setUploading(false); | ||
}; | ||
|
||
return ( | ||
<div className="flex flex-col gap-3"> | ||
<AvatarPreview | ||
imageUrl={previewImageUrl} | ||
showProgressIndicator={uploading} | ||
/> | ||
<ImageFilePicker handleImageData={handleUpload} /> | ||
{errorMessage && <FormError error={errorMessage} />} | ||
</div> | ||
); | ||
} | ||
|
||
type ImageFilePickerProps = { | ||
handleImageData: (file: File, imageDataUrl: string) => void; | ||
}; | ||
|
||
const ImageFilePicker = ({ handleImageData }: ImageFilePickerProps) => { | ||
const inputFileRef = useRef<HTMLInputElement>(null); | ||
const [errorMessage, setErrorMessage] = useState(""); | ||
|
||
const handleFileSelection = () => { | ||
setErrorMessage(""); | ||
|
||
if (!inputFileRef.current?.files) { | ||
setErrorMessage("Není vybraný soubor"); | ||
return; | ||
} | ||
|
||
const file = inputFileRef.current.files[0]; | ||
|
||
if (file.size > 4500000) { | ||
setErrorMessage("Soubor musí být menší než 4,5 MB"); | ||
return; | ||
} | ||
|
||
if (!file.type.startsWith("image/")) { | ||
setErrorMessage("Soubor musí mít formát obrázku"); | ||
return; | ||
} | ||
|
||
const fileReader = new FileReader(); | ||
fileReader.onload = (e) => { | ||
if (e.target && typeof e.target.result === "string") { | ||
handleImageData(file, e.target.result); | ||
} else { | ||
setErrorMessage("Něco se nepovedlo, zkus to znovu"); | ||
} | ||
}; | ||
|
||
fileReader.readAsDataURL(file); | ||
}; | ||
|
||
return ( | ||
<div className="flex flex-col gap-2"> | ||
<input | ||
className="max-w-prose" | ||
name="file" | ||
ref={inputFileRef} | ||
type="file" | ||
required | ||
onChange={handleFileSelection} | ||
/> | ||
{errorMessage && <FormError error={errorMessage} />} | ||
</div> | ||
); | ||
}; | ||
|
||
const AvatarPreview = ({ | ||
imageUrl, | ||
showProgressIndicator = false, | ||
}: { | ||
imageUrl?: string; | ||
showProgressIndicator?: boolean; | ||
}) => ( | ||
<div className="flex flex-col gap-2"> | ||
<label htmlFor="avatarImage" className="block"> | ||
Profilová fotka: | ||
</label> | ||
<Image | ||
src={imageUrl ?? defaultAvatarUrl} | ||
className={clsx( | ||
"h-[100px] w-[100px] rounded-full bg-gray object-cover shadow", | ||
showProgressIndicator && "animate-pulse", | ||
)} | ||
alt="Náhled současné profilovky" | ||
width={100} | ||
height={100} | ||
/> | ||
</div> | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import crypto from "crypto"; | ||
|
||
import { NextResponse } from "next/server"; | ||
|
||
import { put } from "@vercel/blob"; | ||
|
||
import { withAuthenticatedUser } from "~/src/auth"; | ||
|
||
export async function POST(request: Request): Promise<Response> { | ||
return withAuthenticatedUser(async () => { | ||
if (!request.body) { | ||
return new Response("Missing payload", { status: 400 }); | ||
} | ||
|
||
// We use the original filename to get the extension | ||
const { searchParams } = new URL(request.url); | ||
const originalFilename = searchParams.get("filename"); | ||
if (!originalFilename) { | ||
return new Response("Missing filename", { status: 400 }); | ||
} | ||
|
||
// But the file name itself is an 8-character prefix of the SHA1 | ||
// of file content | ||
const data = await getArrayBufferView(request.body); | ||
const hash = shasumPrefix(new Uint8Array(data)); | ||
const target = hash + "." + getFilenameExtension(originalFilename); | ||
|
||
// Upload | ||
const blob = await put(target, data, { | ||
addRandomSuffix: false, | ||
access: "public", | ||
token: process.env.USER_BLOB_READ_WRITE_TOKEN, | ||
}); | ||
|
||
return NextResponse.json(blob); | ||
}); | ||
} | ||
|
||
const getArrayBufferView = async (data: ReadableStream<Uint8Array>) => | ||
new Response(data).arrayBuffer(); | ||
|
||
const shasumPrefix = (data: crypto.BinaryLike) => | ||
crypto.createHash("sha1").update(data).digest("hex").slice(0, 8); | ||
|
||
const getFilenameExtension = (name: string) => | ||
name.split(".").pop()?.toLowerCase(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters