Version 1.0 #102
@@ -101,3 +101,4 @@ Desktop.ini
|
||||
# /path/to/some/file
|
||||
|
||||
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 App\Http\Requests\StoreGameRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\MatchGame;
|
||||
|
||||
class GameController extends Controller
|
||||
{
|
||||
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'])) {
|
||||
$query->where('type', $request->type);
|
||||
if ($request->has("type") && in_array($request->type, ["3", "9"])) {
|
||||
$query->where("type", $request->type);
|
||||
}
|
||||
|
||||
if ($request->has('status') && in_array($request->status, ['Pending', 'Playing', 'Ended', 'Interrupted'])) {
|
||||
$query->where('status', $request->status);
|
||||
if (
|
||||
$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));
|
||||
}
|
||||
@@ -29,39 +38,56 @@ class GameController extends Controller
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'type' => 'required|in:3,9',
|
||||
"type" => "required|in:3,9",
|
||||
]);
|
||||
|
||||
$user = Auth::user();
|
||||
|
||||
$activeGame = Game::where(function ($query) use ($user) {
|
||||
$query->where('player1_user_id', $user->id)
|
||||
->orWhere('player2_user_id', $user->id);
|
||||
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||
$q->where("player1_user_id", $user->id)->orWhere(
|
||||
"player2_user_id",
|
||||
$user->id,
|
||||
);
|
||||
})
|
||||
->whereIn('status', ['Pending', 'Playing'])
|
||||
->whereIn("status", ["Pending", "Playing"])
|
||||
->exists();
|
||||
|
||||
if ($activeGame) {
|
||||
return response()->json(['message' => 'You already have an active game.'], 400);
|
||||
$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,
|
||||
);
|
||||
}
|
||||
|
||||
$game = Game::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,
|
||||
'began_at' => now(),
|
||||
'player1_points' => 0,
|
||||
'player2_points' => 0,
|
||||
'custom' => null
|
||||
"type" => $validated["type"],
|
||||
"status" => "Pending",
|
||||
"player1_user_id" => $user->id,
|
||||
"player2_user_id" => null,
|
||||
"winner_user_id" => null,
|
||||
"loser_user_id" => null,
|
||||
"began_at" => now(),
|
||||
"player1_points" => 0,
|
||||
"player2_points" => 0,
|
||||
"custom" => null,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Multiplayer game room created',
|
||||
'game' => $game
|
||||
], 201);
|
||||
return response()->json(
|
||||
[
|
||||
"message" => "Multiplayer game room created",
|
||||
"game" => $game,
|
||||
],
|
||||
201,
|
||||
);
|
||||
}
|
||||
|
||||
public function join(Game $game)
|
||||
@@ -69,62 +95,75 @@ class GameController extends Controller
|
||||
$user = Auth::user();
|
||||
|
||||
if ($game->player1_user_id == $user->id) {
|
||||
return response()->json([
|
||||
'message' => 'Waiting for opponent...',
|
||||
'game' => $game
|
||||
], 200);
|
||||
return response()->json(
|
||||
[
|
||||
"message" => "Waiting for opponent...",
|
||||
"game" => $game,
|
||||
],
|
||||
200,
|
||||
);
|
||||
}
|
||||
|
||||
if ($game->status !== 'Pending') {
|
||||
return response()->json(['message' => 'Game is full or already started'], 400);
|
||||
if ($game->status !== "Pending") {
|
||||
return response()->json(
|
||||
["message" => "Game is full or already started"],
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
$activeGame = Game::where(function ($query) use ($user) {
|
||||
$query->where('player1_user_id', $user->id)
|
||||
->orWhere('player2_user_id', $user->id);
|
||||
$query
|
||||
->where("player1_user_id", $user->id)
|
||||
->orWhere("player2_user_id", $user->id);
|
||||
})
|
||||
->whereIn('status', ['Pending', 'Playing'])
|
||||
->whereIn("status", ["Pending", "Playing"])
|
||||
->exists();
|
||||
|
||||
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([
|
||||
'status' => 'Playing',
|
||||
'player2_user_id' => $user->id,
|
||||
"status" => "Playing",
|
||||
"player2_user_id" => $user->id,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Joined successfully! Game starts now.',
|
||||
'game' => $game
|
||||
], 200);
|
||||
return response()->json(
|
||||
[
|
||||
"message" => "Joined successfully! Game starts now.",
|
||||
"game" => $game,
|
||||
],
|
||||
200,
|
||||
);
|
||||
}
|
||||
|
||||
public function show(Game $game)
|
||||
{
|
||||
$game->load(['player1', 'player2', 'winner']);
|
||||
$game->load(["player1", "player2", "winner"]);
|
||||
return response()->json($game);
|
||||
}
|
||||
|
||||
public function update(Request $request, Game $game)
|
||||
{
|
||||
if ($game->status == 'Ended') {
|
||||
return response()->json(['message' => 'Game already ended'], 400);
|
||||
if ($game->status == "Ended") {
|
||||
return response()->json(["message" => "Game already ended"], 400);
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'status' => 'in:Playing,Ended,Interrupted',
|
||||
'winner_user_id' => 'exists:users,id',
|
||||
'loser_user_id' => 'exists:users,id',
|
||||
'player1_points' => 'integer',
|
||||
'player2_points' => 'integer',
|
||||
'is_draw' => 'boolean',
|
||||
'total_time' => 'numeric'
|
||||
"status" => "in:Playing,Ended,Interrupted",
|
||||
"winner_user_id" => "exists:users,id",
|
||||
"loser_user_id" => "exists:users,id",
|
||||
"player1_points" => "integer",
|
||||
"player2_points" => "integer",
|
||||
"is_draw" => "boolean",
|
||||
"total_time" => "numeric",
|
||||
]);
|
||||
|
||||
if (isset($data['status']) && $data['status'] === 'Ended') {
|
||||
$data['ended_at'] = now();
|
||||
if (isset($data["status"]) && $data["status"] === "Ended") {
|
||||
$data["ended_at"] = now();
|
||||
}
|
||||
|
||||
$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\GameController;
|
||||
use App\Http\Controllers\MatchController;
|
||||
use App\Http\Controllers\UserController;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
|
||||
# Authentication Routes
|
||||
// Authentication Routes
|
||||
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']);
|
||||
|
||||
# Game Routes - Protected
|
||||
Route::middleware('auth:sanctum')->group(function () {
|
||||
Route::apiResource('games', GameController::class);
|
||||
Route::post('games', [GameController::class, 'store']);
|
||||
Route::post('/games/{game}/resign', [GameController::class, 'resign']);
|
||||
Route::get('/users/{user}/matches', [UserController::class, 'getMatches']);
|
||||
Route::post('games/{game}/join', [GameController::class, 'join']);
|
||||
Route::post('logout', [AuthController::class, 'logout']);
|
||||
|
||||
Route::prefix('users')->group(function () {
|
||||
Route::get('/me', function (Request $request) {
|
||||
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
|
||||
</label>
|
||||
<Input id="email" v-model="formData.email" type="email" autocomplete="email" required
|
||||
placeholder="[email protected]" :disabled="isLoading" />
|
||||
placeholder="[email protected]" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Password
|
||||
</label>
|
||||
<Input id="password" v-model="formData.password" type="password" autocomplete="current-password" required
|
||||
placeholder="••••••••" :disabled="isLoading" />
|
||||
<Input id="password" v-model="formData.password" type="password" autocomplete="current-password"
|
||||
required placeholder="••••••••" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
<Button type="submit" class="w-full" :disabled="isLoading">
|
||||
{{ isLoading ? 'Signing in...' : 'Sign in' }}
|
||||
</Button>
|
||||
<Button type="submit" class="w-full"> Sign in </Button>
|
||||
</div>
|
||||
|
||||
<div class="text-center text-sm">
|
||||
@@ -50,6 +49,7 @@
|
||||
import { ref } from 'vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { toast } from 'vue-sonner'
|
||||
@@ -62,23 +62,17 @@ const formData = ref({
|
||||
password: '123'
|
||||
})
|
||||
|
||||
const isLoading = ref(false)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
isLoading.value = true
|
||||
|
||||
try {
|
||||
const user = await authStore.login(formData.value)
|
||||
|
||||
toast.success(`Login Successful - Welcome ${user?.name}!`)
|
||||
|
||||
setTimeout(() => {
|
||||
const promise = authStore.login(formData.value)
|
||||
toast.promise(promise, {
|
||||
loading: 'Calling API',
|
||||
success: (user) => {
|
||||
router.push('/')
|
||||
}, 500)
|
||||
} catch (error) {
|
||||
toast.error(`Login Failed - ${error?.response?.data?.message || error.message}`)
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
return `Login Successful - ${user.name}`
|
||||
},
|
||||
error: (error) =>
|
||||
error.response?.data?.message
|
||||
})
|
||||
}
|
||||
</script>
|
||||
@@ -1,4 +1,3 @@
|
||||
// src/stores/api.js
|
||||
import { defineStore } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { inject, ref } from 'vue'
|
||||
@@ -17,15 +16,16 @@ export const useAPIStore = defineStore('api', () => {
|
||||
},
|
||||
})
|
||||
|
||||
// AUTH
|
||||
const postLogin = async (credentials) => {
|
||||
const response = await axios.post(`${API_BASE_URL}/login`, credentials)
|
||||
|
||||
if (!response.data.token) throw response
|
||||
|
||||
token.value = response.data.token
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
const postLogout = async () => {
|
||||
await axios.post(`${API_BASE_URL}/logout`)
|
||||
token.value = undefined
|
||||
@@ -57,19 +57,11 @@ export const useAPIStore = defineStore('api', () => {
|
||||
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
||||
}
|
||||
|
||||
const initToken = (storedToken) => {
|
||||
if (storedToken) {
|
||||
token.value = storedToken
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${storedToken}`
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
postLogin,
|
||||
postLogout,
|
||||
getAuthUser,
|
||||
getGames,
|
||||
gameQueryParameters,
|
||||
initToken,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// src/stores/auth.js
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { useAPIStore } from './api'
|
||||
import axios from 'axios'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const apiStore = useAPIStore()
|
||||
@@ -22,10 +20,8 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
token.value = jwtToken
|
||||
if (jwtToken) {
|
||||
localStorage.setItem('token', jwtToken)
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${jwtToken}`
|
||||
} else {
|
||||
localStorage.removeItem('token')
|
||||
delete axios.defaults.headers.common['Authorization']
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,58 +30,19 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
|
||||
const login = async (credentials) => {
|
||||
try {
|
||||
// postLogin already sets the token and axios headers, and returns the response
|
||||
const loginResponse = await apiStore.postLogin(credentials)
|
||||
|
||||
// Extract the token from the response
|
||||
const jwtToken = loginResponse.data.token
|
||||
|
||||
// Store token in auth store (for localStorage)
|
||||
const loginResp = await apiStore.postLogin(credentials)
|
||||
const userResp = await apiStore.getAuthUser()
|
||||
const jwtToken = loginResp.data.token
|
||||
setToken(jwtToken)
|
||||
|
||||
// Use the user data from login response (it's already there!)
|
||||
currentUser.value = loginResponse.data.user
|
||||
|
||||
return currentUser.value
|
||||
} catch (error) {
|
||||
// Clear everything on login failure
|
||||
setToken(null)
|
||||
currentUser.value = undefined
|
||||
throw error
|
||||
}
|
||||
currentUser.value = userResp.data
|
||||
return userResp.data
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await apiStore.postLogout()
|
||||
} catch (error) {
|
||||
console.error('Logout API call failed:', error)
|
||||
} finally {
|
||||
currentUser.value = undefined
|
||||
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 {
|
||||
currentUser,
|
||||
@@ -96,6 +53,5 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
getToken,
|
||||
login,
|
||||
logout,
|
||||
initAuth,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -5,15 +5,20 @@ export const useSocketStore = defineStore('socket', () => {
|
||||
const socket = inject('socket')
|
||||
|
||||
const handleConnection = () => {
|
||||
try {
|
||||
socket.on('connect', () => {
|
||||
console.log(`[Socket] Connected -- ${socket.id}`)
|
||||
})
|
||||
socket.on('disconnect', () => {
|
||||
console.log(`[Socket] Disconnected -- ${socket.id}`)
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[Socket] Connection error:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handleConnection,
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user