Browse Source

fix: recaptcha

poeti8 6 years ago
parent
commit
9d7bc460f2
3 changed files with 34 additions and 6 deletions
  1. 29 6
      client/components/Shortener.tsx
  2. 3 0
      client/module.d.ts
  3. 2 0
      client/store/links.ts

+ 29 - 6
client/components/Shortener.tsx

@@ -73,13 +73,9 @@ const Shortener = () => {
     }
   });
 
-  const onSubmit = async e => {
-    e.preventDefault();
-    if (loading) return;
-    setCopied(false);
-    setLoading(true);
+  const submitLink = async (reCaptchaToken?: string) => {
     try {
-      const link = await submit(formState.values);
+      const link = await submit({ ...formState.values, reCaptchaToken });
       setLink(link);
       formState.clear();
     } catch (err) {
@@ -90,6 +86,33 @@ const Shortener = () => {
     setLoading(false);
   };
 
+  const onSubmit = async e => {
+    e.preventDefault();
+    if (loading) return;
+    setCopied(false);
+    setLoading(true);
+
+    if (process.env.NODE_ENV === "production" && !isAuthenticated) {
+      window.grecaptcha.execute(window.captchaId);
+      const getCaptchaToken = () => {
+        setTimeout(() => {
+          if (window.isCaptchaReady) {
+            const reCaptchaToken = window.grecaptcha.getResponse(
+              window.captchaId
+            );
+            window.isCaptchaReady = false;
+            window.grecaptcha.reset(window.captchaId);
+            return submitLink(reCaptchaToken);
+          }
+          return getCaptchaToken();
+        }, 200);
+      };
+      return getCaptchaToken();
+    }
+
+    return submitLink();
+  };
+
   const title = !link && (
     <H1 light>
       Kutt your links{" "}

+ 3 - 0
client/module.d.ts

@@ -6,6 +6,9 @@ declare module "*.svg";
 declare global {
   interface Window {
     GA_INITIALIZED: boolean;
+    grecaptcha: any;
+    isCaptchaReady: boolean;
+    captchaId: boolean;
   }
 }
 

+ 2 - 0
client/store/links.ts

@@ -4,6 +4,7 @@ import query from "query-string";
 
 import { getAxiosConfig } from "../utils";
 import { API } from "../consts";
+import { string } from "prop-types";
 
 export interface Link {
   id: number;
@@ -26,6 +27,7 @@ export interface NewLink {
   customurl?: string;
   password?: string;
   reuse?: boolean;
+  reCaptchaToken?: string;
 }
 
 export interface LinksQuery {