From e812bb61a6c82eef6eb74f023e24326fc169960d Mon Sep 17 00:00:00 2001 From: arriej Date: Wed, 3 Sep 2025 19:29:42 +0200 Subject: [PATCH] Added security customizations: bet controller and hashing --- app/Helpers/SecurityHelper.php | 13 +++++ app/Http/Controllers/Api/BetController.php | 56 ++++++++++++++++++++++ routes/api.php | 11 +++++ 3 files changed, 80 insertions(+) create mode 100644 app/Helpers/SecurityHelper.php create mode 100644 app/Http/Controllers/Api/BetController.php create mode 100644 routes/api.php diff --git a/app/Helpers/SecurityHelper.php b/app/Helpers/SecurityHelper.php new file mode 100644 index 0000000..47c58aa --- /dev/null +++ b/app/Helpers/SecurityHelper.php @@ -0,0 +1,13 @@ +timestamp); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/BetController.php b/app/Http/Controllers/Api/BetController.php new file mode 100644 index 0000000..4732e7f --- /dev/null +++ b/app/Http/Controllers/Api/BetController.php @@ -0,0 +1,56 @@ +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()); + } + } +} \ No newline at end of file diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..34be78d --- /dev/null +++ b/routes/api.php @@ -0,0 +1,11 @@ +get('/user', function (Request $request) { + return $request->user(); +}); + +Route::middleware('auth:sanctum')->post('/bet', [BetController::class, 'placeBet']); \ No newline at end of file