gambosite/app/controllers/game_controller.rb

79 lines
1.9 KiB
Ruby
Raw Normal View History

2025-01-24 10:22:13 -08:00
class GameController < ApplicationController
2025-01-26 15:26:34 -08:00
skip_before_action :verify_authenticity_token, only: [ :create ]
2025-01-24 10:22:13 -08:00
respond_to? :json
def index
@recent_games = Game.order(timestamp: :desc).limit(20)
end
def show
@game = Game.find(params[:id])
end
def create
2025-01-24 13:03:47 -08:00
unless authenticate_api_key?
unauthorized_response
return
end
2025-01-24 10:22:13 -08:00
game_params[:timestamp] = Time.at(params[:timestamp].to_i).utc if params[:timestamp].present?
if Game.find_by(timestamp: game_params[:timestamp])
2025-01-24 13:03:47 -08:00
already_reported_response
return
2025-01-24 10:22:13 -08:00
end
players = []
params[:players].each do | name, _pos |
player = Player.find_by(name: name)
if player.nil?
player = Player.new(name: name, wins: 0, losses: 0, purse: 0)
player.save
end
players << player
end
@game = Game.create(game_params)
2025-01-24 13:03:47 -08:00
@game.client = @apikey.client
2025-01-24 10:22:13 -08:00
if @game.save
players.each do | player |
if @game.winner == player.name
player.purse += @game.payout
player.wins += 1
player.save
elsif @game.loser == player.name
player.purse -= @game.payout
player.losses += 1
player.save
end
end
2025-01-24 13:03:47 -08:00
render json: {}, status: :ok
2025-01-24 10:22:13 -08:00
else
2025-01-24 13:03:47 -08:00
render json: { error: "Unable to process input" }, status: :unprocessable_content
2025-01-24 10:22:13 -08:00
end
end
private
def game_params
params.require(:game).permit(:timestamp, :gametype, :wager, :winner, :loser, :high_roll, :low_roll, :payout)
end
2025-01-24 13:03:47 -08:00
def authenticate_api_key?
api_key = request.headers["X-API-KEY"]
if api_key.present? && ApiKey.exists?(key: api_key)
@apikey = ApiKey.find_by(key: api_key)
return true
end
false
end
def unauthorized_response
render json: { error: "API key is missing or empty" }, status: :unauthorized
end
def already_reported_response
render json: { error: "Already reported this gambo" }, status: :already_reported
end
2025-01-24 10:22:13 -08:00
end