source: reactapp/src/Pages/Login.js@ 6eba109

main
Last change on this file since 6eba109 was 6eba109, checked in by unknown <mlviktor23@…>, 23 months ago

implemented authentication in react

  • Property mode set to 100644
File size: 2.4 KB
Line 
1import React, { useRef, useState, useEffect, useContext } from "react";
2import { Navigate } from "react-router-dom";
3import AuthApi from "../api/AuthApi";
4import axios from "../api/axios";
5import Cookies from "js-cookie";
6const LOGIN_URL = "/login";
7
8const Login = () => {
9 const { auth, setAuth } = useContext(AuthApi);
10 const userRef = useRef();
11 const errRef = useRef();
12
13 const [username, setUsername] = useState("");
14 const [password, setPassword] = useState("");
15 const [errMsg, setErrMsg] = useState("");
16
17 useEffect(() => {
18 userRef.current.focus();
19 }, []);
20
21 const handleSubmit = async (e) => {
22 e.preventDefault();
23
24 const response = await axios.post(
25 LOGIN_URL,
26 `username=${username}&password=${password}`,
27 {
28 headers: {
29 "content-type": "application/x-www-form-urlencoded",
30 withCredentials: true,
31 },
32 }
33 );
34 if (!response.request.responseURL.includes("error")) {
35 // ako NE redirektira na /login?error
36 Cookies.set("JSESSIONID", response.data.sessionId);
37 setAuth(true);
38 setErrMsg("");
39 } else {
40 setErrMsg("Погрешно корисиничко име и/или лозинка");
41 }
42
43 setUsername("");
44 setPassword("");
45 };
46
47 const handleLogout = () => {
48 setAuth(false);
49 Cookies.remove("JSESSIONID");
50 };
51
52 return auth ? (
53 /*
54 <div style={{ marginTop: "140px" }}>
55 <h1>Успешна најава!</h1>
56 <br />
57 <p>
58 <a href="/user">Оди на protected</a>
59 </p>
60 <button onClick={handleLogout}>Одјави се</button>
61 </div>
62 */
63 <Navigate to="/user" />
64 ) : (
65 <div style={{ marginTop: "140px" }}>
66 <p ref={errRef} className={errMsg ? "errmsg" : "offscreen"}>
67 {errMsg}
68 </p>
69 <h1>Најава</h1>
70 <form onSubmit={handleSubmit}>
71 <label htmlFor="username">E-mail:</label>
72 <input
73 type="text"
74 id="username"
75 ref={userRef}
76 autoComplete="off"
77 onChange={(e) => setUsername(e.target.value)}
78 value={username}
79 required
80 />
81 <label htmlFor="password">Лозинка:</label>
82 <input
83 type="password"
84 id="password"
85 onChange={(e) => setPassword(e.target.value)}
86 value={password}
87 required
88 />
89 <button>Најави се</button>
90 </form>
91 </div>
92 );
93};
94
95export default Login;
Note: See TracBrowser for help on using the repository browser.