]> Untitled Git - lemmy-ui.git/blob - src/shared/components/home/login.tsx
Merge remote-tracking branch 'lemmy/main' into fix/a11y-fixes-2
[lemmy-ui.git] / src / shared / components / home / login.tsx
1 import { myAuth, setIsoData } from "@utils/app";
2 import { isBrowser } from "@utils/browser";
3 import { validEmail } from "@utils/helpers";
4 import { Component, linkEvent } from "inferno";
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           <h5>{I18NextService.i18n.t("login")}</h5>
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               <button
109                 type="button"
110                 onClick={linkEvent(this, this.handlePasswordReset)}
111                 className="btn p-0 btn-link d-inline-block float-right text-muted small fw-bold pointer-events not-allowed"
112                 disabled={
113                   !!this.state.form.username_or_email &&
114                   !validEmail(this.state.form.username_or_email)
115                 }
116                 title={I18NextService.i18n.t("no_password_reset")}
117               >
118                 {I18NextService.i18n.t("forgot_password")}
119               </button>
120             </div>
121           </div>
122           {this.state.showTotp && (
123             <div className="mb-3 row">
124               <label
125                 className="col-sm-6 col-form-label"
126                 htmlFor="login-totp-token"
127               >
128                 {I18NextService.i18n.t("two_factor_token")}
129               </label>
130               <div className="col-sm-6">
131                 <input
132                   type="number"
133                   inputMode="numeric"
134                   className="form-control"
135                   id="login-totp-token"
136                   pattern="[0-9]*"
137                   autoComplete="one-time-code"
138                   value={this.state.form.totp_2fa_token}
139                   onInput={linkEvent(this, this.handleLoginTotpChange)}
140                 />
141               </div>
142             </div>
143           )}
144           <div className="mb-3 row">
145             <div className="col-sm-10">
146               <button type="submit" className="btn btn-secondary">
147                 {this.state.loginRes.state == "loading" ? (
148                   <Spinner />
149                 ) : (
150                   I18NextService.i18n.t("login")
151                 )}
152               </button>
153             </div>
154           </div>
155         </form>
156       </div>
157     );
158   }
159
160   async handleLoginSubmit(i: Login, event: any) {
161     event.preventDefault();
162     const { password, totp_2fa_token, username_or_email } = i.state.form;
163
164     if (username_or_email && password) {
165       i.setState({ loginRes: { state: "loading" } });
166
167       const loginRes = await HttpService.client.login({
168         username_or_email,
169         password,
170         totp_2fa_token,
171       });
172       switch (loginRes.state) {
173         case "failed": {
174           if (loginRes.msg === "missing_totp_token") {
175             i.setState({ showTotp: true });
176             toast(I18NextService.i18n.t("enter_two_factor_code"), "info");
177           }
178
179           i.setState({ loginRes: { state: "failed", msg: loginRes.msg } });
180           break;
181         }
182
183         case "success": {
184           UserService.Instance.login(loginRes.data);
185           const site = await HttpService.client.getSite({
186             auth: myAuth(),
187           });
188
189           if (site.state === "success") {
190             UserService.Instance.myUserInfo = site.data.my_user;
191           }
192
193           i.props.history.action === "PUSH"
194             ? i.props.history.back()
195             : i.props.history.replace("/");
196
197           break;
198         }
199       }
200     }
201   }
202
203   handleLoginUsernameChange(i: Login, event: any) {
204     i.state.form.username_or_email = event.target.value.trim();
205     i.setState(i.state);
206   }
207
208   handleLoginTotpChange(i: Login, event: any) {
209     i.state.form.totp_2fa_token = event.target.value;
210     i.setState(i.state);
211   }
212
213   handleLoginPasswordChange(i: Login, event: any) {
214     i.state.form.password = event.target.value;
215     i.setState(i.state);
216   }
217
218   async handlePasswordReset(i: Login, event: any) {
219     event.preventDefault();
220     const email = i.state.form.username_or_email;
221     if (email) {
222       const res = await HttpService.client.passwordReset({ email });
223       if (res.state == "success") {
224         toast(I18NextService.i18n.t("reset_password_mail_sent"));
225       }
226     }
227   }
228 }