network-resurrector/src/features/login/components/LoginContainer.js

63 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-12-23 03:37:26 +02:00
import React, { useContext } from "react";
2020-12-24 15:56:30 +02:00
import LoginCard from "./LoginCard";
import { authenticate, invalidate } from "../../../utils/identity";
2020-12-24 02:39:48 +02:00
import {
ApplicationStateContext,
ApplicationDispatchContext
} from "../../../state/ApplicationContexts";
2020-12-24 15:56:30 +02:00
import { useToast, useAuthorizationToken } from "../../../hooks";
import { useTranslation } from "react-i18next";
2020-12-24 15:56:30 +02:00
import LoggedInComponent from "./LoggedInComponent";
2020-12-08 03:03:15 +02:00
const LoginContainer = () => {
2020-12-23 03:37:26 +02:00
const state = useContext(ApplicationStateContext);
2020-12-24 02:39:48 +02:00
const dispatchActions = useContext(ApplicationDispatchContext);
const { error } = useToast();
const { t } = useTranslation();
2020-12-24 15:56:30 +02:00
const { tokenIsValid } = useAuthorizationToken();
2020-12-24 02:39:48 +02:00
const handleChange = prop => event => {
dispatchActions.onCredentialsChange(prop, event.target.value);
};
2020-12-16 02:34:07 +02:00
2020-12-23 03:37:26 +02:00
const handleLogin = async () => {
const { userName, password } = state.credentials;
try {
const response = await authenticate(userName, password);
2020-12-24 05:32:35 +02:00
if (response.status === "SUCCESS") {
dispatchActions.onAuthorizationTokenChange(response.token);
} else if (response.status === "BAD_CREDENTIALS") {
error(t("Login.IncorrectCredentials"));
}
} catch (err) {
error(err.message);
}
2020-12-16 02:34:07 +02:00
};
2020-12-24 15:56:30 +02:00
const handleLogout = () => {
invalidate();
};
2020-12-16 02:34:07 +02:00
return (
<>
2020-12-24 15:56:30 +02:00
{tokenIsValid ? (
<LoggedInComponent
credentials={state.credentials}
onChange={handleChange}
onLogin={handleLogin}
onLogout={handleLogout}
/>
) : (
<LoginCard
credentials={state.credentials}
onChange={handleChange}
onLogin={handleLogin}
/>
)}
2020-12-16 02:34:07 +02:00
</>
);
2020-12-08 03:03:15 +02:00
};
export default LoginContainer;