From 603036b28272c394c71ecc0b7a7a3199983f0f76 Mon Sep 17 00:00:00 2001
From: Joe Banks <joseph@josephbanks.me>
Date: Tue, 6 Oct 2020 14:38:24 +0100
Subject: On OAuth2 button click pop open Discord authorize window

---
 src/components/OAuth2Button.tsx | 42 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 40 insertions(+), 2 deletions(-)

(limited to 'src/components/OAuth2Button.tsx')

diff --git a/src/components/OAuth2Button.tsx b/src/components/OAuth2Button.tsx
index 9cd009a..1b3d588 100644
--- a/src/components/OAuth2Button.tsx
+++ b/src/components/OAuth2Button.tsx
@@ -5,6 +5,9 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { faDiscord } from "@fortawesome/free-brands-svg-icons";
 
 import colors from "../colors";
+import { useState } from "react";
+
+const OAUTH2_CLIENT_ID = process.env.REACT_APP_OAUTH2_CLIENT_ID;
 
 const buttonStyling = css`
 display: flex;
@@ -26,14 +29,49 @@ span {
   vertical-align: middle;
 }
 
-&:hover {
+&:hover:enabled {
   filter: brightness(110%);
   cursor: pointer;
 }
+
+&:disabled {
+  background-color: ${colors.greyple};
+}
 `;
 
+function doLogin(disableFunction: (newState: boolean) => void) {
+  disableFunction(true);
+
+  const redirectURI = encodeURIComponent(document.location.protocol + "//" + document.location.host + "/callback");
+
+  const windowRef = window.open(
+    `https://discord.com/api/oauth2/authorize?client_id=${OAUTH2_CLIENT_ID}&response_type=code&scope=identify&redirect_uri=${redirectURI}&prompt=none`,
+    "Discord_OAuth2",
+    "height=700,width=500,location=no,menubar=no,resizable=no,status=no,titlebar=no,left=300,top=300"
+  )
+
+  window.onmessage = (code: MessageEvent) => {
+    if (code.data.hello) {
+      // React DevTools has a habit of sending messages, ignore them.
+      return;
+    }
+
+    if (code.isTrusted) {
+      windowRef?.close();
+
+      console.log("Code received:", code.data);
+
+      disableFunction(false);
+
+      window.onmessage = null;
+    }
+  };
+}
+
 function OAuth2Button() {
-  return <button onClick={() => alert("Clicked!")} css={buttonStyling}>
+  const [disabled, setDisabled] = useState<boolean>(false);
+
+  return <button disabled={disabled} onClick={() => doLogin(setDisabled)} css={buttonStyling}>
     <span css={{marginRight: "10px"}}><FontAwesomeIcon icon={faDiscord} css={{fontSize: "2em", marginTop: "3px"}}/></span>
     <span>Sign in with Discord</span>
   </button>;
-- 
cgit v1.2.3

