]> Untitled Git - lemmy.git/blob - ui/src/components/login.tsx
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / ui / src / components / login.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Helmet } from 'inferno-helmet';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import {
6   LoginForm,
7   RegisterForm,
8   LoginResponse,
9   UserOperation,
10   PasswordResetForm,
11   GetSiteResponse,
12   GetCaptchaResponse,
13   WebSocketJsonResponse,
14   Site,
15 } from 'lemmy-js-client';
16 import { WebSocketService, UserService } from '../services';
17 import { wsJsonToRes, validEmail, toast } from '../utils';
18 import { i18n } from '../i18next';
19
20 interface State {
21   loginForm: LoginForm;
22   registerForm: RegisterForm;
23   loginLoading: boolean;
24   registerLoading: boolean;
25   captcha: GetCaptchaResponse;
26   captchaPlaying: boolean;
27   site: Site;
28 }
29
30 export class Login extends Component<any, State> {
31   private subscription: Subscription;
32
33   emptyState: State = {
34     loginForm: {
35       username_or_email: undefined,
36       password: undefined,
37     },
38     registerForm: {
39       username: undefined,
40       password: undefined,
41       password_verify: undefined,
42       admin: false,
43       show_nsfw: false,
44       captcha_uuid: undefined,
45       captcha_answer: undefined,
46     },
47     loginLoading: false,
48     registerLoading: false,
49     captcha: undefined,
50     captchaPlaying: false,
51     site: {
52       id: undefined,
53       name: undefined,
54       creator_id: undefined,
55       published: undefined,
56       creator_name: undefined,
57       number_of_users: undefined,
58       number_of_posts: undefined,
59       number_of_comments: undefined,
60       number_of_communities: undefined,
61       enable_downvotes: undefined,
62       open_registration: undefined,
63       enable_nsfw: undefined,
64     },
65   };
66
67   constructor(props: any, context: any) {
68     super(props, context);
69
70     this.state = this.emptyState;
71
72     this.subscription = WebSocketService.Instance.subject
73       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
74       .subscribe(
75         msg => this.parseMessage(msg),
76         err => console.error(err),
77         () => console.log('complete')
78       );
79
80     WebSocketService.Instance.getSite();
81     WebSocketService.Instance.getCaptcha();
82   }
83
84   componentWillUnmount() {
85     this.subscription.unsubscribe();
86   }
87
88   get documentTitle(): string {
89     if (this.state.site.name) {
90       return `${i18n.t('login')} - ${this.state.site.name}`;
91     } else {
92       return 'Lemmy';
93     }
94   }
95
96   render() {
97     return (
98       <div class="container">
99         <Helmet title={this.documentTitle} />
100         <div class="row">
101           <div class="col-12 col-lg-6 mb-4">{this.loginForm()}</div>
102           <div class="col-12 col-lg-6">{this.registerForm()}</div>
103         </div>
104       </div>
105     );
106   }
107
108   loginForm() {
109     return (
110       <div>
111         <form onSubmit={linkEvent(this, this.handleLoginSubmit)}>
112           <h5>{i18n.t('login')}</h5>
113           <div class="form-group row">
114             <label
115               class="col-sm-2 col-form-label"
116               htmlFor="login-email-or-username"
117             >
118               {i18n.t('email_or_username')}
119             </label>
120             <div class="col-sm-10">
121               <input
122                 type="text"
123                 class="form-control"
124                 id="login-email-or-username"
125                 value={this.state.loginForm.username_or_email}
126                 onInput={linkEvent(this, this.handleLoginUsernameChange)}
127                 required
128                 minLength={3}
129               />
130             </div>
131           </div>
132           <div class="form-group row">
133             <label class="col-sm-2 col-form-label" htmlFor="login-password">
134               {i18n.t('password')}
135             </label>
136             <div class="col-sm-10">
137               <input
138                 type="password"
139                 id="login-password"
140                 value={this.state.loginForm.password}
141                 onInput={linkEvent(this, this.handleLoginPasswordChange)}
142                 class="form-control"
143                 required
144               />
145               {validEmail(this.state.loginForm.username_or_email) && (
146                 <button
147                   type="button"
148                   onClick={linkEvent(this, this.handlePasswordReset)}
149                   className="btn p-0 btn-link d-inline-block float-right text-muted small font-weight-bold"
150                 >
151                   {i18n.t('forgot_password')}
152                 </button>
153               )}
154             </div>
155           </div>
156           <div class="form-group row">
157             <div class="col-sm-10">
158               <button type="submit" class="btn btn-secondary">
159                 {this.state.loginLoading ? (
160                   <svg class="icon icon-spinner spin">
161                     <use xlinkHref="#icon-spinner"></use>
162                   </svg>
163                 ) : (
164                   i18n.t('login')
165                 )}
166               </button>
167             </div>
168           </div>
169         </form>
170       </div>
171     );
172   }
173
174   registerForm() {
175     return (
176       <form onSubmit={linkEvent(this, this.handleRegisterSubmit)}>
177         <h5>{i18n.t('sign_up')}</h5>
178
179         <div class="form-group row">
180           <label class="col-sm-2 col-form-label" htmlFor="register-username">
181             {i18n.t('username')}
182           </label>
183
184           <div class="col-sm-10">
185             <input
186               type="text"
187               id="register-username"
188               class="form-control"
189               value={this.state.registerForm.username}
190               onInput={linkEvent(this, this.handleRegisterUsernameChange)}
191               required
192               minLength={3}
193               maxLength={20}
194               pattern="[a-zA-Z0-9_]+"
195             />
196           </div>
197         </div>
198
199         <div class="form-group row">
200           <label class="col-sm-2 col-form-label" htmlFor="register-email">
201             {i18n.t('email')}
202           </label>
203           <div class="col-sm-10">
204             <input
205               type="email"
206               id="register-email"
207               class="form-control"
208               placeholder={i18n.t('optional')}
209               value={this.state.registerForm.email}
210               onInput={linkEvent(this, this.handleRegisterEmailChange)}
211               minLength={3}
212             />
213             {!validEmail(this.state.registerForm.email) && (
214               <div class="mt-2 mb-0 alert alert-light" role="alert">
215                 <svg class="icon icon-inline mr-2">
216                   <use xlinkHref="#icon-alert-triangle"></use>
217                 </svg>
218                 {i18n.t('no_password_reset')}
219               </div>
220             )}
221           </div>
222         </div>
223
224         <div class="form-group row">
225           <label class="col-sm-2 col-form-label" htmlFor="register-password">
226             {i18n.t('password')}
227           </label>
228           <div class="col-sm-10">
229             <input
230               type="password"
231               id="register-password"
232               value={this.state.registerForm.password}
233               autoComplete="new-password"
234               onInput={linkEvent(this, this.handleRegisterPasswordChange)}
235               class="form-control"
236               required
237             />
238           </div>
239         </div>
240
241         <div class="form-group row">
242           <label
243             class="col-sm-2 col-form-label"
244             htmlFor="register-verify-password"
245           >
246             {i18n.t('verify_password')}
247           </label>
248           <div class="col-sm-10">
249             <input
250               type="password"
251               id="register-verify-password"
252               value={this.state.registerForm.password_verify}
253               autoComplete="new-password"
254               onInput={linkEvent(this, this.handleRegisterPasswordVerifyChange)}
255               class="form-control"
256               required
257             />
258           </div>
259         </div>
260
261         {this.state.captcha && (
262           <div class="form-group row">
263             <label class="col-sm-2" htmlFor="register-captcha">
264               <span class="mr-2">{i18n.t('enter_code')}</span>
265               <button
266                 type="button"
267                 class="btn btn-secondary"
268                 onClick={linkEvent(this, this.handleRegenCaptcha)}
269               >
270                 <svg class="icon icon-refresh-cw">
271                   <use xlinkHref="#icon-refresh-cw"></use>
272                 </svg>
273               </button>
274             </label>
275             {this.showCaptcha()}
276             <div class="col-sm-6">
277               <input
278                 type="text"
279                 class="form-control"
280                 id="register-captcha"
281                 value={this.state.registerForm.captcha_answer}
282                 onInput={linkEvent(
283                   this,
284                   this.handleRegisterCaptchaAnswerChange
285                 )}
286                 required
287               />
288             </div>
289           </div>
290         )}
291         {this.state.site.enable_nsfw && (
292           <div class="form-group row">
293             <div class="col-sm-10">
294               <div class="form-check">
295                 <input
296                   class="form-check-input"
297                   id="register-show-nsfw"
298                   type="checkbox"
299                   checked={this.state.registerForm.show_nsfw}
300                   onChange={linkEvent(this, this.handleRegisterShowNsfwChange)}
301                 />
302                 <label class="form-check-label" htmlFor="register-show-nsfw">
303                   {i18n.t('show_nsfw')}
304                 </label>
305               </div>
306             </div>
307           </div>
308         )}
309         <div class="form-group row">
310           <div class="col-sm-10">
311             <button type="submit" class="btn btn-secondary">
312               {this.state.registerLoading ? (
313                 <svg class="icon icon-spinner spin">
314                   <use xlinkHref="#icon-spinner"></use>
315                 </svg>
316               ) : (
317                 i18n.t('sign_up')
318               )}
319             </button>
320           </div>
321         </div>
322       </form>
323     );
324   }
325
326   showCaptcha() {
327     return (
328       <div class="col-sm-4">
329         {this.state.captcha.ok && (
330           <>
331             <img
332               class="rounded-top img-fluid"
333               src={this.captchaPngSrc()}
334               style="border-bottom-right-radius: 0; border-bottom-left-radius: 0;"
335             />
336             {this.state.captcha.ok.wav && (
337               <button
338                 class="rounded-bottom btn btn-sm btn-secondary btn-block"
339                 style="border-top-right-radius: 0; border-top-left-radius: 0;"
340                 title={i18n.t('play_captcha_audio')}
341                 onClick={linkEvent(this, this.handleCaptchaPlay)}
342                 type="button"
343                 disabled={this.state.captchaPlaying}
344               >
345                 <svg class="icon icon-play">
346                   <use xlinkHref="#icon-play"></use>
347                 </svg>
348               </button>
349             )}
350           </>
351         )}
352       </div>
353     );
354   }
355
356   handleLoginSubmit(i: Login, event: any) {
357     event.preventDefault();
358     i.state.loginLoading = true;
359     i.setState(i.state);
360     WebSocketService.Instance.login(i.state.loginForm);
361   }
362
363   handleLoginUsernameChange(i: Login, event: any) {
364     i.state.loginForm.username_or_email = event.target.value;
365     i.setState(i.state);
366   }
367
368   handleLoginPasswordChange(i: Login, event: any) {
369     i.state.loginForm.password = event.target.value;
370     i.setState(i.state);
371   }
372
373   handleRegisterSubmit(i: Login, event: any) {
374     event.preventDefault();
375     i.state.registerLoading = true;
376     i.setState(i.state);
377     WebSocketService.Instance.register(i.state.registerForm);
378   }
379
380   handleRegisterUsernameChange(i: Login, event: any) {
381     i.state.registerForm.username = event.target.value;
382     i.setState(i.state);
383   }
384
385   handleRegisterEmailChange(i: Login, event: any) {
386     i.state.registerForm.email = event.target.value;
387     if (i.state.registerForm.email == '') {
388       i.state.registerForm.email = undefined;
389     }
390     i.setState(i.state);
391   }
392
393   handleRegisterPasswordChange(i: Login, event: any) {
394     i.state.registerForm.password = event.target.value;
395     i.setState(i.state);
396   }
397
398   handleRegisterPasswordVerifyChange(i: Login, event: any) {
399     i.state.registerForm.password_verify = event.target.value;
400     i.setState(i.state);
401   }
402
403   handleRegisterShowNsfwChange(i: Login, event: any) {
404     i.state.registerForm.show_nsfw = event.target.checked;
405     i.setState(i.state);
406   }
407
408   handleRegisterCaptchaAnswerChange(i: Login, event: any) {
409     i.state.registerForm.captcha_answer = event.target.value;
410     i.setState(i.state);
411   }
412
413   handleRegenCaptcha(_i: Login, _event: any) {
414     event.preventDefault();
415     WebSocketService.Instance.getCaptcha();
416   }
417
418   handlePasswordReset(i: Login) {
419     event.preventDefault();
420     let resetForm: PasswordResetForm = {
421       email: i.state.loginForm.username_or_email,
422     };
423     WebSocketService.Instance.passwordReset(resetForm);
424   }
425
426   handleCaptchaPlay(i: Login) {
427     event.preventDefault();
428     let snd = new Audio('data:audio/wav;base64,' + i.state.captcha.ok.wav);
429     snd.play();
430     i.state.captchaPlaying = true;
431     i.setState(i.state);
432     snd.addEventListener('ended', () => {
433       snd.currentTime = 0;
434       i.state.captchaPlaying = false;
435       i.setState(this.state);
436     });
437   }
438
439   captchaPngSrc() {
440     return `data:image/png;base64,${this.state.captcha.ok.png}`;
441   }
442
443   parseMessage(msg: WebSocketJsonResponse) {
444     let res = wsJsonToRes(msg);
445     if (msg.error) {
446       toast(i18n.t(msg.error), 'danger');
447       this.state = this.emptyState;
448       this.state.registerForm.captcha_answer = undefined;
449       // Refetch another captcha
450       WebSocketService.Instance.getCaptcha();
451       this.setState(this.state);
452       return;
453     } else {
454       if (res.op == UserOperation.Login) {
455         let data = res.data as LoginResponse;
456         this.state = this.emptyState;
457         this.setState(this.state);
458         UserService.Instance.login(data);
459         WebSocketService.Instance.userJoin();
460         toast(i18n.t('logged_in'));
461         this.props.history.push('/');
462       } else if (res.op == UserOperation.Register) {
463         let data = res.data as LoginResponse;
464         this.state = this.emptyState;
465         this.setState(this.state);
466         UserService.Instance.login(data);
467         WebSocketService.Instance.userJoin();
468         this.props.history.push('/communities');
469       } else if (res.op == UserOperation.GetCaptcha) {
470         let data = res.data as GetCaptchaResponse;
471         if (data.ok) {
472           this.state.captcha = data;
473           this.state.registerForm.captcha_uuid = data.ok.uuid;
474           this.setState(this.state);
475         }
476       } else if (res.op == UserOperation.PasswordReset) {
477         toast(i18n.t('reset_password_mail_sent'));
478       } else if (res.op == UserOperation.GetSite) {
479         let data = res.data as GetSiteResponse;
480         this.state.site = data.site;
481         this.setState(this.state);
482       }
483     }
484   }
485 }