import * as SecureStore from "@/utils/SecureStore" import { useRouter } from "expo-router" import { useRef, useState } from "react" import { Platform } from "react-native" import { Button, Dialog, Portal, Surface, Text, TextInput } from "react-native-paper" export default function Login() { const router = useRouter() const [name, setName] = useState(SecureStore.getItem('apiName') ?? "") const [password, setPassword] = useState("") const [errorDialogVisible, setErrorDialogVisible] = useState(false) const [errorTitle, setErrorTitle] = useState("") const [errorText, setErrorText] = useState("") const loginRef = useRef() const passwordRef = useRef() const hideErrorDialog = () => setErrorDialogVisible(false) async function onLogin() { const resp = await fetch("http://192.168.1.198:3000/auth/login/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: name, password: password }) }) .then(resp => resp.json()) .catch(err => { setErrorDialogVisible(true) setErrorTitle("Erreur") setErrorText("Une erreur inconnue est survenue lors de la connexion. Veuillez réessayer plus tard. " + err) }) if (!resp) return else if (resp.error) { setErrorDialogVisible(true) setErrorTitle(resp.error) setErrorText(resp.message) return } SecureStore.setItem("apiName", name) if (Platform.OS !== "web") { // Le stockage navigateur n'est pas sûr, on évite de stocker un mot de passe à l'intérieur SecureStore.setItem("apiPassword", password) } SecureStore.setItem("apiToken", resp.accessToken) if (router.canGoBack()) router.back() else router.navigate('/') } return ( setName(text)} onSubmitEditing={() => passwordRef?.current.focus()} style={{ margin: 8 }} /> setPassword(text)} onSubmitEditing={onLogin} secureTextEntry={true} style={{ margin: 8 }} /> {errorTitle} {errorText} ) }