1 | import React, { useState } from "react";
|
---|
2 | import { Link, useNavigate } from "react-router-dom";
|
---|
3 | import styles from "./Login.module.css";
|
---|
4 | import illustration from "../../assets/illustration_img.png";
|
---|
5 |
|
---|
6 | const LoginPage = ({onLogin}) => {
|
---|
7 | const [username, setUsername] = useState("");
|
---|
8 | const [password, setPassword] = useState("");
|
---|
9 | const [error, setError] = useState(null);
|
---|
10 | const navigate = useNavigate();
|
---|
11 |
|
---|
12 | const payload = {
|
---|
13 | username: username,
|
---|
14 | password: password
|
---|
15 | };
|
---|
16 |
|
---|
17 | const handleLogin = (e) => {
|
---|
18 | e.preventDefault();
|
---|
19 |
|
---|
20 | fetch("http://localhost:8080/api/auth/login", {
|
---|
21 | method: "POST",
|
---|
22 | headers: {
|
---|
23 | "Content-Type": "application/json",
|
---|
24 | },
|
---|
25 | body: JSON.stringify(payload),
|
---|
26 | })
|
---|
27 | .then((response) => {
|
---|
28 | if (!response.ok) {
|
---|
29 | throw new Error("Login failed: resp = " + response.statusText);
|
---|
30 | }
|
---|
31 | return response.json();
|
---|
32 | })
|
---|
33 | .then((data) => {
|
---|
34 | if (data.token) {
|
---|
35 | navigate("/Maps/FinkiMaps/Draw");
|
---|
36 | onLogin(data.token)
|
---|
37 | } else {
|
---|
38 | setError("Invalid username or password.");
|
---|
39 | }
|
---|
40 | })
|
---|
41 | .catch((error) => {
|
---|
42 | console.error("Login failed", error);
|
---|
43 | setError("Login failed. Please try again.");
|
---|
44 | });
|
---|
45 |
|
---|
46 | };
|
---|
47 |
|
---|
48 | return (
|
---|
49 | <div className={styles.wrapper}>
|
---|
50 | <div className={styles.illustration}>
|
---|
51 | <img src={illustration} alt="illustration" />
|
---|
52 | </div>
|
---|
53 | <div className={styles.form}>
|
---|
54 | <div className={styles.heading}>LOGIN</div>
|
---|
55 | <form onSubmit={handleLogin}>
|
---|
56 | <div>
|
---|
57 | <label htmlFor="username">Username</label>
|
---|
58 | <input
|
---|
59 | type="text"
|
---|
60 | id="name"
|
---|
61 | placeholder="Enter your username"
|
---|
62 | onChange={(e) => setUsername(e.target.value)}
|
---|
63 | value={username}
|
---|
64 | required
|
---|
65 | />
|
---|
66 | </div>
|
---|
67 | <div>
|
---|
68 | <label htmlFor="password">Password</label>
|
---|
69 | <input
|
---|
70 | type="password"
|
---|
71 | id="password"
|
---|
72 | placeholder="Enter your password"
|
---|
73 | onChange={(e) => setPassword(e.target.value)}
|
---|
74 | value={password}
|
---|
75 | required
|
---|
76 | />
|
---|
77 | </div>
|
---|
78 | {error && <p className={styles.error}>{error}</p>}
|
---|
79 | <button type="submit">Submit</button>
|
---|
80 | </form>
|
---|
81 | <p>
|
---|
82 | Don't have an account? <Link to="/Signup"> Sign Up </Link>
|
---|
83 | </p>
|
---|
84 | </div>
|
---|
85 | </div>
|
---|
86 | );
|
---|
87 | };
|
---|
88 |
|
---|
89 | export default LoginPage;
|
---|