Added security customizations: bet controller and hashing
This commit is contained in:
13
app/Helpers/SecurityHelper.php
Normal file
13
app/Helpers/SecurityHelper.php
Normal 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);
|
||||
}
|
||||
}
|
||||
56
app/Http/Controllers/Api/BetController.php
Normal file
56
app/Http/Controllers/Api/BetController.php
Normal 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
11
routes/api.php
Normal file
11
routes/api.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use App\Http\Controllers\Api\BetController;
|
||||
|
||||
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
|
||||
return $request->user();
|
||||
});
|
||||
|
||||
Route::middleware('auth:sanctum')->post('/bet', [BetController::class, 'placeBet']);
|
||||
Reference in New Issue
Block a user