feat: implement useAuth composable for authentication.

This commit is contained in:
supalerk-ar66 2026-01-28 11:54:20 +07:00
parent 53314dfd7e
commit 9fd217e1db

View file

@ -251,6 +251,37 @@ export const useAuth = () => {
}
}
// ฟังก์ชันอัปโหลดรูปโปรไฟล์ (Upload Avatar)
const uploadAvatar = async (file: File) => {
if (!token.value) return { success: false, error: 'ไม่พบ Token การใช้งาน' }
const formData = new FormData()
formData.append('file', file)
try {
const data = await $fetch<{ code: number; message: string; data: { avatar_url: string; id: number } }>(`${API_BASE_URL}/user/upload-avatar`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token.value}`
},
body: formData
})
// อัปเดตข้อมูล User ใน Local State เมื่ออัปโหลดสำเร็จ
if (data.data.avatar_url && user.value && user.value.profile) {
user.value.profile.avatar_url = data.data.avatar_url
} else {
// หากไม่มีข้อมูลใน cache ให้ดึงใหม่
await fetchUserProfile(true)
}
return { success: true, data: data.data }
} catch (err: any) {
console.error('Upload avatar failed:', err)
return { success: false, error: err.data?.message || 'อัปโหลดรูปภาพไม่สำเร็จ' }
}
}
// ฟังก์ชันขอ Access Token ใหม่ด้วย Refresh Token
const refreshAccessToken = async () => {
if (!refreshToken.value) return false
@ -313,6 +344,7 @@ export const useAuth = () => {
requestPasswordReset,
confirmResetPassword,
changePassword,
uploadAvatar,
refreshAccessToken,
logout
}