Added security customizations: bet controller and hashing

This commit is contained in:
2025-09-03 19:29:42 +02:00
parent 5eae90294e
commit e812bb61a6
3 changed files with 80 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Hash;
class SecurityHelper
{
public static function generateBetHash($userId, $amount, $gameId)
{
return Hash::make($userId . $amount . $gameId . now()->timestamp);
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers\Api;
use App\Helpers\SecurityHelper;
use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class BetController extends Controller
{
public function placeBet(Request $request)
{
$validated = $request->validate([
'game_id' => 'required|exists:games,id',
'amount' => 'required|numeric|min:0.01',
]);
DB::beginTransaction();
try {
$user = auth()->user();
if ($user->balance < $validated['amount']) {
abort(400, 'Insufficient balance');
}
$hash = SecurityHelper::generateBetHash($user->id, $validated['amount'], $validated['game_id']);
$game = Game::find($validated['game_id']);
$win = random_int(0, 100) < $game->win_probability;
$payout = $win ? $validated['amount'] * 2 : -$validated['amount'];
$user->balance += $payout;
$user->save();
Transaction::create([
'user_id' => $user->id,
'type' => $win ? 'win' : 'loss',
'amount' => abs($payout),
'description' => "Bet hash: $hash",
]);
DB::commit();
return response()->json([
'success' => true,
'win' => $win,
'balance' => $user->balance,
'hash' => $hash,
]);
} catch (\Exception $e) {
DB::rollback();
abort(500, $e->getMessage());
}
}
}