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