feat: implement useAuth composable for authentication.
This commit is contained in:
parent
53314dfd7e
commit
9fd217e1db
1 changed files with 32 additions and 0 deletions
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue