Skip to content

Commit 4030e26

Browse files
committed
feat: Integrate CrazyGames SDK and enhance user authentication flow
- Added a caching mechanism for the CrazyGames public key to optimize API calls and reduce latency. - Updated the Home component to call the loadingStop method immediately upon receiving a response from the CrazyGames authentication API, improving user experience. - Modified the HeadContent component to preload the CrazyGames SDK when on the CrazyGames platform, ensuring faster script loading. - Enhanced the formatNumber utility to remove trailing zeroes more effectively, improving number display consistency.
1 parent 3b0b247 commit 4030e26

File tree

4 files changed

+42
-14
lines changed

4 files changed

+42
-14
lines changed

api/crazyAuth.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@ import { getLeague } from '../components/utils/leagues.js';
99

1010
const USERNAME_CHANGE_COOLDOWN = 30 * 24 * 60 * 60 * 1000; // 30 days
1111

12+
// In-memory cache for CrazyGames public key (1 hour TTL)
13+
let cachedPublicKey = null;
14+
let publicKeyCacheTime = 0;
15+
const PUBLIC_KEY_CACHE_TTL = 60 * 60 * 1000; // 1 hour
16+
17+
async function getCrazyGamesPublicKey() {
18+
const now = Date.now();
19+
if (cachedPublicKey && (now - publicKeyCacheTime) < PUBLIC_KEY_CACHE_TTL) {
20+
return cachedPublicKey;
21+
}
22+
const resp = await axios.get("https://sdk.crazygames.com/publicKey.json");
23+
cachedPublicKey = resp.data["publicKey"];
24+
publicKeyCacheTime = now;
25+
return cachedPublicKey;
26+
}
27+
1228
/**
1329
* Get extended user data (publicAccount + eloRank data) for combined response
1430
*/
@@ -70,8 +86,7 @@ export default async function handler(req, res) {
7086

7187
let decodedToken;
7288
try {
73-
const resp = await axios.get("https://sdk.crazygames.com/publicKey.json");
74-
const publicKey = resp.data["publicKey"];
89+
const publicKey = await getCrazyGamesPublicKey();
7590
decodedToken = verify(token, publicKey, { algorithms: ["RS256"] });
7691
} catch (error) {
7792
return res.status(400).json({ error: 'Invalid token' });

components/headContent.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import Head from "next/head";
22
import Script from "next/script";
33
import { useEffect } from "react";
44

5-
export default function HeadContent({text,inCoolMathGames}) {
5+
export default function HeadContent({ text, inCoolMathGames, inCrazyGames = false }) {
6+
67
useEffect(() => {
78
if (!window.location.search.includes("crazygames") && !process.env.NEXT_PUBLIC_POKI &&
89
!process.env.NEXT_PUBLIC_COOLMATH) {
@@ -121,6 +122,10 @@ ads.js"></script>*/
121122

122123
{/* <link rel="preconnect" href="https://fonts.googleapis.com"/>
123124
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/> */}
125+
{/* Preload CrazyGames SDK when on CrazyGames platform */}
126+
{inCrazyGames && (
127+
<link rel="preload" href="https://sdk.crazygames.com/crazygames-sdk-v3.js" as="script" />
128+
)}
124129
<link href="https://fonts.googleapis.com/css2?family=Jockey+One&display=swap" rel="stylesheet"/>
125130
<link href="https://fonts.googleapis.com/css2?family=Lexend:wght@100..900&display=swap" rel="stylesheet"/>
126131

components/home.js

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ import FriendsModal from "@/components/friendModal";
3434
import { toast, ToastContainer } from "react-toastify";
3535
import InfoModal from "@/components/infoModal";
3636
import { inIframe, isForbiddenIframe } from "@/components/utils/inIframe";
37-
import moment from 'moment-timezone';
3837
import MapsModal from "@/components/maps/mapsModal";
3938
import { useRouter } from "next/router";
4039
import { fromLonLat } from "ol/proj";
@@ -356,17 +355,27 @@ export default function Home({ }) {
356355
const token = await window.CrazyGames.SDK.user.getUserToken();
357356
if (token && user.username) {
358357
// /api/crazyAuth
358+
let loadingStopCalled = false;
359+
const callLoadingStop = () => {
360+
if (loadingStopCalled) return;
361+
loadingStopCalled = true;
362+
try {
363+
window.CrazyGames.SDK.game.loadingStop();
364+
} catch (e) { }
365+
};
366+
359367
fetch(clientConfigData.apiUrl + "/api/crazyAuth", {
360368
method: "POST",
361369
headers: {
362370
'Content-Type': 'application/json'
363371
},
364372
body: JSON.stringify({ token, username: user.username })
365-
}).then((res) => res.json()).then((data) => {
373+
}).then((res) => {
374+
// Call loadingStop immediately when response is received (before JSON parsing)
375+
callLoadingStop();
376+
return res.json();
377+
}).then((data) => {
366378
console.log("crazygames auth", token, user, data)
367-
try {
368-
window.CrazyGames.SDK.game.loadingStop();
369-
} catch (e) { }
370379
if (data.secret && data.username) {
371380
// Store full auth data including extended fields (elo, rank, etc.)
372381
setSession({ token: data })
@@ -386,9 +395,8 @@ export default function Home({ }) {
386395
toast.error("CrazyGames auth failed")
387396
}
388397
}).catch((e) => {
389-
try {
390-
window.CrazyGames.SDK.game.loadingStop();
391-
} catch (e) { }
398+
// Call loadingStop in case of network error (where first .then() never ran)
399+
callLoadingStop();
392400
console.error("crazygames auth failed", e)
393401
});
394402

@@ -1190,7 +1198,7 @@ export default function Home({ }) {
11901198
console.log("connected to ws", window.verifyPayload)
11911199
if (!inCrazyGames && !window.location.search.includes("crazygames")) {
11921200

1193-
const tz = moment.tz.guess();
1201+
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
11941202
let secret = "not_logged_in";
11951203
try {
11961204
const s = window.localStorage.getItem("wg_secret");

components/utils/fmtNumber.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ export default function formatNumber(number, identifyingDigits) {
1616

1717
let formattedNumber = scaledNumber.toFixed(precision);
1818

19-
// Remove trailing zeroes
20-
formattedNumber = formattedNumber.replace(/\.?0+$/, '');
19+
// Remove trailing zeroes after decimal point (e.g., "1.50" → "1.5", "2.00" → "2")
20+
formattedNumber = formattedNumber.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
2121

2222
return `${formattedNumber}${suffix}`;
2323
}

0 commit comments

Comments
 (0)