Skip to content

Commit

Permalink
Fix discord linking
Browse files Browse the repository at this point in the history
  • Loading branch information
thesprockee committed Dec 4, 2023
1 parent a89189d commit 106b0fd
Showing 1 changed file with 71 additions and 37 deletions.
108 changes: 71 additions & 37 deletions app/routes/oauth.success.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,104 +4,139 @@ import type {
MetaFunction,
} from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, Link, useActionData, useSearchParams } from "@remix-run/react";
import { useEffect, useRef } from "react";
import { Form, Link, useActionData, useLoaderData, useSearchParams } from "@remix-run/react";

Check failure on line 7 in app/routes/oauth.success.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

There should be no empty line within import group

Check failure on line 7 in app/routes/oauth.success.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

'Link' is defined but never used

import { useEffect, useRef } from "react";

export const loader = async ({ request }: LoaderFunctionArgs) => {
const DISCORD_OAUTH2_URL = process.env.DISCORD_OAUTH2_URL ?? '';

Check failure on line 12 in app/routes/oauth.success.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

'DISCORD_OAUTH2_URL' is assigned a value but never used

String(request);
return json({});

return json({discordOauth2Url: process.env.DISCORD_OAUTH2_URL ?? ''});
};


//const OAUTH_REDIRECT_URL = process.env.OAUTH_REDIRECT_URL ?? '';


const _sanitizeLinkCode = (linkCode: string) => {
return linkCode.toUpperCase().replace(/[^ABCDEFGHJKLMNPQRSTUVWXYZ]/g, '').slice(0, 4);
return linkCode.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 4);
}

export const action = async ({ request }: ActionFunctionArgs) => {
const SUCCESS_REDIRECT_URL = process.env.SUCCESS_REDIRECT_URL ?? "/";

Check failure on line 24 in app/routes/oauth.success.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

'SUCCESS_REDIRECT_URL' is assigned a value but never used
const DISCORD_OAUTH2_URL = process.env.DISCORD_OAUTH2_URL ?? '';

Check failure on line 25 in app/routes/oauth.success.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

'DISCORD_OAUTH2_URL' is assigned a value but never used
const NAKAMA_API_URL = process.env.NAKAMA_API_URL ?? '';
const NAKAMA_API_BASE_URL = process.env.NAKAMA_API_BASE_URL ?? '';
const NAKAMA_HTTP_KEY = process.env.NAKAMA_HTTP_KEY ?? '';
const OAUTH_REDIRECT_URL = process.env.OAUTH_REDIRECT_URL ?? '';

const formData = await request.formData();
let linkCode = String(formData.get("linkCode"));
const oauthCode = String(formData.get("discordCode"));

linkCode = _sanitizeLinkCode(linkCode);
if (linkCode.length != 4) {
return json(
{ errors: { linkCode: "linkCode is invalid", discordCode: null } },
{ success: false, errors: { linkCode: "linkCode is invalid. Your link code is 4 letters.", discordCode: null } },
{ status: 400 },
);
} else if (oauthCode == null) {
}
if (!oauthCode) {
return json(
{ errors: { linkCode: null, discordCode: "discord code is invalid. retry oauth." } },
{ success: false, errors: { linkCode: null, discordCode: "discord code is invalid. retry oauth by clicking 'Link Discord' below." } },
{ status: 400 },
);
}

const response = await fetch(NAKAMA_API_URL, {
console.log("url:", NAKAMA_API_BASE_URL + '/v2/rpc/discordLinkDevice?http_key=' + NAKAMA_HTTP_KEY)
console.log("Sending: %s", JSON.stringify(JSON.stringify({
linkCode,
oauthCode,
oauthRedirectUrl: OAUTH_REDIRECT_URL,
})));
const response = await fetch(
NAKAMA_API_BASE_URL + '/v2/rpc/discordLinkDevice?http_key=' + NAKAMA_HTTP_KEY, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
body: JSON.stringify(JSON.stringify({
linkCode,
oauthCode: oauthCode,
oauthCode,
oauthRedirectUrl: OAUTH_REDIRECT_URL,
}),
})),
});
console.log("Nakama response: %s %s", response.status, response.statusText, response);

