Skip to content

Commit

Permalink
refactor websocket tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
rileythomp committed Mar 1, 2024
1 parent e8a7b6e commit ca718b9
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 74 deletions.
71 changes: 20 additions & 51 deletions be-jeopardy/internal/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,41 +254,28 @@ func JoinPublicGame(c *gin.Context) {
func JoinGameChat(c *gin.Context) {
log.Infof("Received request to join game chat")

ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("Error upgrading connection to WebSocket: %s", err.Error())
respondWithError(c, http.StatusInternalServerError, ErrJoiningChatMsg)
return
}

_, msg, err := ws.ReadMessage()
token, err := c.Cookie(jwtCookie)
if err != nil {
log.Errorf("Error reading message from WebSocket: %s", err.Error())
closeConnWithMsg(ws, socket.ServerError, ErrJoiningChatMsg)
return
}

var req TokenRequest
if err := json.Unmarshal(msg, &req); err != nil {
log.Errorf("Error parsing chat request: %s", err.Error())
closeConnWithMsg(ws, socket.BadRequest, ErrMalformedReqMsg)
log.Errorf("Error getting token from cookie: %s", err.Error())
respondWithError(c, http.StatusForbidden, ErrInvalidAuthCredMsg)
return
}

playerId, err := auth.GetJWTSubject(req.Token)
playerId, err := auth.GetJWTSubject(token)
if err != nil {
log.Errorf(ErrGettingPlayerIdMsg, err.Error())
closeConnWithMsg(ws, socket.Unauthorized, ErrInvalidAuthCredMsg)
respondWithError(c, http.StatusUnauthorized, ErrInvalidAuthCredMsg)
return
}

conn := socket.NewSafeConn(ws)
err = jeopardy.JoinGameChat(playerId, conn)
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("Error joining chat: %s", err.Error())
closeConnWithMsg(ws, socket.BadRequest, "Unable to join chat: %s", err.Error())
log.Errorf("Error upgrading connection to WebSocket: %s", err.Error())
respondWithError(c, http.StatusInternalServerError, ErrJoiningChatMsg)
return
}

jeopardy.JoinGameChat(playerId, ws)
}

func AddBot(c *gin.Context) {
Expand Down Expand Up @@ -318,41 +305,28 @@ func AddBot(c *gin.Context) {
func PlayGame(c *gin.Context) {
log.Infof("Received play request")

ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("Error upgrading connection to WebSocket: %s", err.Error())
respondWithError(c, http.StatusInternalServerError, UnexpectedServerErrMsg)
return
}

_, msg, err := ws.ReadMessage()
token, err := c.Cookie(jwtCookie)
if err != nil {
log.Errorf("Error reading message from WebSocket: %s", err.Error())
closeConnWithMsg(ws, socket.ServerError, UnexpectedServerErrMsg)
return
}

var req TokenRequest
if err := json.Unmarshal(msg, &req); err != nil {
log.Errorf("Error parsing play request: %s", err.Error())
closeConnWithMsg(ws, socket.BadRequest, ErrMalformedReqMsg)
log.Errorf("Error getting token from cookie: %s", err.Error())
respondWithError(c, http.StatusForbidden, ErrInvalidAuthCredMsg)
return
}

playerId, err := auth.GetJWTSubject(req.Token)
playerId, err := auth.GetJWTSubject(token)
if err != nil {
log.Errorf(ErrGettingPlayerIdMsg, err.Error())
closeConnWithMsg(ws, socket.Unauthorized, ErrInvalidAuthCredMsg)
respondWithError(c, http.StatusUnauthorized, ErrInvalidAuthCredMsg)
return
}

conn := socket.NewSafeConn(ws)
err = jeopardy.PlayGame(playerId, conn)
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("Error playing game: %s", err.Error())
closeConnWithMsg(ws, socket.BadRequest, "Unable to play game: %s", err.Error())
log.Errorf("Error upgrading connection to WebSocket: %s", err.Error())
respondWithError(c, http.StatusInternalServerError, UnexpectedServerErrMsg)
return
}

jeopardy.PlayGame(playerId, ws)
}

