source: reactapp/src/Pages/Login.js@ 702ca77

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

added current user/logout in header, display karma on user dashboard, started add post functionality in react

  • Property mode set to 100644
File size: 2.1 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 return auth ? (
48 <Navigate to="/user_dashboard" />
49 ) : (
50 <div style={{ marginTop: "140px" }}>
51 <p ref={errRef} className={errMsg ? "errmsg" : "offscreen"}>
52 {errMsg}
53 </p>
54 <h1>Најава</h1>
55 <form onSubmit={handleSubmit}>
56 <label htmlFor="username">E-mail:</label>
57 <input
58 type="text"
59 id="username"
60 ref={userRef}
61 autoComplete="off"
62 onChange={(e) => setUsername(e.target.value)}
63 value={username}
64 required
65 />
66 <label htmlFor="password">Лозинка:</label>
67 <input
68 type="password"
69 id="password"
70 onChange={(e) => setPassword(e.target.value)}
71 value={password}
72 required
73 />
74 <button>Најави се</button>
75 </form>
76 </div>
77 );
78};
79
80export default Login;
Note: See TracBrowser for help on using the repository browser.