Skip to content

Commit

Permalink
Arena handle bot_token and bot_secret for bots joining game
Browse files Browse the repository at this point in the history
  • Loading branch information
AminArria committed Jun 12, 2024
1 parent 7e96845 commit 5fb98ef
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions apps/arena/lib/arena/game_socket_handler.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,10 @@ defmodule Arena.GameSocketHandler do

@impl true
def init(req, _opts) do
## TODO: The only reason we need this is because bots are broken, we should fix bots in a way that
## we don't need to pass a real user_id (or none at all). Ideally we could have JWT that says "Bot Sever".
client_id =
case :cowboy_req.parse_qs(req) do
[{"gateway_jwt", jwt}] ->
signer = GatewaySigner.get_signer()
{:ok, %{"sub" => user_id}} = GatewayTokenManager.verify_and_validate(jwt, signer)
user_id

_ ->
:cowboy_req.binding(:client_id, req)
end

game_id = :cowboy_req.binding(:game_id, req)
game_pid = game_id |> Base58.decode() |> :erlang.binary_to_term([:safe])

{:cowboy_websocket, req, %{client_id: client_id, game_pid: game_pid, game_id: game_id}}
user_id = get_user_id(req)
{:cowboy_websocket, req, %{client_id: user_id, game_pid: game_pid, game_id: game_id}}
end

@impl true
Expand Down Expand Up @@ -240,4 +227,19 @@ defmodule Arena.GameSocketHandler do

defp handle_decoded_message(_, _),
do: nil

defp get_user_id(req) do
signer = GatewaySigner.get_signer()

case :cowboy_req.parse_qs(req) do
[{"gateway_jwt", jwt}] ->
{:ok, %{"sub" => user_id}} = GatewayTokenManager.verify_and_validate(jwt, signer)
user_id

[{"bot_token", token}, {"bot_secret", secret}] ->
hashed_secret = :crypto.hash(:sha256, secret) |> Base.url_encode64()
{:ok, %{"bot" => ^hashed_secret}} = GatewayTokenManager.verify_and_validate(token, signer)
:cowboy_req.binding(:client_id, req)
end
end
end

0 comments on commit 5fb98ef

Please sign in to comment.