Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix/89: websocket token flow #90

Merged
merged 1 commit into from
Nov 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/src/chat/chat.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@
}
}

afterInit(_: Server) {

Check warning on line 556 in backend/src/chat/chat.gateway.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

'_' is defined but never used
this.server.use((socket, next) => {
this.validateConnection(socket)
.then((user) => {
Expand All @@ -569,7 +569,8 @@
}

private validateConnection(client: Socket) {
const token = client.handshake.headers.cookie.split(';')[0].split('=')[1];
const token = client.handshake.auth.token;

try {
const payload = this.jwtService.verify<TokenPayload>(token, {
secret: process.env.JWT_SECRET,
Expand Down
4 changes: 2 additions & 2 deletions backend/src/game/game.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {

handleConnection(client: Socket) {
// Get user from cookie coming from client
const user = client.handshake.headers.cookie.split(';')[0].split('=')[1];
const user = client.handshake.auth.token;

// Decode user from JWT
const decodedUser = this.jwtService.decode(user).sub;
Expand All @@ -53,7 +53,7 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {

@SubscribeMessage('joinGame')
joinGame(client: Socket) {
const user = client.handshake.headers.cookie.split(';')[0].split('=')[1];
const user = client.handshake.auth.token;
const decodedUser = this.jwtService.decode(user).sub;

if (this.gameLobby.joinPlayer1(client, decodedUser)) {
Expand Down
14 changes: 10 additions & 4 deletions frontend/src/contexts/GameContext.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";
import React, { createContext, useEffect, useRef, useState } from "react";
import io, { Socket } from "socket.io-client";
import nookies from "nookies";

/**
* Backend websocket events
Expand Down Expand Up @@ -52,7 +53,7 @@ export type MovePlayerData = {
direction: string;
};

export type GameLayout = 'default' | 'sunlight' | 'moonlight' | 'dark';
export type GameLayout = "default" | "sunlight" | "moonlight" | "dark";

type GameContextType = {
waitingPlayer2: boolean;
Expand All @@ -79,13 +80,18 @@ export const GameProvider = ({ children }: GameProviderProps) => {
const [clientId, setClientId] = useState("");
const [gameData, setGameData] = useState({} as GameData);
const [gameFinishedData, setGameFinishedData] = useState({} as GameData);
const [gameLayout, setGameLayout] = useState<GameLayout>('default');
const [gameLayout, setGameLayout] = useState<GameLayout>("default");

const socket = useRef<Socket | null>(null);

useEffect(() => {
// Listen for the 'connect' event
const { accessToken } = nookies.get(null, "accesssToken");

socket.current = io("http://localhost:3000/game", {
auth: {
token: accessToken,
},
transports: ["websocket", "polling", "flashsocket"],
});

Expand Down Expand Up @@ -180,8 +186,8 @@ export const GameProvider = ({ children }: GameProviderProps) => {
gameAbandoned,
gameFinishedData,
gameData,
gameLayout,
setGameLayout
gameLayout,
setGameLayout,
}}
>
{children}
Expand Down
3 changes: 0 additions & 3 deletions frontend/src/services/api.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { TokenPayload, signOut } from "@/contexts/AuthContext";
import axios, { AxiosError } from "axios";
import nookies from "nookies";
import jwt_decode from "jwt-decode";
import { GetServerSidePropsContext } from "next";
import { parseCookies } from "nookies";

type Context = undefined | GetServerSidePropsContext;

Expand All @@ -13,7 +11,6 @@ export function setupAPIClient(ctx: Context = undefined) {
api.interceptors.request.use(
(config) => {
const { accessToken } = nookies.get(null, "accesssToken");
const payload: TokenPayload = jwt_decode(accessToken);

if (accessToken) {
config.headers["Authorization"] = `Bearer ${accessToken}`;
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/services/chatClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { io, Socket } from "socket.io-client";
import nookies from "nookies";

class ChatService {
public socket: Socket | null;
Expand All @@ -9,7 +10,12 @@ class ChatService {

public connect(): void {
if (!this.socket) {
const { accessToken } = nookies.get(null, "accesssToken");

this.socket = io("http://localhost:3000/chat", {
auth: {
token: accessToken,
},
transports: ["websocket", "polling", "flashsocket"],
});
}
Expand Down
Loading