feature/profile-page #71
@@ -101,3 +101,4 @@ Desktop.ini
|
|||||||
# /path/to/some/file
|
# /path/to/some/file
|
||||||
|
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
.vscode
|
||||||
Vendored
-3
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"postman.settings.dotenv-detection-notification-visibility": false
|
|
||||||
}
|
|
||||||
@@ -6,22 +6,31 @@ use App\Models\Game;
|
|||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use App\Http\Requests\StoreGameRequest;
|
use App\Http\Requests\StoreGameRequest;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use App\Models\MatchGame;
|
||||||
|
|
||||||
class GameController extends Controller
|
class GameController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request)
|
public function index(Request $request)
|
||||||
{
|
{
|
||||||
$query = Game::query()->with(['winner', 'player1', 'player2']);
|
$query = Game::query()->with(["winner", "player1", "player2"]);
|
||||||
|
|
||||||
if ($request->has('type') && in_array($request->type, ['3', '9'])) {
|
if ($request->has("type") && in_array($request->type, ["3", "9"])) {
|
||||||
$query->where('type', $request->type);
|
$query->where("type", $request->type);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->has('status') && in_array($request->status, ['Pending', 'Playing', 'Ended', 'Interrupted'])) {
|
if (
|
||||||
$query->where('status', $request->status);
|
$request->has("status") &&
|
||||||
|
in_array($request->status, [
|
||||||
|
"Pending",
|
||||||
|
"Playing",
|
||||||
|
"Ended",
|
||||||
|
"Interrupted",
|
||||||
|
])
|
||||||
|
) {
|
||||||
|
$query->where("status", $request->status);
|
||||||
}
|
}
|
||||||
|
|
||||||
$query->orderBy('began_at', 'desc');
|
$query->orderBy("began_at", "desc");
|
||||||
|
|
||||||
return response()->json($query->paginate(15));
|
return response()->json($query->paginate(15));
|
||||||
}
|
}
|
||||||
@@ -29,39 +38,56 @@ class GameController extends Controller
|
|||||||
public function store(Request $request)
|
public function store(Request $request)
|
||||||
{
|
{
|
||||||
$validated = $request->validate([
|
$validated = $request->validate([
|
||||||
'type' => 'required|in:3,9',
|
"type" => "required|in:3,9",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$user = Auth::user();
|
$user = Auth::user();
|
||||||
|
|
||||||
$activeGame = Game::where(function ($query) use ($user) {
|
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||||
$query->where('player1_user_id', $user->id)
|
$q->where("player1_user_id", $user->id)->orWhere(
|
||||||
->orWhere('player2_user_id', $user->id);
|
"player2_user_id",
|
||||||
|
$user->id,
|
||||||
|
);
|
||||||
})
|
})
|
||||||
->whereIn('status', ['Pending', 'Playing'])
|
->whereIn("status", ["Pending", "Playing"])
|
||||||
->exists();
|
->exists();
|
||||||
|
|
||||||
if ($activeGame) {
|
$activeGame = Game::where(function ($q) use ($user) {
|
||||||
return response()->json(['message' => 'You already have an active game.'], 400);
|
$q->where("player1_user_id", $user->id)->orWhere(
|
||||||
|
"player2_user_id",
|
||||||
|
$user->id,
|
||||||
|
);
|
||||||
|
})
|
||||||
|
->whereIn("status", ["Pending", "Playing"])
|
||||||
|
->exists();
|
||||||
|
|
||||||
|
if ($activeMatch || $activeGame) {
|
||||||
|
return response()->json(
|
||||||
|
["message" => "You already have an active game or match."],
|
||||||
|
400,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$game = Game::create([
|
$game = Game::create([
|
||||||
'type' => $validated['type'],
|
"type" => $validated["type"],
|
||||||
'status' => 'Pending',
|
"status" => "Pending",
|
||||||
'player1_user_id' => $user->id,
|
"player1_user_id" => $user->id,
|
||||||
'player2_user_id' => $user->id,
|
"player2_user_id" => null,
|
||||||
'winner_user_id' => $user->id,
|
"winner_user_id" => null,
|
||||||
'loser_user_id' => $user->id,
|
"loser_user_id" => null,
|
||||||
'began_at' => now(),
|
"began_at" => now(),
|
||||||
'player1_points' => 0,
|
"player1_points" => 0,
|
||||||
'player2_points' => 0,
|
"player2_points" => 0,
|
||||||
'custom' => null
|
"custom" => null,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json(
|
||||||
'message' => 'Multiplayer game room created',
|
[
|
||||||
'game' => $game
|
"message" => "Multiplayer game room created",
|
||||||
], 201);
|
"game" => $game,
|
||||||
|
],
|
||||||
|
201,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function join(Game $game)
|
public function join(Game $game)
|
||||||
@@ -69,62 +95,75 @@ class GameController extends Controller
|
|||||||
$user = Auth::user();
|
$user = Auth::user();
|
||||||
|
|
||||||
if ($game->player1_user_id == $user->id) {
|
if ($game->player1_user_id == $user->id) {
|
||||||
return response()->json([
|
return response()->json(
|
||||||
'message' => 'Waiting for opponent...',
|
[
|
||||||
'game' => $game
|
"message" => "Waiting for opponent...",
|
||||||
], 200);
|
"game" => $game,
|
||||||
|
],
|
||||||
|
200,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($game->status !== 'Pending') {
|
if ($game->status !== "Pending") {
|
||||||
return response()->json(['message' => 'Game is full or already started'], 400);
|
return response()->json(
|
||||||
|
["message" => "Game is full or already started"],
|
||||||
|
400,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$activeGame = Game::where(function ($query) use ($user) {
|
$activeGame = Game::where(function ($query) use ($user) {
|
||||||
$query->where('player1_user_id', $user->id)
|
$query
|
||||||
->orWhere('player2_user_id', $user->id);
|
->where("player1_user_id", $user->id)
|
||||||
|
->orWhere("player2_user_id", $user->id);
|
||||||
})
|
})
|
||||||
->whereIn('status', ['Pending', 'Playing'])
|
->whereIn("status", ["Pending", "Playing"])
|
||||||
->exists();
|
->exists();
|
||||||
|
|
||||||
if ($activeGame) {
|
if ($activeGame) {
|
||||||
return response()->json(['message' => 'You are already in another active game.'], 400);
|
return response()->json(
|
||||||
|
["message" => "You are already in another active game."],
|
||||||
|
400,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$game->update([
|
$game->update([
|
||||||
'status' => 'Playing',
|
"status" => "Playing",
|
||||||
'player2_user_id' => $user->id,
|
"player2_user_id" => $user->id,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json(
|
||||||
'message' => 'Joined successfully! Game starts now.',
|
[
|
||||||
'game' => $game
|
"message" => "Joined successfully! Game starts now.",
|
||||||
], 200);
|
"game" => $game,
|
||||||
|
],
|
||||||
|
200,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Game $game)
|
public function show(Game $game)
|
||||||
{
|
{
|
||||||
$game->load(['player1', 'player2', 'winner']);
|
$game->load(["player1", "player2", "winner"]);
|
||||||
return response()->json($game);
|
return response()->json($game);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function update(Request $request, Game $game)
|
public function update(Request $request, Game $game)
|
||||||
{
|
{
|
||||||
if ($game->status == 'Ended') {
|
if ($game->status == "Ended") {
|
||||||
return response()->json(['message' => 'Game already ended'], 400);
|
return response()->json(["message" => "Game already ended"], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'status' => 'in:Playing,Ended,Interrupted',
|
"status" => "in:Playing,Ended,Interrupted",
|
||||||
'winner_user_id' => 'exists:users,id',
|
"winner_user_id" => "exists:users,id",
|
||||||
'loser_user_id' => 'exists:users,id',
|
"loser_user_id" => "exists:users,id",
|
||||||
'player1_points' => 'integer',
|
"player1_points" => "integer",
|
||||||
'player2_points' => 'integer',
|
"player2_points" => "integer",
|
||||||
'is_draw' => 'boolean',
|
"is_draw" => "boolean",
|
||||||
'total_time' => 'numeric'
|
"total_time" => "numeric",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (isset($data['status']) && $data['status'] === 'Ended') {
|
if (isset($data["status"]) && $data["status"] === "Ended") {
|
||||||
$data['ended_at'] = now();
|
$data["ended_at"] = now();
|
||||||
}
|
}
|
||||||
|
|
||||||
$game->update($data);
|
$game->update($data);
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\MatchGame;
|
||||||
|
use App\Models\Game;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use App\Http\Requests\StoreMatchRequest;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
||||||
|
class MatchController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request)
|
||||||
|
{
|
||||||
|
$query = MatchGame::query()->with(['winner', 'player1', 'player2']);
|
||||||
|
|
||||||
|
if ($request->has('type')) {
|
||||||
|
$query->where('type', $request->type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->has('status')) {
|
||||||
|
$query->where('status', $request->status);
|
||||||
|
}
|
||||||
|
|
||||||
|
$query->orderBy('began_at', 'desc');
|
||||||
|
|
||||||
|
return response()->json($query->paginate(15));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(StoreMatchRequest $request)
|
||||||
|
{
|
||||||
|
$validated = $request->validated();
|
||||||
|
$user = Auth::user();
|
||||||
|
|
||||||
|
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||||
|
$q->where('player1_user_id', $user->id)
|
||||||
|
->orWhere('player2_user_id', $user->id);
|
||||||
|
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
||||||
|
|
||||||
|
$activeGame = Game::where(function ($q) use ($user) {
|
||||||
|
$q->where('player1_user_id', $user->id)
|
||||||
|
->orWhere('player2_user_id', $user->id);
|
||||||
|
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
||||||
|
|
||||||
|
if ($activeMatch || $activeGame) {
|
||||||
|
return response()->json(['message' => 'You already have an active game or match.'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$match = MatchGame::create([
|
||||||
|
'type' => $validated['type'],
|
||||||
|
'status' => 'Pending',
|
||||||
|
'player1_user_id' => $user->id,
|
||||||
|
'player2_user_id' => $user->id,
|
||||||
|
'winner_user_id' => $user->id,
|
||||||
|
'loser_user_id' => $user->id,
|
||||||
|
'stake' => $validated['stake'],
|
||||||
|
'began_at' => now(),
|
||||||
|
'player1_marks' => 0,
|
||||||
|
'player2_marks' => 0,
|
||||||
|
'player1_points' => 0,
|
||||||
|
'player2_points' => 0,
|
||||||
|
'custom' => null
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'Match created successfully',
|
||||||
|
'match' => $match
|
||||||
|
], 201);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(MatchGame $match)
|
||||||
|
{
|
||||||
|
$match->load(['player1', 'player2', 'winner']);
|
||||||
|
return response()->json($match);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function join(MatchGame $match)
|
||||||
|
{
|
||||||
|
$user = Auth::user();
|
||||||
|
|
||||||
|
if ($match->player1_user_id == $user->id) {
|
||||||
|
return response()->json(['message' => 'Waiting for opponent...', 'match' => $match]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($match->status !== 'Pending') {
|
||||||
|
return response()->json(['message' => 'Match is full or started'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||||
|
$q->where('player1_user_id', $user->id)
|
||||||
|
->orWhere('player2_user_id', $user->id);
|
||||||
|
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
||||||
|
|
||||||
|
if ($activeMatch) {
|
||||||
|
return response()->json(['message' => 'You are already in another active match.'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$match->update([
|
||||||
|
'status' => 'Playing',
|
||||||
|
'player2_user_id' => $user->id
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'Joined match successfully!',
|
||||||
|
'match' => $match
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request, MatchGame $match)
|
||||||
|
{
|
||||||
|
if ($match->status == 'Ended') {
|
||||||
|
return response()->json(['message' => 'Match already ended'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = $request->validate([
|
||||||
|
'status' => 'in:Playing,Ended,Interrupted',
|
||||||
|
'winner_user_id' => 'exists:users,id',
|
||||||
|
'loser_user_id' => 'exists:users,id',
|
||||||
|
'player1_marks' => 'integer',
|
||||||
|
'player2_marks' => 'integer',
|
||||||
|
'player1_points' => 'integer',
|
||||||
|
'player2_points' => 'integer',
|
||||||
|
'total_time' => 'numeric'
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (isset($data['status']) && $data['status'] === 'Ended') {
|
||||||
|
$data['ended_at'] = now();
|
||||||
|
}
|
||||||
|
|
||||||
|
$match->update($data);
|
||||||
|
|
||||||
|
return response()->json($match);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
||||||
|
class StoreMatchRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return Auth::check();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type' => 'required|in:3,9',
|
||||||
|
'stake' => 'required|integer|min:1',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class MatchGame extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $table = 'matches';
|
||||||
|
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'type',
|
||||||
|
'status',
|
||||||
|
'player1_user_id',
|
||||||
|
'player2_user_id',
|
||||||
|
'winner_user_id',
|
||||||
|
'loser_user_id',
|
||||||
|
'began_at',
|
||||||
|
'ended_at',
|
||||||
|
'total_time',
|
||||||
|
'player1_marks',
|
||||||
|
'player2_marks',
|
||||||
|
'player1_points',
|
||||||
|
'player2_points',
|
||||||
|
'stake',
|
||||||
|
'custom'
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'began_at' => 'datetime',
|
||||||
|
'ended_at' => 'datetime',
|
||||||
|
'player1_marks' => 'integer',
|
||||||
|
'player2_marks' => 'integer',
|
||||||
|
'player1_points' => 'integer',
|
||||||
|
'player2_points' => 'integer',
|
||||||
|
'stake' => 'integer',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function player1()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'player1_user_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function player2()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'player2_user_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function winner()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'winner_user_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
-16
@@ -2,28 +2,33 @@
|
|||||||
|
|
||||||
use App\Http\Controllers\AuthController;
|
use App\Http\Controllers\AuthController;
|
||||||
use App\Http\Controllers\GameController;
|
use App\Http\Controllers\GameController;
|
||||||
|
use App\Http\Controllers\MatchController;
|
||||||
use App\Http\Controllers\UserController;
|
use App\Http\Controllers\UserController;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
// Authentication Routes
|
||||||
# Authentication Routes
|
|
||||||
Route::post('/login', [AuthController::class, 'login']);
|
Route::post('/login', [AuthController::class, 'login']);
|
||||||
|
|
||||||
Route::middleware('auth:sanctum')->group(function () {
|
|
||||||
Route::get('/users/me', function (Request $request) {
|
|
||||||
return $request->user();
|
|
||||||
});
|
|
||||||
Route::post('logout', [AuthController::class, 'logout']);
|
|
||||||
});
|
|
||||||
|
|
||||||
Route::post('/register', [AuthController::class, 'register']);
|
Route::post('/register', [AuthController::class, 'register']);
|
||||||
|
|
||||||
# Game Routes - Protected
|
|
||||||
Route::middleware('auth:sanctum')->group(function () {
|
Route::middleware('auth:sanctum')->group(function () {
|
||||||
Route::apiResource('games', GameController::class);
|
Route::post('logout', [AuthController::class, 'logout']);
|
||||||
Route::post('games', [GameController::class, 'store']);
|
|
||||||
Route::post('/games/{game}/resign', [GameController::class, 'resign']);
|
Route::prefix('users')->group(function () {
|
||||||
Route::get('/users/{user}/matches', [UserController::class, 'getMatches']);
|
Route::get('/me', function (Request $request) {
|
||||||
Route::post('games/{game}/join', [GameController::class, 'join']);
|
return $request->user();
|
||||||
|
});
|
||||||
|
Route::get('/{user}/matches', [UserController::class, 'getMatches']);
|
||||||
|
});
|
||||||
|
|
||||||
|
Route::prefix('games')->group(function () {
|
||||||
|
Route::apiResource('/', GameController::class)->parameters(['' => 'game']);
|
||||||
|
Route::post('/{game}/resign', [GameController::class, 'resign']);
|
||||||
|
Route::post('/{game}/join', [GameController::class, 'join']);
|
||||||
|
});
|
||||||
|
|
||||||
|
Route::prefix('matches')->group(function () {
|
||||||
|
Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
|
||||||
|
Route::post('/{match}/join', [MatchController::class, 'join']);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
### Get All Students
|
||||||
|
POST http://localhost:8000/api/login
|
||||||
|
content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"email": "[email protected]",
|
||||||
|
"password": "123"
|
||||||
|
}
|
||||||
Generated
+417
-469
File diff suppressed because it is too large
Load Diff
@@ -17,22 +17,21 @@
|
|||||||
Email address
|
Email address
|
||||||
</label>
|
</label>
|
||||||
<Input id="email" v-model="formData.email" type="email" autocomplete="email" required
|
<Input id="email" v-model="formData.email" type="email" autocomplete="email" required
|
||||||
placeholder="[email protected]" :disabled="isLoading" />
|
placeholder="[email protected]" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">
|
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Password
|
Password
|
||||||
</label>
|
</label>
|
||||||
<Input id="password" v-model="formData.password" type="password" autocomplete="current-password" required
|
<Input id="password" v-model="formData.password" type="password" autocomplete="current-password"
|
||||||
placeholder="••••••••" :disabled="isLoading" />
|
required placeholder="••••••••" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Button type="submit" class="w-full" :disabled="isLoading">
|
<Button type="submit" class="w-full"> Sign in </Button>
|
||||||
{{ isLoading ? 'Signing in...' : 'Sign in' }}
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="text-center text-sm">
|
<div class="text-center text-sm">
|
||||||
@@ -50,6 +49,7 @@
|
|||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
@@ -62,23 +62,17 @@ const formData = ref({
|
|||||||
password: '123'
|
password: '123'
|
||||||
})
|
})
|
||||||
|
|
||||||
const isLoading = ref(false)
|
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
isLoading.value = true
|
const promise = authStore.login(formData.value)
|
||||||
|
toast.promise(promise, {
|
||||||
try {
|
loading: 'Calling API',
|
||||||
const user = await authStore.login(formData.value)
|
success: (user) => {
|
||||||
|
|
||||||
toast.success(`Login Successful - Welcome ${user?.name}!`)
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
router.push('/')
|
router.push('/')
|
||||||
}, 500)
|
return `Login Successful - ${user.name}`
|
||||||
} catch (error) {
|
},
|
||||||
toast.error(`Login Failed - ${error?.response?.data?.message || error.message}`)
|
error: (error) =>
|
||||||
} finally {
|
error.response?.data?.message
|
||||||
isLoading.value = false
|
})
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
// src/stores/api.js
|
|
||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { inject, ref } from 'vue'
|
import { inject, ref } from 'vue'
|
||||||
@@ -17,15 +16,16 @@ export const useAPIStore = defineStore('api', () => {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// AUTH
|
|
||||||
const postLogin = async (credentials) => {
|
const postLogin = async (credentials) => {
|
||||||
const response = await axios.post(`${API_BASE_URL}/login`, credentials)
|
const response = await axios.post(`${API_BASE_URL}/login`, credentials)
|
||||||
|
|
||||||
|
if (!response.data.token) throw response
|
||||||
|
|
||||||
token.value = response.data.token
|
token.value = response.data.token
|
||||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||||
|
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
const postLogout = async () => {
|
const postLogout = async () => {
|
||||||
await axios.post(`${API_BASE_URL}/logout`)
|
await axios.post(`${API_BASE_URL}/logout`)
|
||||||
token.value = undefined
|
token.value = undefined
|
||||||
@@ -57,19 +57,11 @@ export const useAPIStore = defineStore('api', () => {
|
|||||||
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const initToken = (storedToken) => {
|
|
||||||
if (storedToken) {
|
|
||||||
token.value = storedToken
|
|
||||||
axios.defaults.headers.common['Authorization'] = `Bearer ${storedToken}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
postLogin,
|
postLogin,
|
||||||
postLogout,
|
postLogout,
|
||||||
getAuthUser,
|
getAuthUser,
|
||||||
getGames,
|
getGames,
|
||||||
gameQueryParameters,
|
gameQueryParameters,
|
||||||
initToken,
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
// src/stores/auth.js
|
|
||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { ref, computed } from 'vue'
|
import { ref, computed } from 'vue'
|
||||||
import { useAPIStore } from './api'
|
import { useAPIStore } from './api'
|
||||||
import axios from 'axios'
|
|
||||||
|
|
||||||
export const useAuthStore = defineStore('auth', () => {
|
export const useAuthStore = defineStore('auth', () => {
|
||||||
const apiStore = useAPIStore()
|
const apiStore = useAPIStore()
|
||||||
@@ -22,10 +20,8 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
token.value = jwtToken
|
token.value = jwtToken
|
||||||
if (jwtToken) {
|
if (jwtToken) {
|
||||||
localStorage.setItem('token', jwtToken)
|
localStorage.setItem('token', jwtToken)
|
||||||
axios.defaults.headers.common['Authorization'] = `Bearer ${jwtToken}`
|
|
||||||
} else {
|
} else {
|
||||||
localStorage.removeItem('token')
|
localStorage.removeItem('token')
|
||||||
delete axios.defaults.headers.common['Authorization']
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,58 +30,19 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const login = async (credentials) => {
|
const login = async (credentials) => {
|
||||||
try {
|
const loginResp = await apiStore.postLogin(credentials)
|
||||||
// postLogin already sets the token and axios headers, and returns the response
|
const userResp = await apiStore.getAuthUser()
|
||||||
const loginResponse = await apiStore.postLogin(credentials)
|
const jwtToken = loginResp.data.token
|
||||||
|
|
||||||
// Extract the token from the response
|
|
||||||
const jwtToken = loginResponse.data.token
|
|
||||||
|
|
||||||
// Store token in auth store (for localStorage)
|
|
||||||
setToken(jwtToken)
|
setToken(jwtToken)
|
||||||
|
currentUser.value = userResp.data
|
||||||
// Use the user data from login response (it's already there!)
|
return userResp.data
|
||||||
currentUser.value = loginResponse.data.user
|
|
||||||
|
|
||||||
return currentUser.value
|
|
||||||
} catch (error) {
|
|
||||||
// Clear everything on login failure
|
|
||||||
setToken(null)
|
|
||||||
currentUser.value = undefined
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const logout = async () => {
|
const logout = async () => {
|
||||||
try {
|
|
||||||
await apiStore.postLogout()
|
await apiStore.postLogout()
|
||||||
} catch (error) {
|
|
||||||
console.error('Logout API call failed:', error)
|
|
||||||
} finally {
|
|
||||||
currentUser.value = undefined
|
currentUser.value = undefined
|
||||||
setToken(null)
|
setToken(null)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize auth from localStorage on app start
|
|
||||||
const initAuth = async () => {
|
|
||||||
if (token.value) {
|
|
||||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
|
||||||
apiStore.initToken(token.value)
|
|
||||||
|
|
||||||
// Try to fetch current user if we don't have it
|
|
||||||
if (!currentUser.value) {
|
|
||||||
try {
|
|
||||||
const userResponse = await apiStore.getAuthUser()
|
|
||||||
currentUser.value = userResponse.data
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to restore user session:', error)
|
|
||||||
// Clear invalid token
|
|
||||||
setToken(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
currentUser,
|
currentUser,
|
||||||
@@ -96,6 +53,5 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
getToken,
|
getToken,
|
||||||
login,
|
login,
|
||||||
logout,
|
logout,
|
||||||
initAuth,
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -5,15 +5,20 @@ export const useSocketStore = defineStore('socket', () => {
|
|||||||
const socket = inject('socket')
|
const socket = inject('socket')
|
||||||
|
|
||||||
const handleConnection = () => {
|
const handleConnection = () => {
|
||||||
|
try {
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
console.log(`[Socket] Connected -- ${socket.id}`)
|
console.log(`[Socket] Connected -- ${socket.id}`)
|
||||||
})
|
})
|
||||||
socket.on('disconnect', () => {
|
socket.on('disconnect', () => {
|
||||||
console.log(`[Socket] Disconnected -- ${socket.id}`)
|
console.log(`[Socket] Disconnected -- ${socket.id}`)
|
||||||
})
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Socket] Connection error:', error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
handleConnection,
|
handleConnection,
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user