]> Untitled Git - lemmy-ui.git/blob - src/shared/components/home/login.tsx
62e5721409beb93472e5a3157060b8d42319858e
[lemmy-ui.git] / src / shared / components / home / login.tsx
1 import { myAuth, setIsoData } from "@utils/app";
2 import { isBrowser } from "@utils/browser";
3 import { Component, linkEvent } from "inferno";
4 import { NavLink } from "inferno-router";
5 import { GetSiteResponse, LoginResponse } from "lemmy-js-client";
6 import { I18NextService, UserService } from "../../services";
7 import { HttpService, RequestState } from "../../services/HttpService";
8 import { toast } from "../../toast";
9 import { HtmlTags } from "../common/html-tags";
10 import { Spinner } from "../common/icon";
11
12 interface State {
13   loginRes: RequestState<LoginResponse>;
14   form: {
15     username_or_email?: string;
16     password?: string;
17     totp_2fa_token?: string;
18   };
19   showTotp: boolean;
20   siteRes: GetSiteResponse;
21 }
22
23 export class Login extends Component<any, State> {
24   private isoData = setIsoData(this.context);
25
26   state: State = {
27     loginRes: { state: "empty" },
28     form: {},
29     showTotp: false,
30     siteRes: this.isoData.site_res,
31   };
32
33   constructor(props: any, context: any) {
34     super(props, context);
35   }
36
37   componentDidMount() {
38     // Navigate to home if already logged in
39     if (UserService.Instance.myUserInfo) {
40       this.context.router.history.push("/");
41     }
42   }
43
44   get documentTitle(): string {
45     return `${I18NextService.i18n.t("login")} - ${
46       this.state.siteRes.site_view.site.name
47     }`;
48   }
49
50   get isLemmyMl(): boolean {
51     return isBrowser() && window.location.hostname == "lemmy.ml";
52   }
53
54   render() {
55     return (
56       <div className="login container-lg">
57         <HtmlTags
58           title={this.documentTitle}
59           path={this.context.router.route.match.url}
60         />
61         <div className="row">
62           <div className="col-12 col-lg-6 offset-lg-3">{this.loginForm()}</div>
63         </div>
64       </div>
65     );
66   }
67
68   loginForm() {
69     return (
70       <div>
71         <form onSubmit={linkEvent(this, this.handleLoginSubmit)}>
72           <h1 className="h4 mb-4">{I18NextService.i18n.t("login")}</h1>
73           <div className="mb-3 row">
74             <label
75               className="col-sm-2 col-form-label"
76               htmlFor="login-email-or-username"
77             >
78               {I18NextService.i18n.t("email_or_username")}
79             </label>
80             <div className="col-sm-10">
81               <input
82                 type="text"
83                 className="form-control"
84                 id="login-email-or-username"
85                 value={this.state.form.username_or_email}
86                 onInput={linkEvent(this, this.handleLoginUsernameChange)}
87                 autoComplete="email"
88                 required
89                 minLength={3}
90               />
91             </div>
92           </div>
93           <div className="mb-3 row">
94             <label className="col-sm-2 col-form-label" htmlFor="login-password">
95               {I18NextService.i18n.t("password")}
96             </label>
97             <div className="col-sm-10">
98               <input
99                 type="password"
100                 id="login-password"
101                 value={this.state.form.password}
102                 onInput={linkEvent(this, this.handleLoginPasswordChange)}
103                 className="form-control"
104                 autoComplete="current-password"
105                 required
106                 maxLength={60}
107               />
108               <NavLink
109                 className="btn p-0 btn-link d-inline-block float-right text-muted small font-weight-bold pointer-events not-allowed"
110                 to="/login_reset"
111               >
112                 {I18NextService.i18n.t("forgot_password")}
113               </NavLink>
114             </div>
115           </div>
116           {this.state.showTotp && (
117             <div className="mb-3 row">
118               <label
119                 className="col-sm-6 col-form-label"
120                 htmlFor="login-totp-token"
121               >
122                 {I18NextService.i18n.t("two_factor_token")}
123               </label>
124               <div className="col-sm-6">
125                 <input
126                   type="number"
127                   inputMode="numeric"
128                   className="form-control"
129                   id="login-totp-token"
130                   pattern="[0-9]*"
131                   autoComplete="one-time-code"
132                   value={this.state.form.totp_2fa_token}
133                   onInput={linkEvent(this, this.handleLoginTotpChange)}
134                 />
135               </div>
136             </div>
137           )}
138           <div className="mb-3 row">
139             <div className="col-sm-10">
140               <button type="submit" className="btn btn-secondary">
141                 {this.state.loginRes.state == "loading" ? (
142                   <Spinner />
143                 ) : (
144                   I18NextService.i18n.t("login")
145                 )}
146               </button>
147             </div>
148           </div>
149         </form>
150       </div>
151     );
152   }
153
154   async handleLoginSubmit(i: Login, event: any) {
155     event.preventDefault();
156     const { password, totp_2fa_token, username_or_email } = i.state.form;
157
158     if (username_or_email && password) {
159       i.setState({ loginRes: { state: "loading" } });
160
161       const loginRes = await HttpService.client.login({
162         username_or_email,
163         password,
164         totp_2fa_token,
165       });
166       switch (loginRes.state) {
167         case "failed": {
168           if (loginRes.msg === "missing_totp_token") {
169             i.setState({ showTotp: true });
170             toast(I18NextService.i18n.t("enter_two_factor_code"), "info");
171           }
172           if (loginRes.msg === "incorrect_login") {
173             toast(I18NextService.i18n.t("incorrect_login"), "danger");
174           }
175
176           i.setState({ loginRes: { state: "failed", msg: loginRes.msg } });
177           break;
178         }
179
180         case "success": {
181           UserService.Instance.login({
182             res: loginRes.data,
183           });
184           const site = await HttpService.client.getSite({
185             auth: myAuth(),
186           });
187
188           if (site.state === "success") {
189             UserService.Instance.myUserInfo = site.data.my_user;
190           }
191
192           i.props.history.action === "PUSH"
193             ? i.props.history.back()
194             : i.props.history.replace("/");
195
196           break;
197         }
198       }
199     }
200   }
201
202   handleLoginUsernameChange(i: Login, event: any) {
203     i.state.form.username_or_email = event.target.value.trim();
204     i.setState(i.state);
205   }
206
207   handleLoginTotpChange(i: Login, event: any) {
208     i.state.form.totp_2fa_token = event.target.value;
209     i.setState(i.state);
210   }
211
212   handleLoginPasswordChange(i: Login, event: any) {
213     i.state.form.password = event.target.value;
214     i.setState(i.state);
215   }
216 }