summaryrefslogtreecommitdiff
path: root/front/src/Authentication/LoginPage.tsx
blob: e98c5062774c54ccb46fc6ba80cc2b536b9bf367 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import axios from "axios";
import { useContext, useState } from "react";
import { useNavigate } from "react-router";
import { BackendURL } from "../Config";
import { Authentication, SaveState } from "./ContextProvider";
import { useCookies } from 'react-cookie';
import { GetLocalizedString } from "../Locales/Locales";
import { LanguageContext } from "../Locales/Context";

const LoginURL = `${BackendURL}/auth/login`;

function LoginPage() {
    const lang = useContext(LanguageContext);

    const [username, setUsername] = useState<string>("");
    const [passw, setPassw] = useState<string>("");
    const navigate = useNavigate();

    function SetAuthState(newAuthState: Authentication | null) {
        if (newAuthState) {
            console.log(`Logging in as ${newAuthState.User}...`);
        } else {
            console.log(`Logging out...`);
        }
        SaveState(newAuthState, (cookie: string) => {
            document.cookie = `X-AUTH-TOKEN=${cookie}; path=/;`;
        })
    }

    return (
        <div>
            <h2> { GetLocalizedString("Username", lang) } </h2>
            <input onChange={ev => setUsername(ev.target.value)} />
            <h2> { GetLocalizedString("Password", lang) } </h2>
            <input onChange={ev => setPassw(ev.target.value)} />
            <button onClick={() => {
                Login(username, passw, (data) => {
                    SetAuthState(data);
                    navigate("/");
                    window.location.reload();
                });
            }}> { GetLocalizedString("Log in", lang) } </button>
        </div>
    );
}

async function Login(username: string, passw: string, onSuccess: (data: Authentication) => void) {
    await axios.post<Authentication>(
        LoginURL, {
            Username: username,
            Password: passw
        }
    ).then(resp => {
        onSuccess(resp.data);
    }).catch(err => {
        console.log(`Failed to send a login responce: ${err}`);
    });
}

export default LoginPage;