matiru

Blockchain-Based Supply Chain Transparency for Agricultural Produce

frontend/screens/Login.js (2109B)


 1import { useState, useContext } from "react";
 2import { Text, TextInput, TouchableOpacity, Alert } from "react-native";
 3import { SafeAreaView } from "react-native-safe-area-context";
 4import { MaterialCommunityIcons } from "@expo/vector-icons";
 5
 6import styles, { colors } from "../styles";
 7import { AuthContext } from "../AuthContext";
 8import { api } from "../services/api";
 9
10export default function LoginScreen({ route, navigation }) {
11  const { role } = route.params || {};
12  const [username, setUsername] = useState("");
13  const [password, setPassword] = useState("");
14  const { login } = useContext(AuthContext);
15
16  const handleLogin = async () => {
17    if (!username || !password) {
18      Alert.alert("Error", "Enter username and password");
19      return;
20    }
21
22    try {
23      const data = await api.login({ username, password });
24
25      if (role && data.role !== role) {
26        return Alert.alert(
27          "Error",
28          `Account role mismatch. Expected ${role}, got ${data.role}`
29        );
30      }
31
32      await login({
33        token: data.token,
34        id: data.id,
35        role: data.role,
36        username: data.username,
37      });
38
39      navigation.replace(data.role, { userId: data.id });
40    } catch (err) {
41      Alert.alert("Login failed", err.message);
42    }
43  };
44
45  return (
46    <SafeAreaView style={styles.container}>
47      <Text style={styles.title}>Login as {role}</Text>
48      <TextInput
49        style={styles.input}
50        placeholder="Username"
51        value={username}
52        onChangeText={setUsername}
53        autoCapitalize="none"
54      />
55      <TextInput
56        style={styles.input}
57        placeholder="Password"
58        secureTextEntry
59        value={password}
60        onChangeText={setPassword}
61      />
62      <TouchableOpacity
63        style={[
64          styles.bigButton,
65          { backgroundColor: colors.darkGreen, width: "100%" },
66        ]}
67        onPress={handleLogin}
68      >
69        <MaterialCommunityIcons name="login" size={24} color="white" />
70        <Text style={styles.bigButtonText}>Login</Text>
71      </TouchableOpacity>
72    </SafeAreaView>
73  );
74}