Skip to content

Commit

Permalink
Migrated API routes to express
Browse files Browse the repository at this point in the history
  • Loading branch information
codergautam committed Oct 12, 2024
1 parent 1d26998 commit 9383f88
Show file tree
Hide file tree
Showing 47 changed files with 1,110 additions and 5,382 deletions.
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ jobs:
runs-on: ubuntu-latest
env:
CI: false
NEXT_PUBLIC_SERVER: staging.worldguessr.com
# add more env vars here

steps:
Expand Down
53 changes: 53 additions & 0 deletions OldAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

// import NextAuth from "next-auth";
// import GoogleProvider from "next-auth/providers/google";
// import mongoose from "mongoose";
// import User from "../../../models/User";
// import { createUUID } from "@/components/createUUID";

// mongoose.connect(process.env.MONGODB);

// export default NextAuth.default({
// providers: [
// GoogleProvider.default({
// clientId: process.env.GOOGLE_CLIENT_ID,
// clientSecret: process.env.GOOGLE_CLIENT_SECRET,
// authorization: {
// params: {},
// },
// checks: ['none'],
// }),
// ],
// callbacks: {
// async signIn({ user }) {
// const { email } = user;
// const existingUser = await User.findOne({ email });
// let secret = null;
// if (!existingUser) {
// console.log("User does not exist, creating a new user", email);
// secret = createUUID();
// const newUser = new User({ email, secret });
// await newUser.save();
// }

// return true;
// },
// jwt: async (token, user) => {
// const email = token?.token?.email;
// let output ={};
// if(email) {
// const userDb = await User.findOne({
// email,
// }).select("secret username email staff canMakeClues supporter");
// if (userDb) {
// output = { secret: userDb.secret, username: userDb.username, email: userDb.email, staff: userDb.staff, canMakeClues: userDb.canMakeClues, supporter: userDb.supporter };
// }
// }
// return output;
// },
// async session(session, token) {
// return session;
// },
// },
// });

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
6 changes: 4 additions & 2 deletions pages/api/crazyAuth.js → api/crazyAuth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as jwt from "jsonwebtoken";
import axios from "axios";
import { createUUID } from "@/components/createUUID";
import User from "@/models/User";
// import { createUUID } from "@/components/createUUID";
// import User from "@/models/User";
import { createUUID } from "../components/createUUID.js";
import User from "../models/User.js";
import { Webhook } from "discord-webhook-node";

