]> Untitled Git - lemmy-ui.git/blob - src/shared/components/home/signup.tsx
Splitting login and signup pages. Fixes #386 (#431)
[lemmy-ui.git] / src / shared / components / home / signup.tsx
1 import { Component, linkEvent } from "inferno";
2 import { T } from "inferno-i18next-dess";
3 import {
4   GetCaptchaResponse,
5   GetSiteResponse,
6   LoginResponse,
7   Register,
8   SiteView,
9   UserOperation,
10 } from "lemmy-js-client";
11 import { Subscription } from "rxjs";
12 import { i18n } from "../../i18next";
13 import { Options, passwordStrength } from "check-password-strength";
14 import { UserService, WebSocketService } from "../../services";
15 import {
16   authField,
17   isBrowser,
18   joinLemmyUrl,
19   setIsoData,
20   toast,
21   validEmail,
22   wsClient,
23   wsJsonToRes,
24   wsSubscribe,
25   wsUserOp,
26 } from "../../utils";
27 import { HtmlTags } from "../common/html-tags";
28 import { Icon, Spinner } from "../common/icon";
29 import {I18nKeys} from "i18next";
30
31 const passwordStrengthOptions: Options<string> = [
32   {
33     id: 0,
34     value: "too_weak",
35     minDiversity: 0,
36     minLength: 0,
37   },
38   {
39     id: 1,
40     value: "weak",
41     minDiversity: 2,
42     minLength: 10,
43   },
44   {
45     id: 2,
46     value: "medium",
47     minDiversity: 3,
48     minLength: 12,
49   },
50   {
51     id: 3,
52     value: "strong",
53     minDiversity: 4,
54     minLength: 14,
55   },
56 ];
57
58 interface State {
59   registerForm: Register;
60   registerLoading: boolean;
61   captcha: GetCaptchaResponse;
62   captchaPlaying: boolean;
63   site_view: SiteView;
64 }
65
66 export class Signup extends Component<any, State> {
67   private isoData = setIsoData(this.context);
68   private subscription: Subscription;
69   private audio: HTMLAudioElement;
70
71   emptyState: State = {
72     registerForm: {
73       username: undefined,
74       password: undefined,
75       password_verify: undefined,
76       show_nsfw: false,
77       captcha_uuid: undefined,
78       captcha_answer: undefined,
79     },
80     registerLoading: false,
81     captcha: undefined,
82     captchaPlaying: false,
83     site_view: this.isoData.site_res.site_view,
84   };
85
86   constructor(props: any, context: any) {
87     super(props, context);
88
89     this.state = this.emptyState;
90
91     this.parseMessage = this.parseMessage.bind(this);
92     this.subscription = wsSubscribe(this.parseMessage);
93
94     if (isBrowser()) {
95       WebSocketService.Instance.send(wsClient.getCaptcha());
96     }
97   }
98
99   componentWillUnmount() {
100     if (isBrowser()) {
101       this.subscription.unsubscribe();
102     }
103   }
104
105   get documentTitle(): string {
106     return `${i18n.t("login")} - ${this.state.site_view.site.name}`;
107   }
108
109   get isLemmyMl(): boolean {
110     return isBrowser() && window.location.hostname == "lemmy.ml";
111   }
112
113   render() {
114     return (
115       <div class="container">
116         <HtmlTags
117           title={this.documentTitle}
118           path={this.context.router.route.match.url}
119         />
120         <div class="row">
121           <div class="col-12 col-lg-6 offset-lg-3">{this.registerForm()}</div>
122         </div>
123       </div>
124     );
125   }
126
127   registerForm() {
128     return (
129       <form onSubmit={linkEvent(this, this.handleRegisterSubmit)}>
130         <h5>{i18n.t("sign_up")}</h5>
131
132         <div class="form-group row">
133           <label class="col-sm-2 col-form-label" htmlFor="register-username">
134             {i18n.t("username")}
135           </label>
136
137           <div class="col-sm-10">
138             <input
139               type="text"
140               id="register-username"
141               class="form-control"
142               value={this.state.registerForm.username}
143               onInput={linkEvent(this, this.handleRegisterUsernameChange)}
144               required
145               minLength={3}
146               pattern="[a-zA-Z0-9_]+"
147               title={i18n.t("community_reqs")}
148             />
149           </div>
150         </div>
151
152         <div class="form-group row">
153           <label class="col-sm-2 col-form-label" htmlFor="register-email">
154             {i18n.t("email")}
155           </label>
156           <div class="col-sm-10">
157             <input
158               type="email"
159               id="register-email"
160               class="form-control"
161               placeholder={i18n.t("optional")}
162               value={this.state.registerForm.email}
163               autoComplete="email"
164               onInput={linkEvent(this, this.handleRegisterEmailChange)}
165               minLength={3}
166             />
167             {!validEmail(this.state.registerForm.email) && (
168               <div class="mt-2 mb-0 alert alert-light" role="alert">
169                 <Icon icon="alert-triangle" classes="icon-inline mr-2" />
170                 {i18n.t("no_password_reset")}
171               </div>
172             )}
173           </div>
174         </div>
175
176         <div class="form-group row">
177           <label class="col-sm-2 col-form-label" htmlFor="register-password">
178             {i18n.t("password")}
179           </label>
180           <div class="col-sm-10">
181             <input
182               type="password"
183               id="register-password"
184               value={this.state.registerForm.password}
185               autoComplete="new-password"
186               onInput={linkEvent(this, this.handleRegisterPasswordChange)}
187               minLength={10}
188               maxLength={60}
189               class="form-control"
190               required
191             />
192             {this.state.registerForm.password && (
193               <div class={this.passwordColorClass}>
194                 {i18n.t(this.passwordStrength as I18nKeys)}
195               </div>
196             )}
197           </div>
198         </div>
199
200         <div class="form-group row">
201           <label
202             class="col-sm-2 col-form-label"
203             htmlFor="register-verify-password"
204           >
205             {i18n.t("verify_password")}
206           </label>
207           <div class="col-sm-10">
208             <input
209               type="password"
210               id="register-verify-password"
211               value={this.state.registerForm.password_verify}
212               autoComplete="new-password"
213               onInput={linkEvent(this, this.handleRegisterPasswordVerifyChange)}
214               maxLength={60}
215               class="form-control"
216               required
217             />
218           </div>
219         </div>
220
221         {this.state.captcha && (
222           <div class="form-group row">
223             <label class="col-sm-2" htmlFor="register-captcha">
224               <span class="mr-2">{i18n.t("enter_code")}</span>
225               <button
226                 type="button"
227                 class="btn btn-secondary"
228                 onClick={linkEvent(this, this.handleRegenCaptcha)}
229                 aria-label={i18n.t("captcha")}
230               >
231                 <Icon icon="refresh-cw" classes="icon-refresh-cw" />
232               </button>
233             </label>
234             {this.showCaptcha()}
235             <div class="col-sm-6">
236               <input
237                 type="text"
238                 class="form-control"
239                 id="register-captcha"
240                 value={this.state.registerForm.captcha_answer}
241                 onInput={linkEvent(
242                   this,
243                   this.handleRegisterCaptchaAnswerChange
244                 )}
245                 required
246               />
247             </div>
248           </div>
249         )}
250         {this.state.site_view.site.enable_nsfw && (
251           <div class="form-group row">
252             <div class="col-sm-10">
253               <div class="form-check">
254                 <input
255                   class="form-check-input"
256                   id="register-show-nsfw"
257                   type="checkbox"
258                   checked={this.state.registerForm.show_nsfw}
259                   onChange={linkEvent(this, this.handleRegisterShowNsfwChange)}
260                 />
261                 <label class="form-check-label" htmlFor="register-show-nsfw">
262                   {i18n.t("show_nsfw")}
263                 </label>
264               </div>
265             </div>
266           </div>
267         )}
268         {this.isLemmyMl && (
269           <div class="mt-2 mb-0 alert alert-light" role="alert">
270             <T i18nKey="lemmy_ml_registration_message">
271               #<a href={joinLemmyUrl}>#</a>
272             </T>
273           </div>
274         )}
275         <div class="form-group row">
276           <div class="col-sm-10">
277             <button type="submit" class="btn btn-secondary">
278               {this.state.registerLoading ? <Spinner /> : i18n.t("sign_up")}
279             </button>
280           </div>
281         </div>
282       </form>
283     );
284   }
285
286   showCaptcha() {
287     return (
288       <div class="col-sm-4">
289         {this.state.captcha.ok && (
290           <>
291             <img
292               class="rounded-top img-fluid"
293               src={this.captchaPngSrc()}
294               style="border-bottom-right-radius: 0; border-bottom-left-radius: 0;"
295               alt={i18n.t("captcha")}
296             />
297             {this.state.captcha.ok.wav && (
298               <button
299                 class="rounded-bottom btn btn-sm btn-secondary btn-block"
300                 style="border-top-right-radius: 0; border-top-left-radius: 0;"
301                 title={i18n.t("play_captcha_audio")}
302                 onClick={linkEvent(this, this.handleCaptchaPlay)}
303                 type="button"
304                 disabled={this.state.captchaPlaying}
305               >
306                 <Icon icon="play" classes="icon-play" />
307               </button>
308             )}
309           </>
310         )}
311       </div>
312     );
313   }
314
315   get passwordStrength() {
316     return passwordStrength(
317       this.state.registerForm.password,
318       passwordStrengthOptions
319     ).value;
320   }
321
322   get passwordColorClass(): string {
323     let strength = this.passwordStrength;
324
325     if (["weak", "medium"].includes(strength)) {
326       return "text-warning";
327     } else if (strength == "strong") {
328       return "text-success";
329     } else {
330       return "text-danger";
331     }
332   }
333
334   handleRegisterSubmit(i: Signup, event: any) {
335     event.preventDefault();
336     i.state.registerLoading = true;
337     i.setState(i.state);
338     WebSocketService.Instance.send(wsClient.register(i.state.registerForm));
339   }
340
341   handleRegisterUsernameChange(i: Signup, event: any) {
342     i.state.registerForm.username = event.target.value;
343     i.setState(i.state);
344   }
345
346   handleRegisterEmailChange(i: Signup, event: any) {
347     i.state.registerForm.email = event.target.value;
348     if (i.state.registerForm.email == "") {
349       i.state.registerForm.email = undefined;
350     }
351     i.setState(i.state);
352   }
353
354   handleRegisterPasswordChange(i: Signup, event: any) {
355     i.state.registerForm.password = event.target.value;
356     i.setState(i.state);
357   }
358
359   handleRegisterPasswordVerifyChange(i: Signup, event: any) {
360     i.state.registerForm.password_verify = event.target.value;
361     i.setState(i.state);
362   }
363
364   handleRegisterShowNsfwChange(i: Signup, event: any) {
365     i.state.registerForm.show_nsfw = event.target.checked;
366     i.setState(i.state);
367   }
368
369   handleRegisterCaptchaAnswerChange(i: Signup, event: any) {
370     i.state.registerForm.captcha_answer = event.target.value;
371     i.setState(i.state);
372   }
373
374   handleRegenCaptcha(i: Signup) {
375     i.audio = null;
376     i.state.captchaPlaying = false;
377     i.setState(i.state);
378     WebSocketService.Instance.send(wsClient.getCaptcha());
379   }
380
381   handleCaptchaPlay(i: Signup) {
382     // This was a bad bug, it should only build the new audio on a new file.
383     // Replays would stop prematurely if this was rebuilt every time.
384     if (i.audio == null) {
385       let base64 = `data:audio/wav;base64,${i.state.captcha.ok.wav}`;
386       i.audio = new Audio(base64);
387     }
388
389     i.audio.play();
390
391     i.state.captchaPlaying = true;
392     i.setState(i.state);
393
394     i.audio.addEventListener("ended", () => {
395       i.audio.currentTime = 0;
396       i.state.captchaPlaying = false;
397       i.setState(i.state);
398     });
399   }
400
401   captchaPngSrc() {
402     return `data:image/png;base64,${this.state.captcha.ok.png}`;
403   }
404
405   parseMessage(msg: any) {
406     let op = wsUserOp(msg);
407     console.log(msg);
408     if (msg.error) {
409       toast(i18n.t(msg.error), "danger");
410       this.state = this.emptyState;
411       this.state.registerForm.captcha_answer = undefined;
412       // Refetch another captcha
413       WebSocketService.Instance.send(wsClient.getCaptcha());
414       this.setState(this.state);
415       return;
416     } else {
417       if (op == UserOperation.Register) {
418         let data = wsJsonToRes<LoginResponse>(msg).data;
419         this.state = this.emptyState;
420         this.setState(this.state);
421         UserService.Instance.login(data);
422         WebSocketService.Instance.send(
423           wsClient.userJoin({
424             auth: authField(),
425           })
426         );
427         this.props.history.push("/communities");
428       } else if (op == UserOperation.GetCaptcha) {
429         let data = wsJsonToRes<GetCaptchaResponse>(msg).data;
430         if (data.ok) {
431           this.state.captcha = data;
432           this.state.registerForm.captcha_uuid = data.ok.uuid;
433           this.setState(this.state);
434         }
435       } else if (op == UserOperation.PasswordReset) {
436         toast(i18n.t("reset_password_mail_sent"));
437       } else if (op == UserOperation.GetSite) {
438         let data = wsJsonToRes<GetSiteResponse>(msg).data;
439         this.state.site_view = data.site_view;
440         this.setState(this.state);
441       }
442     }
443   }
444 }