if (response.status === 200) {
return redirect(SUCCESS_REDIRECT_URL);
return json(
{ success: true, errors: { linkCode: null, discordCode: null, } },
{ status: 200 },
);
//return redirect(SUCCESS_REDIRECT_URL);
} else if (response.status === 401) {
console.error(`Redirecting to oauth url, because of error from nakama: ${response.statusText}`)
//return redirect(DISCORD_OAUTH2_URL);
console.error("Error: 404 ", )
return json(
{ success: false, errors: { linkCode: "Could not find link code or discord code expired. Try clicking 'Link Discord' below.", discordCode: null, } },
{ status: 400 },
);
} else if ( response.status === 404) {
console.log("Error 404");
return json(
{ errors: { linkCode: null, discordCode: "discord code is invalid. retry oauth." } },
{ success: false, errors: { linkCode: "linkCode is used/expired/not found.", discordCode: null } },
{ status: 400 },
);
} else if ( response.status != 200) {
console.log("Error: ", response.status, response.statusText);
return json(
{ success: false, errors: { linkCode: "linkCode is invalid", discordCode: null } },
{ status: 400 },
);
}
return { errors: { linkCode: null, discordCode: null }};

return { success: false, errors: { linkCode: null, discordCode: null }};
};

export const meta: MetaFunction = () => [{ title: "Link Device" }];

export default function LoginPage() {

const [searchParams] = useSearchParams();
const discordCode = searchParams.get("code");

const actionData = useActionData<typeof action>();
const loaderData = useLoaderData<typeof loader>();
const linkCodeRef = useRef<HTMLInputElement>(null);


if (!discordCode) {
return redirect(loaderData.discordOauth2Url);
}
useEffect(() => {

Check failure on line 112 in app/routes/oauth.success.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render

if (actionData?.errors?.linkCode) {
linkCodeRef.current?.focus();
}

linkCodeRef.current?.addEventListener("input", (e) => {

const input = e.target as HTMLInputElement;
// limit it to 4 characters
input.value = _sanitizeLinkCode(input.value);
} )



}, [actionData]);


return (
<div className="flex min-h-full flex-col justify-center">
<div className="mx-auto w-full max-w-md px-8 my-4">
<Form method="post" navigate={false} className="space-y-6">
<div className="mx-auto w-full max-w-md px-8">
<Form method="post" className="space-y-6">
<div>

<input type="hidden" name="discordCode" value={discordCode ?? ''} />
<label
htmlFor="linkCode"
className="block text-center text-4xl font-bold text-gray-700">Link Account</label>
className="block text-sm font-medium text-gray-700">Link Account</label>
<p id="subheader">To link your account, please enter the 4-character code displayed in your headset.</p>
<input type="hidden" name="discordCode" value={discordCode ?? ""} />
<div className="mt-1">
<input
ref={linkCodeRef}
Expand All @@ -114,13 +149,18 @@ export default function LoginPage() {
autoComplete="none"
aria-invalid={actionData?.errors?.linkCode ? true : undefined}
aria-describedby="linkCode-error"
className="w-80 h-40 rounded border border-gray-500 px-2 py-1 text-9xl"
className="w-full rounded border border-gray-500 px-2 py-1 text-lg"
/>
{actionData?.errors?.linkCode ? (
<div className="pt-1 text-red-700" id="linkCode-error">
{actionData.errors.linkCode}
</div>
) : null}
{actionData?.success == true ? (
<div className="pt-1 text-green-700" id="linkCode-success">
ACCOUNT SUCCESSFULLY LINKED! You can now close this window and restart your EchoVR game!
</div>
) : null}
</div>
</div>
<div>
Expand All @@ -137,15 +177,9 @@ export default function LoginPage() {

<div className="text-center text-sm text-gray-500">
Don&apos;t have an account?{" "}
<Link
className="text-blue-500 underline"
to={{
pathname: "/join",
search: searchParams.toString(),
}}
>
Link Account
</Link>
<a href={loaderData.discordOauth2Url} className="font-medium text-blue-600 hover:text-blue-500">
Link Discord
</a>
</div>
</div>
</div>
Expand Down

0 comments on commit 106b0fd

Please sign in to comment.