Rate limit game creation

This commit is contained in:
Logan Hunt 2023-01-31 12:44:15 -07:00
parent 4394d4721c
commit e5d97870a1
No known key found for this signature in database
GPG Key ID: 8AC6A4B840C0EC49
3 changed files with 65 additions and 33 deletions

View File

@ -12,7 +12,9 @@ config :chessh, RateLimits,
max_concurrent_user_sessions: 5,
player_session_message_burst_ms: 500,
player_session_message_burst_rate: 8,
player_public_keys: 15
player_public_keys: 15,
create_game_ms: 60 * 1000,
create_game_rate: 2
config :chessh, Web,
github_oauth_login_url: "https://github.com/login/oauth/access_token",

View File

@ -45,9 +45,8 @@ defmodule Chessh.SSH.Client do
screen_state_initials: screen_state_initials
} = state
) do
{:ok, new_screen_pid} =
GenServer.start_link(module, [%{screen_state_initial | client_pid: self()}])
case GenServer.start_link(module, [%{screen_state_initial | client_pid: self()}]) do
{:ok, new_screen_pid} ->
send(new_screen_pid, {:render, width, height})
{:noreply,
@ -56,6 +55,10 @@ defmodule Chessh.SSH.Client do
| screen_pid: new_screen_pid,
screen_state_initials: [{module, screen_state_initial} | screen_state_initials]
}}
_ ->
{:noreply, state}
end
end
@impl true

View File

@ -59,9 +59,23 @@ 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
[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(
@ -85,6 +99,19 @@ defmodule Chessh.SSH.Client.Game do
}
| 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"
]}
)
{:stop, :normal, state}
end
end
def init([