import { Component, linkEvent } from "inferno"; import { GetSiteResponse, LoginResponse } from "lemmy-js-client"; import { i18n } from "../../i18next"; import { UserService } from "../../services"; import { HttpService, RequestState } from "../../services/HttpService"; import { isBrowser, myAuth, setIsoData, toast, validEmail } from "../../utils"; import { HtmlTags } from "../common/html-tags"; import { Spinner } from "../common/icon"; interface State { loginRes: RequestState; form: { username_or_email?: string; password?: string; totp_2fa_token?: string; }; showTotp: boolean; siteRes: GetSiteResponse; } export class Login extends Component { private isoData = setIsoData(this.context); state: State = { loginRes: { state: "empty" }, form: {}, showTotp: false, siteRes: this.isoData.site_res, }; constructor(props: any, context: any) { super(props, context); } componentDidMount() { // Navigate to home if already logged in if (UserService.Instance.myUserInfo) { this.context.router.history.push("/"); } } get documentTitle(): string { return `${i18n.t("login")} - ${this.state.siteRes.site_view.site.name}`; } get isLemmyMl(): boolean { return isBrowser() && window.location.hostname == "lemmy.ml"; } render() { return (
{this.loginForm()}
); } loginForm() { return (
{i18n.t("login")}
{this.state.showTotp && (
)}
); } async handleLoginSubmit(i: Login, event: any) { event.preventDefault(); const { password, totp_2fa_token, username_or_email } = i.state.form; if (username_or_email && password) { i.setState({ loginRes: { state: "loading" } }); const loginRes = await HttpService.client.login({ username_or_email, password, totp_2fa_token, }); switch (loginRes.state) { case "failed": { if (loginRes.msg === "missing_totp_token") { i.setState({ showTotp: true }); toast(i18n.t("enter_two_factor_code"), "info"); } i.setState({ loginRes: { state: "empty" } }); break; } case "success": { UserService.Instance.login(loginRes.data); const site = await HttpService.client.getSite({ auth: myAuth(), }); if (site.state === "success") { UserService.Instance.myUserInfo = site.data.my_user; } i.props.history.action === "PUSH" ? i.props.history.back() : i.props.history.replace("/"); break; } } } } handleLoginUsernameChange(i: Login, event: any) { i.state.form.username_or_email = event.target.value.trim(); i.setState(i.state); } handleLoginTotpChange(i: Login, event: any) { i.state.form.totp_2fa_token = event.target.value; i.setState(i.state); } handleLoginPasswordChange(i: Login, event: any) { i.state.form.password = event.target.value; i.setState(i.state); } async handlePasswordReset(i: Login, event: any) { event.preventDefault(); const email = i.state.form.username_or_email; if (email) { const res = await HttpService.client.passwordReset({ email }); if (res.state == "success") { toast(i18n.t("reset_password_mail_sent")); } } } }