diff --git a/src/blog/providers/Author.tsx b/src/blog/providers/Author.tsx index a42ae3e..64f5d23 100644 --- a/src/blog/providers/Author.tsx +++ b/src/blog/providers/Author.tsx @@ -95,7 +95,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children } }; - /** 🔹 Auto-load current user if token exists */ const fetchCurrentUser = async () => { if (!token) return; @@ -113,6 +112,54 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children } }; + /** -------------------------------------------- + * 🔹 Upload avatar binary → return URL + * -------------------------------------------- */ + const uploadAvatar = async (file: File): Promise => { + try { + const arrayBuffer = await file.arrayBuffer(); + const binary = new Uint8Array(arrayBuffer); + + const res = await fetch('/media/upload', { + method: 'POST', + headers: { + 'Content-Type': file.type, + 'Content-Disposition': `attachment; filename="${file.name}"`, + }, + body: binary, + }); + + if (!res.ok) throw new Error('Avatar upload failed'); + + const data = await res.json(); + return data.url; // "/media/uploads/uuid.jpg" + } catch (err) { + console.error('Failed to upload avatar:', err); + return null; + } + }; + + /** -------------------------------------------- + * 🔹 Full flow: upload avatar → update profile + * -------------------------------------------- */ + const updateAvatar = async (file: File) => { + if (!currentUser) return; + + const url = await uploadAvatar(file); + if (!url) { + setError("Failed to upload avatar"); + return; + } + + // Update the user's avatar + const updated = await updateProfile({ + ...currentUser, + avatar: url, + }); + + return updated; + }; + /** 🔹 On mount, try to fetch user if token exists */ useEffect(() => { if (token) fetchCurrentUser(); @@ -131,6 +178,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children register, refreshAuthors, updateProfile, + uploadAvatar, + updateAvatar, }} > {children} diff --git a/src/blog/types/contexts.ts b/src/blog/types/contexts.ts index 0aab367..e1f07c2 100644 --- a/src/blog/types/contexts.ts +++ b/src/blog/types/contexts.ts @@ -18,4 +18,6 @@ export interface AuthContextModel { logout: () => void; refreshAuthors: () => Promise; updateProfile: (user: AuthorModel) => Promise; + uploadAvatar: (file: File) => Promise; + updateAvatar: (file: File) => Promise; }