Merge remote-tracking branch 'origin/develop' into feature/home-page
This commit is contained in:
@@ -12,17 +12,25 @@ 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));
|
||||
}
|
||||
@@ -30,42 +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();
|
||||
|
||||
$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();
|
||||
$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();
|
||||
$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);
|
||||
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)
|
||||
@@ -73,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);
|
||||
|
||||
+20
-24
@@ -2,37 +2,33 @@
|
||||
|
||||
use App\Http\Controllers\AuthController;
|
||||
use App\Http\Controllers\GameController;
|
||||
use App\Http\Controllers\UserController;
|
||||
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::middleware('auth:sanctum')->group(function () {
|
||||
Route::get('matches', [MatchController::class, 'index']);
|
||||
Route::post('matches', [MatchController::class, 'store']);
|
||||
Route::get('matches/{match}', [MatchController::class, 'show']);
|
||||
Route::post('matches/{match}/join', [MatchController::class, 'join']);
|
||||
Route::put('matches/{match}', [MatchController::class, 'update']);
|
||||
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']);
|
||||
});
|
||||
});
|
||||
@@ -42,12 +42,13 @@ const logout = () => {
|
||||
success: () => {
|
||||
return 'Logout Sucessfull '
|
||||
},
|
||||
error: (data) => `[API] Error saving game - ${data?.response?.data?.message}`,
|
||||
error: (data) => `[API] Error - ${data?.response?.data?.message}`,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
onMounted(async () => {
|
||||
await authStore.restoreSession()
|
||||
socketStore.handleConnection()
|
||||
})
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
NavigationMenuList,
|
||||
NavigationMenuTrigger,
|
||||
} from '@/components/ui/navigation-menu'
|
||||
import router from '@/router';
|
||||
|
||||
|
||||
const emits = defineEmits(['logout'])
|
||||
@@ -46,5 +47,6 @@ const { userLoggedIn } = defineProps(['userLoggedIn'])
|
||||
|
||||
const logoutClickHandler = () => {
|
||||
emits('logout')
|
||||
router.push('/login')
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -27,6 +27,14 @@
|
||||
<Input id="password" v-model="formData.password" type="password" autocomplete="current-password"
|
||||
required placeholder="••••••••" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center pb-2">
|
||||
<input id="remember-me" type="checkbox" v-model="formData.rememberMe"
|
||||
class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded ml-1" />
|
||||
<label for="remember-me" class="ml-2 block text-sm text-gray-900">
|
||||
Remember me
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -59,7 +67,8 @@ const router = useRouter()
|
||||
|
||||
const formData = ref({
|
||||
email: 'pa@mail.pt',
|
||||
password: '123'
|
||||
password: '123',
|
||||
rememberMe: false
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { inject, ref } from 'vue'
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
export const useAPIStore = defineStore('api', () => {
|
||||
const API_BASE_URL = inject('apiBaseURL')
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const token = ref()
|
||||
const gameQueryParameters = ref({
|
||||
@@ -16,6 +18,24 @@ export const useAPIStore = defineStore('api', () => {
|
||||
},
|
||||
})
|
||||
|
||||
const resetExpiryOnSuccess = (response) => {
|
||||
if (authStore.isLoggedIn && !authStore.isTokenAlmostExpired()) {
|
||||
authStore.resetTokenExpiry()
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
axios.interceptors.response.use(resetExpiryOnSuccess)
|
||||
|
||||
const initializeAxiosHeaders = () => {
|
||||
const storedToken = localStorage.getItem('token')
|
||||
if (storedToken) {
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${storedToken}`
|
||||
}
|
||||
}
|
||||
|
||||
initializeAxiosHeaders()
|
||||
|
||||
const postLogin = async (credentials) => {
|
||||
const response = await axios.post(`${API_BASE_URL}/login`, credentials)
|
||||
|
||||
@@ -25,7 +45,8 @@ export const useAPIStore = defineStore('api', () => {
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
const postLogout = async () => {
|
||||
await axios.post(`${API_BASE_URL}/logout`)
|
||||
token.value = undefined
|
||||
|
||||
@@ -3,25 +3,45 @@ import { ref, computed } from 'vue'
|
||||
import { useAPIStore } from './api'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const apiStore = useAPIStore()
|
||||
|
||||
const DEFAULT_TIMEOUT = 5 * 60 * 1000
|
||||
const REMEMBER_ME_TIMEOUT = 365 * 24 * 60 * 60 * 1000
|
||||
|
||||
const currentUser = ref(undefined)
|
||||
const token = ref(localStorage.getItem('token') || null)
|
||||
const tokenExpiry = ref(localStorage.getItem('tokenExpiry') ? parseInt(localStorage.getItem('tokenExpiry')) : null)
|
||||
const rememberMe = ref(false)
|
||||
|
||||
const isLoggedIn = computed(() => {
|
||||
return currentUser.value !== undefined && token.value !== null
|
||||
return currentUser.value !== undefined && token.value !== null && !isTokenAlmostExpired()
|
||||
})
|
||||
|
||||
const currentUserID = computed(() => {
|
||||
return currentUser.value?.id
|
||||
})
|
||||
|
||||
const setToken = (jwtToken) => {
|
||||
const isTokenAlmostExpired = () => {
|
||||
if (!tokenExpiry.value) return false;
|
||||
return Date.now() > (tokenExpiry.value - 60 * 1000);
|
||||
};
|
||||
|
||||
const resetTokenExpiry = () => {
|
||||
const timeout = rememberMe.value ? REMEMBER_ME_TIMEOUT : DEFAULT_TIMEOUT
|
||||
tokenExpiry.value = Date.now() + timeout
|
||||
localStorage.setItem('tokenExpiry', tokenExpiry.value.toString())
|
||||
}
|
||||
|
||||
const setToken = (jwtToken, shouldRememberMe = false) => {
|
||||
token.value = jwtToken
|
||||
rememberMe.value = shouldRememberMe
|
||||
|
||||
if (jwtToken) {
|
||||
localStorage.setItem('token', jwtToken)
|
||||
resetTokenExpiry()
|
||||
} else {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('tokenExpiry')
|
||||
tokenExpiry.value = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,18 +50,70 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
|
||||
const login = async (credentials) => {
|
||||
const apiStore = useAPIStore()
|
||||
const loginResp = await apiStore.postLogin(credentials)
|
||||
const userResp = await apiStore.getAuthUser()
|
||||
|
||||
const jwtToken = loginResp.data.token
|
||||
setToken(jwtToken)
|
||||
setToken(jwtToken, credentials.rememberMe)
|
||||
currentUser.value = userResp.data
|
||||
|
||||
localStorage.setItem('currentUser', JSON.stringify(userResp.data))
|
||||
return userResp.data
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
const apiStore = useAPIStore()
|
||||
await apiStore.postLogout()
|
||||
currentUser.value = undefined
|
||||
setToken(null)
|
||||
localStorage.removeItem('currentUser')
|
||||
}
|
||||
|
||||
const checkTokenExpiry = () => {
|
||||
if (isTokenAlmostExpired()) {
|
||||
logout()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const restoreSession = async () => {
|
||||
const storedToken = localStorage.getItem('token')
|
||||
const storedUser = localStorage.getItem('currentUser')
|
||||
const storedTokenExpiry = localStorage.getItem('tokenExpiry')
|
||||
|
||||
if (!storedToken || !storedTokenExpiry) {
|
||||
return false
|
||||
}
|
||||
if (Date.now() > parseInt(storedTokenExpiry)) {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('tokenExpiry')
|
||||
localStorage.removeItem('currentUser')
|
||||
return false
|
||||
}
|
||||
|
||||
token.value = storedToken
|
||||
tokenExpiry.value = parseInt(storedTokenExpiry)
|
||||
|
||||
if (storedUser) {
|
||||
try {
|
||||
currentUser.value = JSON.parse(storedUser)
|
||||
} catch (e) {
|
||||
// If stored user data is corrupted, fetch fresh data from API
|
||||
try {
|
||||
const userResp = await apiStore.getAuthUser()
|
||||
currentUser.value = userResp.data
|
||||
localStorage.setItem('currentUser', JSON.stringify(userResp.data))
|
||||
} catch (apiError) {
|
||||
// API call failed, likely token is invalid
|
||||
logout()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -49,9 +121,14 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
isLoggedIn,
|
||||
currentUserID,
|
||||
token,
|
||||
rememberMe,
|
||||
setToken,
|
||||
getToken,
|
||||
login,
|
||||
logout,
|
||||
resetTokenExpiry,
|
||||
isTokenAlmostExpired,
|
||||
checkTokenExpiry,
|
||||
restoreSession,
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user