63 lines
1.7 KiB
JavaScript
63 lines
1.7 KiB
JavaScript
import React, { useContext } from "react";
|
|
import LoginCard from "./LoginCard";
|
|
import { authenticate, invalidate } from "../../../utils/identity";
|
|
import {
|
|
ApplicationStateContext,
|
|
ApplicationDispatchContext
|
|
} from "../../../state/ApplicationContexts";
|
|
import { useToast, useAuthorizationToken } from "../../../hooks";
|
|
import { useTranslation } from "react-i18next";
|
|
import LoggedInComponent from "./LoggedInComponent";
|
|
|
|
const LoginContainer = () => {
|
|
const state = useContext(ApplicationStateContext);
|
|
const dispatchActions = useContext(ApplicationDispatchContext);
|
|
const { error } = useToast();
|
|
const { t } = useTranslation();
|
|
const { tokenIsValid } = useAuthorizationToken();
|
|
|
|
const handleChange = prop => event => {
|
|
dispatchActions.onCredentialsChange(prop, event.target.value);
|
|
};
|
|
|
|
const handleLogin = async () => {
|
|
const { userName, password } = state.credentials;
|
|
|
|
try {
|
|
const response = await authenticate(userName, password);
|
|
if (response.status === "SUCCESS") {
|
|
dispatchActions.onAuthorizationTokenChange(response.token);
|
|
} else if (response.status === "BAD_CREDENTIALS") {
|
|
error(t("Login.IncorrectCredentials"));
|
|
}
|
|
} catch (err) {
|
|
error(err.message);
|
|
}
|
|
};
|
|
|
|
const handleLogout = () => {
|
|
invalidate();
|
|
};
|
|
|
|
return (
|
|
<>
|
|
{tokenIsValid ? (
|
|
<LoggedInComponent
|
|
credentials={state.credentials}
|
|
onChange={handleChange}
|
|
onLogin={handleLogin}
|
|
onLogout={handleLogout}
|
|
/>
|
|
) : (
|
|
<LoginCard
|
|
credentials={state.credentials}
|
|
onChange={handleChange}
|
|
onLogin={handleLogin}
|
|
/>
|
|
)}
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default LoginContainer;
|