export default async function handler(req, res) {
Expand Down
16 changes: 16 additions & 0 deletions api/getCountries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// import { promises as fs } from 'fs';
// import path from 'path';
// import geolib, { getDistance } from 'geolib';

import countries from '../public/countries.json' with { type: "json" };
import countryMaxDists from '../public/countryMaxDists.json' with { type: "json" };

async function getCountries(req, res) {
const out = {};
for (const country of countries) {
out[country] = countryMaxDists[country];
}
res.json(out);
}

export default getCountries;
2 changes: 1 addition & 1 deletion pages/api/leaderboard.js → api/leaderboard.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import mongoose from 'mongoose';
import User from '../../models/User';
import User from '../models/User.js';
const cache = { data: null, timestamp: null };
const pastDayCache = { data: null, timestamp: null };

Expand Down
26 changes: 17 additions & 9 deletions pages/api/map/action.js → api/map/action.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import mapConst from "@/components/maps/mapConst";
import parseMapData from "@/components/utils/parseMapData";
import generateSlug from "@/components/utils/slugGenerator";
import Map from "@/models/Map";
import User from "@/models/User";

import countries from '@/public/countries.json';
import officialCountryMaps from '@/public/officialCountryMaps.json';
// import mapConst from "@/components/maps/mapConst";
// import parseMapData from "@/components/utils/parseMapData";
// import generateSlug from "@/components/utils/slugGenerator";
// import Map from "@/models/Map";
// import User from "@/models/User";

// import countries from '@/public/countries.json';
// import officialCountryMaps from '@/public/officialCountryMaps.json';
import mapConst from '../../components/maps/mapConst.js';
import parseMapData from '../../components/utils/parseMapData.js';
import generateSlug from '../../components/utils/slugGenerator.js';
import Map from '../../models/Map.js';
import User from '../../models/User.js';

import countries from '../../public/countries.json' with { type: "json" };
import officialCountryMaps from '../../public/officialCountryMaps.json' with { type: "json" };

// Function to convert latitude and longitude to Cartesian coordinates
function latLngToCartesian(lat, lng) {
Expand Down Expand Up @@ -197,7 +205,7 @@ export default async function handler(req, res) {
}

return res.status(200).json({ map });

}

return res.status(400).json({ message: 'Invalid action' });
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 1 addition & 2 deletions pages/api/map/mapHome.js → api/map/mapHome.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ export default async function handler(req, res) {
let user;

if(secret) {
console.time('findUser');
console.log('secret', secret);
user = await User.findOne({ secret: secret });
console.timeEnd('findUser');
if(typeof secret !== 'string') {
return res.status(400).json({ message: 'Invalid input' });
}
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions pages/api/publicAccount.js → api/publicAccount.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import mongoose from 'mongoose';
import User from '../../models/User';
import User from '../models/User.js';

export default async function handler(req, res) {
// Only allow POST requests
Expand All @@ -22,7 +22,7 @@ export default async function handler(req, res) {
if ((id && typeof id !== 'string') || (secret && typeof secret !== 'string')) {
return res.status(400).json({ message: 'Invalid input' });
}

if (!id && !secret) {
return res.status(400).json({ message: 'Provide at least one of the following: id or secret' });
}
Expand Down
2 changes: 1 addition & 1 deletion pages/api/setName.js → api/setName.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// pages/api/setName.js
import mongoose from 'mongoose';
import User from '../../models/User';
import User from '../models/User.js';
import { Webhook } from "discord-webhook-node";

export default async function handler(req, res) {
Expand Down
11 changes: 7 additions & 4 deletions pages/api/storeGame.js → api/storeGame.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import calcPoints from '@/components/calcPoints';
import storeGame from '@/components/storeGame';
import ratelimiter from '@/components/utils/ratelimitMiddleware'
// import calcPoints from '@/components/calcPoints';
// import storeGame from '@/components/storeGame';
// import ratelimiter from '@/components/utils/ratelimitMiddleware'
import calcPoints from '../components/calcPoints.js';
import storeGame from '../components/storeGame.js';
import ratelimiter from '../components/utils/ratelimitMiddleware.js';

// multiplayer after guess
async function guess(req, res) {
Expand All @@ -15,7 +18,7 @@ async function guess(req, res) {
if(lat === actualLat || long === actualLong || roundTime < 0 || maxDist < 10) {
return res.status(400).json({ message: 'Invalid input' });
}

if(secret) {
try {
const calcXp = Math.round(calcPoints({ guessLat: lat, guessLon: long, lat: actualLat, lon: actualLong, usedHint, maxDist }) / 50);
Expand Down
12 changes: 12 additions & 0 deletions clientConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

export default function config() {
const isHttps = window ? (window.location.protocol === "https:") : true;
const prefixHttp = (isHttps ? "https" : "http")+"://";
const prefixWs = (isHttps ? "wss" : "ws")+"://";


return {
"apiUrl": prefixHttp+(process.env.NEXT_PUBLIC_API_URL ?? "localhost:3001"),
"websocketUrl": prefixWs+(process.env.NEXT_PUBLIC_WS_HOST ?? process.env.NEXT_PUBLIC_API_URL ?? "localhost:3001")+'/wg',
}
}
2 changes: 1 addition & 1 deletion components/accountModal.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Modal } from "react-responsive-modal";
import { useEffect, useState } from "react";
import AccountView from "./accountView";
import { signOut } from "next-auth/react";
import { signOut } from "@/components/auth/auth";
import { useTranslation } from '@/components/useTranslations';

export default function AccountModal({ session, shown, setAccountModalOpen, inCrazyGames }) {
Expand Down
35 changes: 35 additions & 0 deletions components/auth/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { inIframe } from "../utils/inIframe";

// secret: userDb.secret, username: userDb.username, email: userDb.email, staff: userDb.staff, canMakeClues: userDb.canMakeClues, supporter: userDb.supporter
const session = null;
// null = not logged in
// false = session loading/fetching

export function signOut() {
console.log("Signing out");
}

export function signIn() {
console.log("Signing in");

if(inIframe()) {
console.log("In iframe");
// open site in new window
const url = window.location.href;
window.open(url, '_blank');
}
}

export function useSession() {
console.log("Using session");

return {
data: session
}
}

export function getServerSession(req, res, authOptions) {
console.log("Getting server session", req, res, authOptions);

return null;
}
7 changes: 5 additions & 2 deletions components/bannerAd.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function Ad({

useEffect(() => {
setType(findAdType(screenW, screenH, types, vertThresh));
}, [screenW, screenH, types, vertThresh]);
}, [screenW, screenH, JSON.stringify(types), vertThresh]);

useEffect(() => {
lastRefresh.current = 0;
Expand All @@ -54,6 +54,9 @@ export default function Ad({
const windowAny = window;

const displayNewAd = () => {
if(isClient === "debug" || !isClient) return;
console.log("Displaying new ad", type, isClient);

if (type === -1) return;
setTimeout(() => {
const isAdDivVisible =
Expand Down Expand Up @@ -137,7 +140,7 @@ export default function Ad({
}, 1000);
displayNewAd();
return () => clearInterval(timerId);
}, [type, inCrazyGames]);
}, [type, inCrazyGames, isClient]);

if (type === -1) return null;
if (!isClient) return null;
Expand Down
1 change: 0 additions & 1 deletion components/discordModal.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Modal } from "react-responsive-modal";
import { useTranslation } from '@/components/useTranslations';
import { signIn } from "next-auth/react";
import gameStorage from "./utils/localStorage";

export default function DiscordModal({ shown, setOpen }) {
Expand Down
Loading

0 comments on commit 9383f88

Please sign in to comment.