web-base/react/shared/views/login.jsx

329 lines
13 KiB
React
Raw Normal View History

import {
Box,
2023-01-14 09:51:46 +01:00
Button,
Checkbox, CircularProgress, Container,
FormControlLabel,
Grid,
Link, styled,
2023-01-14 09:51:46 +01:00
TextField,
Typography
2024-04-05 17:14:36 +02:00
} from "@mui/material";
2023-01-14 09:51:46 +01:00
2024-04-05 17:14:36 +02:00
import {Alert} from '@mui/lab';
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
2024-04-05 17:14:36 +02:00
import ReplayIcon from '@mui/icons-material/Replay';
2023-01-14 09:51:46 +01:00
import LanguageSelection from "../elements/language-selection";
import {decodeText, encodeText, getParameter, removeParameter} from "shared/util";
import {LocaleContext} from "shared/locale";
const LoginContainer = styled(Container)((props) => ({
marginTop: props.theme.spacing(5),
paddingBottom: props.theme.spacing(1),
borderColor: props.theme.palette.primary.main,
borderStyle: "solid",
borderWidth: 1,
borderRadius: 5,
"& h1 > img": {
marginRight: props.theme.spacing(2),
2023-01-14 09:51:46 +01:00
width: "60px",
height: "60px"
}
}));
const ResponseAlert = styled(Alert)((props) => ({
marginBottom: props.theme.spacing(2),
}));
2023-01-14 09:51:46 +01:00
export default function LoginForm(props) {
const api = props.api;
2023-01-16 21:47:23 +01:00
// inputs
2023-01-14 09:51:46 +01:00
let [username, setUsername] = useState("");
let [password, setPassword] = useState("");
let [rememberMe, setRememberMe] = useState(true);
let [emailConfirmed, setEmailConfirmed] = useState(null);
let [tfaCode, set2FACode] = useState("");
2023-01-16 21:47:23 +01:00
// 2fa
// 0: not sent, 1: sent, 2: retry
let [tfaToken, set2FAToken] = useState(api.user?.twoFactorToken || { authenticated: false, type: null, step: 0 });
2023-01-14 09:51:46 +01:00
let [error, setError] = useState("");
2023-01-16 21:47:23 +01:00
const abortController = new AbortController();
const abortSignal = abortController.signal;
// state
let [isLoggingIn, setLoggingIn] = useState(false);
2023-01-14 09:51:46 +01:00
let [loaded, setLoaded] = useState(false);
// ui
let passwordRef = useRef();
2023-01-14 09:51:46 +01:00
const {translate: L, currentLocale, requestModules} = useContext(LocaleContext);
const onUpdateLocale = useCallback(() => {
requestModules(api, ["general", "account"], currentLocale).then(data => {
setLoaded(true);
if (!data.success) {
alert(data.msg);
}
});
}, [currentLocale]);
useEffect(() => {
onUpdateLocale();
}, [currentLocale]);
const onLogin = useCallback(() => {
if (!isLoggingIn) {
setError("");
setLoggingIn(true);
removeParameter("success");
api.login(username, password, rememberMe).then((res) => {
2023-01-16 21:47:23 +01:00
let twoFactorToken = res.twoFactorToken || { };
set2FAToken({ ...twoFactorToken, authenticated: false, step: 0, error: "" });
2023-01-14 09:51:46 +01:00
setLoggingIn(false);
setPassword("");
if (!res.success) {
setEmailConfirmed(res.emailConfirmed);
setError(res.msg);
2023-01-16 21:47:23 +01:00
} else if (!twoFactorToken.type) {
2023-01-14 09:51:46 +01:00
props.onLogin();
}
});
}
}, [api, isLoggingIn, password, props, rememberMe, username]);
const onSubmit2FA = useCallback(() => {
setLoggingIn(true);
2023-01-16 21:47:23 +01:00
api.verifyTotp2FA(tfaCode).then((res) => {
2023-01-14 09:51:46 +01:00
setLoggingIn(false);
2023-01-16 21:47:23 +01:00
if (res.success) {
set2FAToken({ ...tfaToken, authenticated: true });
props.onLogin();
} else {
set2FAToken({ ...tfaToken, step: 2, error: res.msg });
}
2023-01-14 09:51:46 +01:00
});
2023-01-16 21:47:23 +01:00
}, [tfaCode, tfaToken, props]);
2023-01-14 09:51:46 +01:00
const onCancel2FA = useCallback(() => {
2023-01-16 21:47:23 +01:00
abortController.abort();
2023-01-14 09:51:46 +01:00
props.onLogout();
2023-01-16 21:47:23 +01:00
set2FAToken({authenticated: false, step: 0, error: ""});
}, [props, abortController]);
2023-01-14 09:51:46 +01:00
useEffect(() => {
2023-01-16 21:47:23 +01:00
if (!api.loggedIn) {
2023-01-14 09:51:46 +01:00
return;
}
2023-01-16 21:47:23 +01:00
if (!tfaToken || !tfaToken.confirmed || tfaToken.authenticated || tfaToken.type !== "fido") {
2023-01-14 09:51:46 +01:00
return;
}
2023-01-16 21:47:23 +01:00
let step = tfaToken.step || 0;
if (step !== 0) {
return;
2023-01-14 09:51:46 +01:00
}
2023-01-16 21:47:23 +01:00
set2FAToken({ ...tfaToken, step: 1, error: "" });
navigator.credentials.get({
publicKey: {
challenge: encodeText(window.atob(tfaToken.challenge)),
allowCredentials: [{
id: encodeText(window.atob(tfaToken.credentialID)),
type: "public-key",
}],
userVerification: "discouraged",
},
signal: abortSignal
}).then((res) => {
let credentialID = res.id;
let clientDataJson = decodeText(res.response.clientDataJSON);
let authData = window.btoa(decodeText(res.response.authenticatorData));
let signature = window.btoa(decodeText(res.response.signature));
api.verifyKey2FA(credentialID, clientDataJson, authData, signature).then((res) => {
if (!res.success) {
set2FAToken({ ...tfaToken, step: 2, error: res.msg });
} else {
props.onLogin();
}
});
}).catch(e => {
set2FAToken({ ...tfaToken, step: 2, error: e.toString() });
});
2023-01-18 14:37:34 +01:00
}, [api.loggedIn, tfaToken, props.onLogin, props.onKey2FA, abortSignal]);
2023-01-14 09:51:46 +01:00
const createForm = () => {
// 2FA
2023-01-16 21:47:23 +01:00
if (api.loggedIn && tfaToken.type) {
if (tfaToken.type === "totp") {
return <>
<div>{L("account.2fa_title")}:</div>
2023-01-14 09:51:46 +01:00
<TextField
2023-01-16 21:47:23 +01:00
variant={"outlined"} margin={"normal"}
id={"code"} label={L("account.6_digit_code")} name={"code"}
autoComplete={"code"}
2023-01-14 09:51:46 +01:00
required fullWidth autoFocus
value={tfaCode} onChange={(e) => set2FACode(e.target.value)}
2024-04-07 14:23:59 +02:00
onKeyDown={e => e.key === "Enter" && onSubmit2FA()} />
2023-01-16 21:47:23 +01:00
{
tfaToken.error ? <ResponseAlert severity="error">{tfaToken.error}</ResponseAlert> : <></>
2023-01-16 21:47:23 +01:00
}
<Grid container spacing={2}>
2023-01-16 21:47:23 +01:00
<Grid item xs={6}>
<Button
fullWidth variant={"contained"}
color={"inherit"} size={"medium"}
disabled={isLoggingIn}
onClick={onCancel2FA}>
{L("general.go_back")}
</Button>
</Grid>
<Grid item xs={6}>
<Button
type="submit" fullWidth variant="contained"
color="primary" size={"medium"}
disabled={isLoggingIn || tfaToken.type !== "totp"}
onClick={onSubmit2FA}>
{isLoggingIn ?
<>{L("general.submitting")} <CircularProgress size={15}/></> :
L("general.submit")
}
</Button>
</Grid>
2023-01-14 09:51:46 +01:00
</Grid>
2023-01-16 21:47:23 +01:00
</>
} else if (tfaToken.type === "fido") {
return <>
<div>{L("account.2fa_title")}:</div>
<br />
{L("account.2fa_text")}
<Box mt={2} textAlign={"center"}>
{tfaToken.step !== 2
? <CircularProgress/>
: <Box>
2023-01-16 21:47:23 +01:00
<div><b>{L("general.something_went_wrong")}:</b><br />{tfaToken.error}</div>
<Button onClick={() => set2FAToken({ ...tfaToken, step: 0, error: "" })}
variant={"outlined"} color={"secondary"} size={"small"}>
<ReplayIcon />&nbsp;{L("general.retry")}
</Button>
</Box>
2023-01-16 21:47:23 +01:00
}
</Box>
<Grid container spacing={2}>
2023-01-16 21:47:23 +01:00
<Grid item xs={6}>
<Button
fullWidth variant={"contained"}
color={"inherit"} size={"medium"}
disabled={isLoggingIn}
onClick={onCancel2FA}>
{L("general.go_back")}
</Button>
</Grid>
<Grid item xs={6}>
<Button
type="submit" fullWidth variant="contained"
color="primary" size={"medium"}
disabled={isLoggingIn || tfaToken.type !== "totp"}
onClick={onSubmit2FA}>
{isLoggingIn ?
<>{L("general.submitting")} <CircularProgress size={15}/></> :
L("general.submit")
}
</Button>
</Grid>
2023-01-14 09:51:46 +01:00
</Grid>
2023-01-16 21:47:23 +01:00
</>
}
2023-01-14 09:51:46 +01:00
}
return <>
<TextField
variant={"outlined"} margin={"normal"}
label={L("account.username")} name={"username"}
autoComplete={"username"} disabled={isLoggingIn}
2023-01-14 09:51:46 +01:00
required fullWidth autoFocus
value={username} onChange={(e) => setUsername(e.target.value)}
onKeyDown={e => e.key === "Enter" && passwordRef.current && passwordRef.current.focus()}
2023-01-14 09:51:46 +01:00
/>
<TextField
variant={"outlined"} margin={"normal"}
name={"password"} label={L("account.password")} type={"password"}
autoComplete={"current-password"}
2023-01-14 09:51:46 +01:00
required fullWidth disabled={isLoggingIn}
value={password} onChange={(e) => setPassword(e.target.value)}
onKeyDown={e => e.key === "Enter" && onLogin()}
inputRef={passwordRef}
2023-01-14 09:51:46 +01:00
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary"/>}
label={L("account.remember_me")}
checked={rememberMe} onClick={(e) => setRememberMe(!rememberMe)}
/>
{
error
? <ResponseAlert severity={"error"}>
2023-01-14 09:51:46 +01:00
{error}
{emailConfirmed === false
2023-03-05 15:30:06 +01:00
? <> <Link href={"/resendConfirmEmail"}>Click here</Link> to resend the confirmation email.</>
2023-01-14 09:51:46 +01:00
: <></>
}
</ResponseAlert>
2023-01-14 09:51:46 +01:00
: (successMessage
? <ResponseAlert severity={"success"}>{successMessage}</ResponseAlert>
2023-01-14 09:51:46 +01:00
: <></>)
}
<Button
type={"submit"} fullWidth variant={"contained"}
color={"primary"}
2023-01-14 09:51:46 +01:00
size={"large"}
disabled={isLoggingIn}
onClick={onLogin}>
{isLoggingIn ?
<>{L("account.signing_in")} <CircularProgress size={15}/></> :
L("account.sign_in")
}
</Button>
<Grid container>
<Grid item xs>
<Link href="/resetPassword" variant="body2">
{L("account.forgot_password")}
</Link>
</Grid>
{ props.info.registrationAllowed ?
<Grid item>
<Link href="/register" variant="body2">
{L("account.register_text")}
</Link>
</Grid> : <></>
}
</Grid>
</>
}
if (!loaded) {
2023-01-18 14:37:34 +01:00
return <Box textAlign={"center"} mt={2}>
<h2>{L("general.loading", "Loading")}</h2>
<CircularProgress size={"32px"}/>
</Box>
2023-01-14 09:51:46 +01:00
}
let successMessage = getParameter("success");
return <LoginContainer maxWidth={"xs"}>
<Box mt={2}>
<Typography component="h1" variant="h4">
<img src={"/img/icons/logo.png"} alt={"Logo"} height={48} />
{props.info.siteName}
</Typography>
{ createForm() }
<LanguageSelection api={api} />
</Box>
</LoginContainer>
2023-01-14 09:51:46 +01:00
}