[6eba109] | 1 | import React, { useRef, useState, useEffect, useContext } from "react";
|
---|
| 2 | import { Navigate } from "react-router-dom";
|
---|
| 3 | import AuthApi from "../api/AuthApi";
|
---|
[800779d] | 4 | import axios from "../api/axios";
|
---|
[6eba109] | 5 | import Cookies from "js-cookie";
|
---|
[800779d] | 6 | const LOGIN_URL = "/login";
|
---|
| 7 |
|
---|
| 8 | const Login = () => {
|
---|
[6eba109] | 9 | const { auth, setAuth } = useContext(AuthApi);
|
---|
[800779d] | 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 | );
|
---|
[6eba109] | 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 |
|
---|
[800779d] | 43 | setUsername("");
|
---|
| 44 | setPassword("");
|
---|
| 45 | };
|
---|
| 46 |
|
---|
[6eba109] | 47 | return auth ? (
|
---|
[702ca77] | 48 | <Navigate to="/user_dashboard" />
|
---|
[800779d] | 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 |
|
---|
| 80 | export default Login;
|
---|