func PlayAgain(c *gin.Context) {
Expand Down Expand Up @@ -441,11 +415,6 @@ func parseBody(body io.ReadCloser, v any) error {
return json.Unmarshal(msg, v)
}

func closeConnWithMsg(conn *websocket.Conn, code int, msg string, args ...any) {
_ = conn.WriteJSON(jeopardy.Response{Code: code, Message: fmt.Sprintf(msg, args...)})
_ = conn.Close()
}

func respondWithError(c *gin.Context, code int, msg string, args ...any) {
c.JSON(code, jeopardy.Response{Code: code, Message: fmt.Sprintf(msg, args...)})
}
Expand Down
19 changes: 13 additions & 6 deletions be-jeopardy/internal/jeopardy/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/gorilla/websocket"
"github.com/rileythomp/jeopardy/be-jeopardy/internal/log"
"github.com/rileythomp/jeopardy/be-jeopardy/internal/socket"
)

type ChatMessage struct {
Expand All @@ -15,25 +16,31 @@ type ChatMessage struct {
TimeStamp int64 `json:"timeStamp"`
}

func JoinGameChat(playerId string, conn SafeConn) error {
func JoinGameChat(playerId string, ws *websocket.Conn) {
conn := socket.NewSafeConn(ws)

game, err := GetPlayerGame(playerId)
if err != nil {
return err
log.Errorf("Error getting game for player %s: %s", playerId, err.Error())
closeConnWithMsg(conn, socket.BadRequest, "Unable to join chat: %s", err.Error())
return
}

player, err := game.getPlayerById(playerId)
if err != nil {
return err
log.Errorf("Error getting player by id: %s", err.Error())
closeConnWithMsg(conn, socket.BadRequest, "Unable to join chat: %s", err.Error())
return
}
if player.chatConn() != nil {
return fmt.Errorf("Player already in chat")
log.Errorf("Error joining chat: Player already in chat")
closeConnWithMsg(conn, socket.BadRequest, "Unable to join chat: Player already in chat")
return
}
player.setChatConn(conn)

player.sendChatPings()
player.processChatMessages(game.chatChan)

return nil
}

func (p *Player) processChatMessages(chatChan chan ChatMessage) {
Expand Down
24 changes: 18 additions & 6 deletions be-jeopardy/internal/jeopardy/jeopardy.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/rileythomp/jeopardy/be-jeopardy/internal/db"
"github.com/rileythomp/jeopardy/be-jeopardy/internal/log"
"github.com/rileythomp/jeopardy/be-jeopardy/internal/socket"
Expand Down Expand Up @@ -167,26 +168,32 @@ func AddBot(playerId string) error {
return nil
}

func PlayGame(playerId string, conn SafeConn) error {
func PlayGame(playerId string, ws *websocket.Conn) {
conn := socket.NewSafeConn(ws)

game, err := GetPlayerGame(playerId)
if err != nil {
return err
log.Errorf("Error getting game for player: %s", err.Error())
closeConnWithMsg(conn, socket.BadRequest, "Unable to play game: %s", err.Error())
return
}

player, err := game.getPlayerById(playerId)
if err != nil {
return err
log.Errorf("Error getting player by id: %s", err.Error())
closeConnWithMsg(conn, socket.BadRequest, "Unable to play game: %s", err.Error())
return
}
if player.conn() != nil {
return fmt.Errorf("Player already playing")
log.Errorf("Error playing game: Player already playing")
closeConnWithMsg(conn, socket.BadRequest, "Unable to play game: Player already playing")
return
}
player.setConn(conn)
player.sendPings()
player.readMessages(game.msgChan, game.pauseChan)

game.handlePlayerJoined(player)

return nil
}

func (g *Game) handlePlayerJoined(player GamePlayer) {
Expand Down Expand Up @@ -285,3 +292,8 @@ func removeGame(g *Game) {
delete(playerGames, p.id())
}
}

func closeConnWithMsg(conn SafeConn, code int, msg string, args ...any) {
_ = conn.WriteJSON(Response{Code: code, Message: fmt.Sprintf(msg, args...)})
_ = conn.Close()
}
4 changes: 0 additions & 4 deletions fe-jeopardy/src/app/game/chat/chat.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ export class ChatComponent implements OnInit, AfterViewChecked {
ngOnInit(): void {
this.chatService.Connect()

this.chatService.OnOpen(() => {
this.chatService.Send({ token: this.jwt })
})

this.chatService.OnMessage((event: { data: string }) => {
let resp = JSON.parse(event.data)

Expand Down
7 changes: 0 additions & 7 deletions fe-jeopardy/src/app/game/game.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,6 @@ export class GameComponent implements OnInit {

this.websocketService.Connect('play')

this.websocketService.OnOpen(() => {
this.websocketService.Send({
state: GameState.PreGame,
token: this.jwt,
})
})

this.websocketService.OnMessage((event: { data: string }) => {
let resp = JSON.parse(event.data)

Expand Down

0 comments on commit ca718b9

Please sign in to comment.