Skip to content

Commit

Permalink
Client side standalone auth
Browse files Browse the repository at this point in the history
  • Loading branch information
codergautam committed Oct 15, 2024
1 parent 3107dbd commit 56f31a2
Show file tree
Hide file tree
Showing 8 changed files with 144 additions and 32 deletions.
72 changes: 55 additions & 17 deletions api/googleAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,72 @@ import User from "../models/User.js";
import { Webhook } from "discord-webhook-node";
import { OAuth2Client } from "google-auth-library";

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
const client = new OAuth2Client(process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET, 'postmessage');

export default async function handler(req, res) {
let output = {};
// only accept post
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method Not Allowed' });
}

const { token } = req.body;
console.log(token);
if (!token) {
return res.status(400).json({ error: 'Invalid input' });
const { code, secret } = req.body;
console.log(code);
if (!code) {
if(!secret) {
return res.status(400).json({ error: 'Invalid' });
}

const userDb = await User.findOne({
secret,
}).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 res.status(200).json(output);
} else {
return res.status(400).json({ error: 'Invalid' });
}

} else {
// first login

// verify the access token
const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;

const { tokens } = await client.getToken(code);
client.setCredentials(tokens);

const ticket = await client.verifyIdToken({
idToken: tokens.id_token,
audience: clientId,
redirectUri: 'worldguessr.com',
});

if(!ticket) {
return res.status(400).json({ error: 'Invalid' });
}

// verify the Google token
let decodedToken;
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: process.env.GOOGLE_CLIENT_ID,
});
const payload = ticket.getPayload();
decodedToken = payload;
} catch (error) {
return res.status(400).json({ error: 'Invalid token' });
const email = ticket.getPayload()?.email;

if (!email) {
return res.status(400).json({ error: 'Invalid' });
}

console.log(decodedToken);
console.log(email);
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();

output = { secret: secret, username: undefined, email: email, staff:false, canMakeClues: false, supporter: false };
} else {
output = { secret: existingUser.secret, username: existingUser.username, email: existingUser.email, staff: existingUser.staff, canMakeClues: existingUser.canMakeClues, supporter: existingUser.supporter };
}

return res.status(200).json(output);
}

}
57 changes: 54 additions & 3 deletions components/auth/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { useGoogleLogin } from "@react-oauth/google";
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;
let session = false;
// null = not logged in
// false = session loading/fetching

export function signOut() {
console.log("Signing out");
window.localStorage.removeItem("wg_secret");
session = null;
window.location.reload();
}

export function signIn() {
Expand All @@ -25,7 +27,56 @@ export function signIn() {
}

export function useSession() {
console.log("Using session");
if(typeof window === "undefined") {
return {
data: false
}
}

if(session === false && !window.fetchingSession) {
let secret = null;
try {

secret = window.localStorage.getItem("wg_secret");

} catch (e) {
console.error(e);
}
if(secret) {

window.fetchingSession = true;

fetch(window.cConfig?.apiUrl+"/api/googleAuth", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ secret }),
})
.then((res) => res.json())
.then((data) => {
window.fetchingSession = false;
if (data.error) {
console.error(data.error);
return;
}

if (data.secret) {
window.localStorage.setItem("wg_secret", data.secret);
session = {token: data};
} else {
session = null;
}
})
.catch((e) => {
window.fetchingSession = false;
console.error(e);
});
} else {
session = null;
}
}


return {
data: session
Expand Down
32 changes: 26 additions & 6 deletions components/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const initialMultiplayerState = {
export default function Home({ }) {
const { width, height } = useWindowDimensions();

const [session, setSession] = useState(null);
const [session, setSession] = useState(false);
const { data: mainSession } = useSession();
const [accountModalOpen, setAccountModalOpen] = useState(false);
const [screen, setScreen] = useState("home");
Expand All @@ -106,13 +106,25 @@ export default function Home({ }) {

const login = useGoogleLogin({
onSuccess: tokenResponse => {
console.log("login success", tokenResponse);
fetch(clientConfig().apiUrl+"/api/googleAuth", {
body: JSON.stringify({ token: tokenResponse.access_token }),
body: JSON.stringify({ code: tokenResponse.code }),
method: "POST",
headers: {
'Content-Type': 'application/json'
}
}).then((res) => res.json()).then((data) => {
console.log("google auth response", data)
if(data.secret) {

setSession({ token: data })
window.localStorage.setItem("wg_secret", data.secret)

} else {
toast.error("Login error, contact support if this persists (2)")
}

}).catch((e) => {
console.error("google auth error", e)
toast.error("Login error, contact support if this persists (3)")
})
},
onError: error => {
Expand All @@ -123,7 +135,8 @@ export default function Home({ }) {
console.log("login non oauth error", error);
toast.error("Login error, contact support if this persists (1)")

}
},
flow: "auth-code",

});
if(typeof window !== "undefined") window.login = login;
Expand All @@ -136,7 +149,9 @@ export default function Home({ }) {
const [legacyMapLoader, setLegacyMapLoader] = useState(false);

useEffect(() => {
if (mainSession && !inCrazyGames) {
console.log("setting session", mainSession)

if (!inCrazyGames) {
setSession(mainSession)
}
}, [JSON.stringify(mainSession), inCrazyGames])
Expand Down Expand Up @@ -745,10 +760,15 @@ setShowCountryButtons(false)

const tz = moment.tz.guess();
let secret = "not_logged_in";
try {
secret = window.localStorage.getItem("wg_secret");
} catch(e) {
}
if(session?.token?.secret) {
secret = session.token.secret;
}


console.log("sending verify with secret", secret)
ws.send(JSON.stringify({ type: "verify", secret, tz}))
} else {
Expand Down
2 changes: 1 addition & 1 deletion components/playerList.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default function PlayerList({ multiplayerState, playAgain, backBtn, start
<FaCopy />
</button>
<br />
{ host && (
{ host && false && (
<button onClick={() => {

}} style={{
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@smastrom/react-rating": "^1.5.0",
"axios": "^1.7.7",
"bad-words": "^4.0.0",
"body-parser": "^1.20.3",
"colors": "^1.4.0",
"coordinate_to_country": "^1.1.0",
"cors": "^2.8.5",
Expand Down
8 changes: 4 additions & 4 deletions public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
"playFriends": "Play with Friends",
"guestMultiplayer": "Playing as {{name}}",
"findDuel": "Find a Duel",
"createGame": "Create Party",
"joinGame": "Join Party",
"createGame": "Create Private Game",
"joinGame": "Join Private Game",
"join": "Join",
"go": "Go",
"numOfRounds": "Number of rounds",
Expand All @@ -25,8 +25,8 @@
"findingGame": "Finding a game",
"waiting": "Waiting",
"gameOver": "Game Over",
"yourPrivateGame": "Your Party",
"privateGame": "Party",
"yourPrivateGame": "Your Private Game",
"privateGame": "Private Game",
"leaderboard": "Leaderboard",
"roundsCount": "{{rounds}} rounds",
"gameCode": "Game Code",
Expand Down
3 changes: 2 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import { createServer } from 'http';
import { createServer as createHttpsServer } from 'https';
import { Filter } from 'bad-words';
import validateSecret from './components/utils/validateSecret.js';

import bodyParser from 'body-parser';

// express
import express from 'express';
Expand All @@ -54,6 +54,7 @@ var app = express();
// disable cors
import cors from 'cors';
app.use(cors());
app.use(bodyParser.json());

app.use(express.json());

Expand Down

0 comments on commit 56f31a2

Please sign in to comment.