source: reactapp/src/Pages/Login.js@ c68150f

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

left: moderation, oAuth, messaging

  • Property mode set to 100644
File size: 2.9 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";
6import { LoginButton, LoginInput } from "../Components/Styled/Login.style";
7const LOGIN_URL = "/login";
8
9const Login = () => {
10 const { auth, setAuth } = useContext(AuthApi);
11 const userRef = useRef();
12 const errRef = useRef();
13
14 const [username, setUsername] = useState("");
15 const [password, setPassword] = useState("");
16 const [errMsg, setErrMsg] = useState("");
17
18 useEffect(() => {
19 userRef.current.focus();
20 }, []);
21
22 const handleSubmit = async (e) => {
23 e.preventDefault();
24
25 const response = await axios.post(
26 LOGIN_URL,
27 `username=${username}&password=${password}`,
28 {
29 headers: {
30 "content-type": "application/x-www-form-urlencoded",
31 withCredentials: true,
32 },
33 }
34 );
35 if (!response.request.responseURL.includes("error")) {
36 // ako NE redirektira na /login?error
37 var in30Minutes = 1 / 48;
38 Cookies.set("JSESSIONID", response.data.sessionId, {
39 expires: in30Minutes,
40 });
41 setAuth(true);
42 setErrMsg("");
43 } else {
44 setErrMsg("Погрешно корисиничко име и/или лозинка");
45 }
46
47 setUsername("");
48 setPassword("");
49 };
50
51 return auth ? (
52 <Navigate to="/user_dashboard" />
53 ) : (
54 <div
55 style={{
56 marginTop: "140px",
57 display: "flex",
58 alignItems: "center",
59 flexFlow: "column",
60 width: "fit-content",
61 margin: "auto",
62 border: "2px solid lightgrey",
63 padding: "25px",
64 boxShadow: "2px 2px 6px #aaaaaa",
65 marginBottom: "80px",
66 }}
67 >
68 <h2>Најава</h2>
69 <form
70 onSubmit={handleSubmit}
71 style={{
72 display: "flex",
73 flexDirection: "column",
74 alignItems: "center",
75 width: "400px",
76 }}
77 >
78 <LoginInput
79 type="text"
80 id="username"
81 ref={userRef}
82 autoComplete="off"
83 onChange={(e) => setUsername(e.target.value)}
84 value={username}
85 required
86 placeholder="Email"
87 />
88 <LoginInput
89 type="password"
90 id="password"
91 onChange={(e) => setPassword(e.target.value)}
92 value={password}
93 placeholder="Лозинка"
94 required
95 />
96 <LoginButton>Најави се</LoginButton>
97 <p
98 ref={errRef}
99 className={errMsg ? "errmsg" : "offscreen"}
100 style={{ color: "red", marginTop: "20px" }}
101 >
102 {errMsg}
103 </p>
104 </form>
105 <p style={{ marginTop: "20px" }}>
106 Немаш сметка? <a href="/registration">Регистрирај се</a>{" "}
107 </p>
108 </div>
109 );
110};
111
112export default Login;
Note: See TracBrowser for help on using the repository browser.