diff --git a/src/components/form.jsx b/src/components/form.jsx index df7a9b7..16e1d8a 100644 --- a/src/components/form.jsx +++ b/src/components/form.jsx @@ -1,22 +1,39 @@ +import { useState } from "react"; +import login from "../utils/login.js"; +import getUser from "../utils/getUser.js"; + function LoginForm({ className }) { + + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + + async function handleSubmit(e) { + + e.preventDefault(); + + await login(email, password); + getUser(); + + } + return ( -
+

Connexion


- + setEmail(e.target.value)} required/>
- + setPassword(e.target.value)} required/>
- - + +
); } export default LoginForm; diff --git a/src/utils/getUser.js b/src/utils/getUser.js new file mode 100644 index 0000000..5345926 --- /dev/null +++ b/src/utils/getUser.js @@ -0,0 +1,12 @@ +export default async function getUser() { + await fetch('http://localhost:8000/api/me', { + method: 'GET', + credentials: 'include', + headers: { + 'Accept': 'application/json' + } + }) + .then(res => res.json()) + .then(data => console.log('Utilisateur connecté :', data)) + .catch(err => console.error('Erreur :', err)); +} \ No newline at end of file diff --git a/src/utils/getXSRF.js b/src/utils/getXSRF.js new file mode 100644 index 0000000..1bed25f --- /dev/null +++ b/src/utils/getXSRF.js @@ -0,0 +1,19 @@ +export default async function getXSRFToken() { + const response = await fetch('http://localhost:8000/sanctum/csrf-cookie', { + method: 'GET', + credentials: 'include' + }); + + if (!response.ok && response.status !== 204) { + throw new Error(`Error : ${response.status}`); + } + + const name = 'XSRF-TOKEN'; + const value = `; ${document.cookie}`; + const parts = value.split(`; ${name}=`); + if (parts.length === 2) { + return decodeURIComponent(parts.pop().split(';').shift()); + } + + throw new Error('Error: Invalid XSRF-TOKEN'); +} diff --git a/src/utils/login.js b/src/utils/login.js new file mode 100644 index 0000000..4174113 --- /dev/null +++ b/src/utils/login.js @@ -0,0 +1,33 @@ +import getXSRFToken from "./getXSRF.js"; + +export default async function login(email, password) { + const csrfToken = await getXSRFToken(); + + + await fetch('http://localhost:8000/api/login', { + method: 'POST', + credentials: 'include', + headers: { + 'Content-Type': 'application/json', + 'X-XSRF-TOKEN': csrfToken, + 'Accept': 'application/json' + }, + body: JSON.stringify({ + email: email, + password: password + }) + }) + .then(response => { + console.log('Code HTTP :', response.status); + if (!response.ok) { + throw new Error(`Erreur HTTP ${response.status}`); + } + return response.json(); + }) + .then(data => { + console.log('Connexion réussie ! Données utilisateur :', data); + }) + .catch(error => { + console.error('Erreur lors de la connexion :', error.message); + }); +} \ No newline at end of file