Files
THE-TIP-TOP/frontend/src/services/auth.js
Emma781227 65d6b23233 mise a jour
2026-07-08 07:10:49 +02:00

67 lines
2.1 KiB
JavaScript

const BASE = '/api/auth'
function apiError(message, status) {
const err = new Error(message)
err.status = status
return err
}
export async function loginApi({ email, password }) {
const res = await fetch(`${BASE}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
})
const data = await res.json()
if (!res.ok) throw apiError(data.message || 'Erreur de connexion.', res.status)
return data
}
export async function registerApi({ email, firstname, lastname, password }) {
const res = await fetch(`${BASE}/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, firstname, lastname, password }),
})
const data = await res.json()
if (!res.ok) throw apiError(data.message || "Erreur lors de l'inscription.", res.status)
return data
}
export async function verifyCodeApi({ email, code }) {
const res = await fetch(`${BASE}/verify-code`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, code }),
})
const data = await res.json()
if (!res.ok) throw apiError(data.message || 'Code invalide.', res.status)
return data
}
export async function deleteAccountApi() {
const token = localStorage.getItem('token')
const res = await fetch(`${BASE}/account`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
})
const data = await res.json()
if (!res.ok) throw apiError(data.message || 'Erreur lors de la suppression.', res.status)
return data
}
export async function changePasswordApi({ currentPassword, newPassword }) {
const token = localStorage.getItem('token')
const res = await fetch(`${BASE}/change-password`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ currentPassword, newPassword }),
})
const data = await res.json()
if (!res.ok) throw apiError(data.message || 'Erreur lors du changement de mot de passe.', res.status)
return data
}