60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
import { Button } from "../elements/Button";
|
|
import { Component, JSX, createRef } from "preact";
|
|
import { DefaultPageProps } from "../../types/DefaultPageProps";
|
|
import { ErrorMessage } from "../elements/ErrorMessage";
|
|
import { Form } from "../elements/forms/Form";
|
|
import { InputWithTitle } from "../elements/InputWithTitle";
|
|
import { Margin } from "../elements/Margin";
|
|
import { MarginInline } from "../elements/MarginInline";
|
|
import { PasswordInput } from "../elements/forms/PasswordInput";
|
|
import { TextInput } from "../elements/forms/TextInput";
|
|
import { route } from "preact-router";
|
|
import i18next from "i18next";
|
|
|
|
export class UsernameLoginForm extends Component<DefaultPageProps> {
|
|
errorMessageRef = createRef<ErrorMessage>();
|
|
|
|
render(): JSX.Element {
|
|
return (
|
|
<Form onSubmit={(data) => this.onSubmit(data)}>
|
|
<Margin>
|
|
<InputWithTitle title={i18next.t("log_in_username_input")}>
|
|
<TextInput name="username" required />
|
|
</InputWithTitle>
|
|
</Margin>
|
|
|
|
<Margin>
|
|
<InputWithTitle title={i18next.t("log_in_password_input")}>
|
|
<PasswordInput name="password" required />
|
|
</InputWithTitle>
|
|
</Margin>
|
|
|
|
<Margin>
|
|
<ErrorMessage ref={this.errorMessageRef} />
|
|
</Margin>
|
|
|
|
<MarginInline>
|
|
<Button text={i18next.t("log_in_btn")} color="primary" type="submit" />
|
|
</MarginInline>
|
|
</Form>
|
|
);
|
|
}
|
|
|
|
async onSubmit(data: FormData): Promise<void> {
|
|
const previousToken = this.props.settings.token;
|
|
|
|
try {
|
|
const res = await this.props.api.usernameLogin(
|
|
data.get("username") as string,
|
|
data.get("password") as string,
|
|
);
|
|
this.props.settings.token = res;
|
|
route("/");
|
|
} catch (e: unknown) {
|
|
const error = e as Error;
|
|
this.errorMessageRef.current.setErrorMessage(error.message);
|
|
this.props.settings.token = previousToken;
|
|
}
|
|
}
|
|
}
|