diff options
author | Logan Hunt <logan.hunt@usu.edu> | 2023-01-31 12:44:15 -0700 |
---|---|---|
committer | Logan Hunt <logan.hunt@usu.edu> | 2023-01-31 12:44:15 -0700 |
commit | e5d97870a12ec87bd463b7657923bb79d3bcb4cc (patch) | |
tree | e552aa6d98d9ccf628d4274b8d9538e741724530 /lib/chessh/ssh/client/game/game.ex | |
parent | 4394d4721ccd5d9b503d01918ff3d6e5d6744c9d (diff) | |
download | chessh-e5d97870a12ec87bd463b7657923bb79d3bcb4cc.tar.gz chessh-e5d97870a12ec87bd463b7657923bb79d3bcb4cc.zip |
Rate limit game creation
Diffstat (limited to 'lib/chessh/ssh/client/game/game.ex')
-rw-r--r-- | lib/chessh/ssh/client/game/game.ex | 69 |
1 files changed, 48 insertions, 21 deletions
diff --git a/lib/chessh/ssh/client/game/game.ex b/lib/chessh/ssh/client/game/game.ex index 3ecd2e4..4a79d05 100644 --- a/lib/chessh/ssh/client/game/game.ex +++ b/lib/chessh/ssh/client/game/game.ex @@ -59,32 +59,59 @@ defmodule Chessh.SSH.Client.Game do end def init([ - %State{player_session: player_session, color: color, game: nil} = state + %State{player_session: player_session, color: color, game: nil, client_pid: client_pid} = + state | tail ]) do - # Starting a new game - {:ok, %Game{} = game} = - Game.changeset( - %Game{}, - Map.merge( - if(color == :light, - do: %{light_player_id: player_session.player_id}, - else: %{dark_player_id: player_session.player_id} - ), - %{ - fen: @default_fen + [create_game_ms, create_game_rate] = + Application.get_env(:chessh, RateLimits) + |> Keyword.take([:create_game_ms, :create_game_rate]) + |> Keyword.values() + + case Hammer.check_rate_inc( + :redis, + "player-#{state.player_session.id}-create-game-rate", + create_game_ms, + create_game_rate, + 1 + ) do + {:allow, _count} -> + # Starting a new game + {:ok, %Game{} = game} = + Game.changeset( + %Game{}, + Map.merge( + if(color == :light, + do: %{light_player_id: player_session.player_id}, + else: %{dark_player_id: player_session.player_id} + ), + %{ + fen: @default_fen + } + ) + ) + |> Repo.insert() + + init([ + %State{ + state + | game: game } + | tail + ]) + + {:deny, _limit} -> + send( + client_pid, + {:send_to_ssh, + [ + Utils.clear_codes(), + "You are creating too many games, and have been rate limited. Try again later.\n" + ]} ) - ) - |> Repo.insert() - init([ - %State{ - state - | game: game - } - | tail - ]) + {:stop, :normal, state} + end end def init([ |