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