Compare commits

...
Author SHA1 Message Date
FernandoJVideira 026e7af6a5 feat: api admin users endpoints 2025-12-24 15:03:37 +00:00
FernandoJVideira 7cfe9d2746 Merge pull request 'feature/account-deletion' (#73) from feature/account-deletion into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/73
Reviewed-by: KZix <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-24 10:52:01 +00:00
AfonsoCMSousa 381f30a0f5 Merge branch 'develop' into feature/account-deletion 2025-12-23 21:52:05 +00:00
AfonsoCMSousa 723d5270e4 Merge pull request 'feature/profile-page' (#71) from feature/profile-page into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/71
Reviewed-by: KZix <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Edd <[email protected]>
2025-12-23 21:49:20 +00:00
AfonsoCMSousa f4aaf9a787 Merge branch 'develop' into feature/profile-page 2025-12-23 21:45:33 +00:00
AfonsoCMSousa 30705fd194 SyntaxSquad/DADProject#10 feat: Account deletion (soft delete) 2025-12-23 21:39:38 +00:00
KZix 44c0ac599e Merge pull request 'Fix auth' (#72) from na/fix-auth into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/72
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: KZix <[email protected]>
2025-12-23 20:06:43 +00:00
Edd 28466ecbbd Merge branch 'develop' into na/fix-auth 2025-12-23 20:05:44 +00:00
Edd e47a453588 remove comment 2025-12-23 20:05:17 +00:00
Edd 0320230279 fix auth 2025-12-23 20:03:59 +00:00
AfonsoCMSousa c34d74db46 SyntaxSquad/DADProject#9 fixforthefix: Remove anoying gray bg 2025-12-23 18:53:11 +00:00
AfonsoCMSousa 18cef8da4b SyntaxSquad/DADProject#9 fix: Used Tailwind Classes and Exported inline CSS into "UserPage.css" 2025-12-23 18:42:09 +00:00
AfonsoCMSousa b82b4d5b59 SyntaxSquad/DADProject#9 feat: Added profile change and name/password changes. 2025-12-23 18:21:04 +00:00
AfonsoCMSousa 29fc78c9f5 Merge remote-tracking branch 'origin/develop' into feature/profile-page 2025-12-23 17:35:49 +00:00
AfonsoCMSousa d903f96d57 SyntaxSquad/DADProject#9 Actuall User View 2025-12-23 17:24:25 +00:00
Edd 7d1b769bdb Merge pull request 'Fixed Endpoint file and GameController' (#70) from fix/api-endpoints into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/70
Reviewed-by: KZix <[email protected]>
Reviewed-by: Edd <[email protected]>
2025-12-23 14:58:27 +00:00
Edd d0f9a03b93 Merge branch 'develop' into fix/api-endpoints 2025-12-23 12:38:51 +00:00
FernandoJVideira 10508cc0b1 fix: GameControler create game fixed 2025-12-23 12:36:56 +00:00
FernandoJVideira c78c5d2784 fix: api.php cleanup 2025-12-23 12:34:19 +00:00
FernandoJVideira 289e8df604 Merge pull request 'Implement login page with email/password authentication' (#69) from feature/login-page into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/69
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-22 17:08:37 +00:00
Edd 8e179200a5 Merge branch 'develop' into feature/login-page 2025-12-21 14:52:32 +00:00
Edd c03d49e7e4 removed vscode preferences 2025-12-21 02:37:46 +00:00
Edd 2734e25cce feature implement login final changes 2025-12-20 22:26:22 +00:00
Edd a566387998 feature implement login part2 2025-12-20 21:59:33 +00:00
AfonsoCMSousa d1dd2c00f6 SyntaxSquad/DADProject#9 feat: User info dysplayed in /users/ 2025-12-18 21:04:49 +00:00
FernandoJVideira 8a6e0d0255 Merge pull request 'Added routes, endpoints to get all matches, get a specific match, create a match, join a match, and update the match' (#68) from feature/matches-api-endpoints into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/68
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-18 20:36:49 +00:00
KZix b485e19c9d Added routes, endpoints to get all matches, get a specific match, create a match, join a match, and update the match 2025-12-18 20:29:10 +00:00
AfonsoCMSousa 94fdbd568c Merge branch 'develop' into feature/profile-page 2025-12-18 19:15:49 +00:00
Edd ae6a0b4706 Merge branch 'develop' into feature/login-page 2025-12-18 19:11:47 +00:00
Edd 5270e3c093 Merge pull request 'feature/game-endpoints' (#62) from feature/game-endpoints into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/62
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Edd <[email protected]>
2025-12-14 00:56:05 +00:00
KZix 5473a4cc69 removed crap i did, sorry frontends 2025-12-14 00:28:58 +00:00
KZix cf8f93d984 Added endpoits to create, join and update the game state, playability should work now 2025-12-14 00:26:41 +00:00
KZix 7686aff546 Added initial game logic 2025-12-12 00:05:37 +00:00
AfonsoCMSousa a0ad35bb08 Merge branch 'feature/login-page' into feature/profile-page 2025-12-11 21:18:31 +00:00
KZix af41990807 Merge pull request 'Added the register endpoint' (#61) from feature/register-api-endpoint into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/61
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-11 21:18:05 +00:00
KZix 20f53197ec Merge branch 'develop' into feature/register-api-endpoint 2025-12-11 21:17:58 +00:00
KZix 7c6d8ed446 Merge pull request 'feat: websocket init' (#60) from feature/websocket-init into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/60
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: KZix <[email protected]>
2025-12-11 21:17:23 +00:00
AfonsoCMSousa 1d5100fbdf feat:initial commit 2025-12-11 21:14:54 +00:00
Edd 511e645d7e feature implement login part 1 2025-12-11 21:14:25 +00:00
KZix daa72ce4c6 Added the register endpoint 2025-12-11 21:13:56 +00:00
AfonsoCMSousa 117f007b83 Merge branch 'develop' into feature/websocket-init 2025-12-11 21:05:10 +00:00
FernandoJVideira 69705ce61c feat: websocket init 2025-12-11 21:02:02 +00:00
FernandoJVideira 8472263f91 Merge pull request 'feature/database-and-auth-api' (#59) from feature/database-and-auth-api into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/59
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-11 20:47:09 +00:00
KZix d7a6862dcb Added necessary stuff for authentication 2025-12-11 20:42:30 +00:00
FernandoJVideira a335e713ee Merge pull request 'Rebase Develop' (#58) from master into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/58
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: KZix <[email protected]>
Reviewed-by: Edd <[email protected]>
2025-12-04 21:01:39 +00:00
FernandoJVideira 1e5792567f Merge pull request 'Added base project' (#57) from na/change-project-base into master
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/57
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Edd <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2025-12-04 20:56:11 +00:00
46 changed files with 2337 additions and 606 deletions
+3
View File
@@ -99,3 +99,6 @@ Desktop.ini
# If you have any local secrets or files not to track, add them here: # If you have any local secrets or files not to track, add them here:
# /path/to/some/file # /path/to/some/file
package-lock.json
.vscode
@@ -5,6 +5,8 @@ namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use App\Models\User;
use App\Http\Requests\RegisterRequest;
class AuthController extends Controller class AuthController extends Controller
{ {
@@ -38,4 +40,30 @@ class AuthController extends Controller
'message' => 'Logged out successfully', 'message' => 'Logged out successfully',
]); ]);
} }
public function register(RegisterRequest $request)
{
if (User::where('email', $request->email)->exists()) {
return response()->json(['message' => 'Email already registered'], 409);
}
$user = User::create([
'email' => $request->email,
'nickname' => $request->nickname,
'name' => $request->name,
'password' => bcrypt($request->password),
'photo_avatar_filename' => $request->photo,
'type' => 'P',
'blocked' => false,
'coins_balance' => 10,
]);
$token = $user->createToken('auth-token')->plainTextToken;
return response()->json([
'message' => 'User registered successfully',
'user' => $user,
'token' => $token,
], 201);
}
} }
+5 -2
View File
@@ -2,7 +2,10 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
abstract class Controller use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Routing\Controller as BaseController;
abstract class Controller extends BaseController
{ {
// use AuthorizesRequests;
} }
+140 -54
View File
@@ -4,84 +4,170 @@ namespace App\Http\Controllers;
use App\Models\Game; use App\Models\Game;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Requests\StoreGameRequest;
use Illuminate\Support\Facades\Auth;
use App\Models\MatchGame;
class GameController extends Controller class GameController extends Controller
{ {
/**
* Display a listing of the resource.
*/
public function index(Request $request) public function index(Request $request)
{ {
$query = Game::query()->with(['winner']); $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);
} }
// Sorting $query->orderBy("began_at", "desc");
$sortField = $request->input('sort_by', 'began_at');
$sortDirection = $request->input('sort_direction', 'desc');
$allowedSortFields = [ return response()->json($query->paginate(15));
'began_at',
'ended_at',
'total_time',
'type',
'status'
];
if (in_array($sortField, $allowedSortFields)) {
$query->orderBy($sortField, $sortDirection === 'asc' ? 'asc' : 'desc');
} }
// Pagination
$perPage = $request->input('per_page', 15);
$games = $query->paginate($perPage);
return response()->json([
'data' => $games->items(),
'meta' => [
'current_page' => $games->currentPage(),
'last_page' => $games->lastPage(),
'per_page' => $games->perPage(),
'total' => $games->total()
]
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request) public function store(Request $request)
{ {
// $validated = $request->validate([
"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();
$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" => 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,
);
}
public function join(Game $game)
{
$user = Auth::user();
if ($game->player1_user_id == $user->id) {
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,
);
}
$activeGame = Game::where(function ($query) use ($user) {
$query
->where("player1_user_id", $user->id)
->orWhere("player2_user_id", $user->id);
})
->whereIn("status", ["Pending", "Playing"])
->exists();
if ($activeGame) {
return response()->json(
["message" => "You are already in another active game."],
400,
);
}
$game->update([
"status" => "Playing",
"player2_user_id" => $user->id,
]);
return response()->json(
[
"message" => "Joined successfully! Game starts now.",
"game" => $game,
],
200,
);
} }
/**
* Display the specified resource.
*/
public function show(Game $game) public function show(Game $game)
{ {
// $game->load(["player1", "player2", "winner"]);
return response()->json($game);
} }
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Game $game) public function update(Request $request, Game $game)
{ {
// if ($game->status == "Ended") {
return response()->json(["message" => "Game already ended"], 400);
} }
/** $data = $request->validate([
* Remove the specified resource from storage. "status" => "in:Playing,Ended,Interrupted",
*/ "winner_user_id" => "exists:users,id",
public function destroy(Game $game) "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();
}
$game->update($data);
return response()->json($game);
} }
} }
@@ -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,100 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function show(Request $request)
{
$user = $request->user();
return response()->json($user);
}
public function update(Request $request)
{
$request->validate([
"name" => "required|string|max:255",
"nickname" =>
"required|string|max:255|unique:users,nickname," .
$request->user()->id,
]);
$user = $request->user();
$user->name = $request->name;
$user->nickname = $request->nickname;
$user->save();
return response()->json($user);
}
public function destroy(User $user)
{
$currentUser = Auth::user();
if ($currentUser->id !== $user->id && $currentUser->type !== "A") {
return response()->json(["message" => "Unauthorized"], 403);
}
$user->delete();
return response()->json(["message" => "User deleted successfully"]);
}
public function updatePassword(Request $request)
{
$request->validate([
"current_password" => "required",
"new_password" => "required|min:8|confirmed",
]);
$user = $request->user();
if (!\Hash::check($request->current_password, $user->password)) {
return response()->json(
[
"message" => "Current password is incorrect",
],
422,
);
}
$user->password = \Hash::make($request->new_password);
$user->save();
return response()->json([
"message" => "Password changed successfully",
]);
}
public function updateAvatar(Request $request)
{
$request->validate([
"avatar" => "required|image|mimes:jpeg,png,jpg,gif|max:2048",
]);
$user = $request->user();
if ($user->photo_avatar_filename) {
\Storage::disk("public")->delete(
"photos_avatars/" . $user->photo_avatar_filename,
);
}
$file = $request->file("avatar");
$filename =
str_pad($user->id, 5, "0", STR_PAD_LEFT) .
"_" .
\Str::random(10) .
"." .
$file->extension();
$file->storeAs("photos_avatars", $filename, "public");
$user->photo_avatar_filename = $filename;
$user->save();
return response()->json($user);
}
}
+187
View File
@@ -0,0 +1,187 @@
<?php
namespace App\Http\Controllers;
use App\Models\Game;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
/**
* GET /api/users
* Lista todos os utilizadores (Apenas para Admins)
*/
public function index(Request $request)
{
$query = User::query();
// Filtros úteis para o Backoffice
if ($request->has('type')) {
$query->where('type', $request->type);
}
if ($request->has('search')) {
$query->where(function ($q) use ($request) {
$q->where('name', 'like', '%'.$request->search.'%')
->orWhere('email', 'like', '%'.$request->search.'%')
->orWhere('nickname', 'like', '%'.$request->search.'%');
});
}
return response()->json($query->paginate(15));
}
/**
* POST /api/users
* Registar um novo utilizador (Admin only)
*/
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'nickname' => 'required|string|max:20|unique:users,nickname',
'email' => 'required|email|unique:users,email',
'password' => 'required|string|min:3',
'type' => 'required|in:A,U',
]);
$validated['password'] = Hash::make($validated['password']);
$user = User::create($validated);
return response()->json($user, 201);
}
/**
* GET /api/users/me
* Retorna o perfil do utilizador autenticado atual.
* Usado pelo VueJS para saber quem está logado.
*/
public function me(Request $request)
{
return response()->json($request->user());
}
/**
* GET /api/users/{user}
* Mostra um perfil específico.
*/
public function show(User $user)
{
$currentUser = Auth::user();
if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
return response()->json([
'id' => $user->id,
'name' => $user->name,
'nickname' => $user->nickname,
'photo_avatar_filename' => $user->photo_avatar_filename,
'type' => $user->type,
]);
}
return response()->json($user);
}
/**
* PUT/PATCH /api/users/{user}
* Atualizar perfil (Nome, Nickname, Password, Foto)
*/
public function update(Request $request, User $user)
{
$currentUser = Auth::user();
if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
return response()->json(['message' => 'Unauthorized'], 403);
}
$validated = $request->validate([
'name' => 'sometimes|string|max:255',
'nickname' => [
'sometimes',
'string',
'max:20',
Rule::unique('users')->ignore($user->id),
],
'email' => [
'sometimes',
'email',
Rule::unique('users')->ignore($user->id),
],
'password' => 'sometimes|string|min:3',
'blocked' => 'sometimes|boolean',
]);
if (isset($validated['blocked']) && $currentUser->type !== 'A') {
return response()->json(
['message' => 'Only admins can block users'],
403,
);
}
// Lógica de Upload de Foto (Exemplo Básico)
// if ($request->hasFile('photo_avatar')) {
// $path = $request->file('photo_avatar')->store('avatars', 'public');
// $validated['photo_avatar_filename'] = basename($path);
// }
$user->update($validated);
return response()->json($user);
}
/**
* DELETE /api/users/{user}
* Apagar conta (Soft Delete)
*/
public function destroy(User $user)
{
$currentUser = Auth::user();
if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
return response()->json(['message' => 'Unauthorized'], 403);
}
if ($currentUser->id === $user->id && $currentUser->type === 'A') {
if ($user->type === 'A') {
return response()->json(
['message' => 'Admins cannot delete their own account'],
403,
);
}
}
$user->delete();
return response()->json(['message' => 'User deleted successfully']);
}
/**
* GET /api/users/{user}/matches
* Histórico de Jogos Multiplayer do Utilizador
*/
public function getMatches(Request $request, User $user)
{
$currentUser = Auth::user();
if ($currentUser->id !== $user->id && $currentUser->type !== 'A') {
return response()->json(['message' => 'Unauthorized'], 403);
}
$matches = Game::query()
->where(function ($q) use ($user) {
$q->where('player1_user_id', $user->id)->orWhere(
'player2_user_id',
$user->id,
);
})
->with(['winner', 'player1', 'player2'])
->orderBy('began_at', 'desc')
->paginate(10);
return response()->json($matches);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckUserType
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(
Request $request,
Closure $next,
string $type,
): Response {
$user = $request->user();
if (!$user || $user->type !== $type) {
return response()->json(
["message" => "Unauthorized. User type {$type} required."],
403,
);
}
return $next($request);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => 'required|email|unique:users,email',
'nickname' => 'required|string|max:255',
'name' => 'required|string|max:255',
'password' => 'required|string|min:3',
'photo' => 'nullable|string',
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class StoreGameRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
// Só utilizadores autenticados podem criar jogos
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
// Agora validamos diretamente '3' ou '9' para bater certo com a BD
'type' => 'required|in:3,9',
];
}
/**
* Mensagens personalizadas (Opcional)
*/
public function messages(): array
{
return [
'type.required' => 'You must choose a game type (Bisca de 3 or 9).',
'type.in' => 'Invalid game type. Choose 3 or 9.',
];
}
}
@@ -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',
];
}
}
+34
View File
@@ -3,11 +3,45 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use App\Http\Requests\StoreGameRequest;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Game extends Model class Game extends Model
{ {
use HasFactory;
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_points',
'player2_points',
'custom',
'is_draw',
'match_id'
];
public function winner() public function winner()
{ {
return $this->belongsTo(User::class, "winner_user_id"); return $this->belongsTo(User::class, "winner_user_id");
} }
public function player1()
{
return $this->belongsTo(User::class, 'player1_user_id');
}
public function player2()
{
return $this->belongsTo(User::class, 'player2_user_id');
}
} }
+58
View File
@@ -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');
}
}
+13 -11
View File
@@ -2,32 +2,35 @@
namespace App\Models; namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable class User extends Authenticatable
{ {
/** @use HasFactory<\Database\Factories\UserFactory> */ use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
use HasFactory, Notifiable, HasApiTokens;
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
* *
* @var list<string> * @var array<int, string>
*/ */
protected $fillable = [ protected $fillable = [
'name', 'name',
'email', 'email',
'password', 'password',
'nickname',
'type',
'photo_avatar_filename',
'coins_balance',
]; ];
/** /**
* The attributes that should be hidden for serialization. * The attributes that should be hidden for serialization.
* *
* @var list<string> * @var array<int, string>
*/ */
protected $hidden = [ protected $hidden = [
'password', 'password',
@@ -35,15 +38,14 @@ class User extends Authenticatable
]; ];
/** /**
* Get the attributes that should be cast. * The attributes that should be cast.
* *
* @return array<string, string> * @var array<string, string>
*/ */
protected function casts(): array protected $casts = [
{
return [
'email_verified_at' => 'datetime', 'email_verified_at' => 'datetime',
'password' => 'hashed', 'password' => 'hashed',
'blocked' => 'boolean',
'deleted_at' => 'datetime',
]; ];
} }
}
+9 -6
View File
@@ -6,14 +6,17 @@ use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__)) return Application::configure(basePath: dirname(__DIR__))
->withRouting( ->withRouting(
web: __DIR__.'/../routes/web.php', web: __DIR__ . "/../routes/web.php",
api: __DIR__.'/../routes/api.php', api: __DIR__ . "/../routes/api.php",
commands: __DIR__.'/../routes/console.php', commands: __DIR__ . "/../routes/console.php",
health: '/up', health: "/up",
) )
->withMiddleware(function (Middleware $middleware): void { ->withMiddleware(function (Middleware $middleware): void {
// $middleware->alias([
"user.type" => App\Http\Middleware\CheckUserType::class,
]);
}) })
->withExceptions(function (Exceptions $exceptions): void { ->withExceptions(function (Exceptions $exceptions): void {
// //
})->create(); })
->create();
+1 -1
View File
@@ -17,7 +17,7 @@
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2", "laravel/pail": "^1.2.2",
"laravel/pint": "^1.24", "laravel/pint": "^1.26",
"laravel/sail": "^1.48", "laravel/sail": "^1.48",
"mockery/mockery": "^1.6", "mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6", "nunomaduro/collision": "^8.6",
+15 -14
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "6ad8f0aa2267878e2374cd4ba4042946", "content-hash": "353b4e6bf34bd12906db0059bb3a9207",
"packages": [ "packages": [
{ {
"name": "brick/math", "name": "brick/math",
@@ -6575,16 +6575,16 @@
}, },
{ {
"name": "laravel/pint", "name": "laravel/pint",
"version": "v1.25.1", "version": "v1.26.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/laravel/pint.git", "url": "https://github.com/laravel/pint.git",
"reference": "5016e263f95d97670d71b9a987bd8996ade6d8d9" "reference": "69dcca060ecb15e4b564af63d1f642c81a241d6f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/laravel/pint/zipball/5016e263f95d97670d71b9a987bd8996ade6d8d9", "url": "https://api.github.com/repos/laravel/pint/zipball/69dcca060ecb15e4b564af63d1f642c81a241d6f",
"reference": "5016e263f95d97670d71b9a987bd8996ade6d8d9", "reference": "69dcca060ecb15e4b564af63d1f642c81a241d6f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -6595,13 +6595,13 @@
"php": "^8.2.0" "php": "^8.2.0"
}, },
"require-dev": { "require-dev": {
"friendsofphp/php-cs-fixer": "^3.87.2", "friendsofphp/php-cs-fixer": "^3.90.0",
"illuminate/view": "^11.46.0", "illuminate/view": "^12.40.1",
"larastan/larastan": "^3.7.1", "larastan/larastan": "^3.8.0",
"laravel-zero/framework": "^11.45.0", "laravel-zero/framework": "^12.0.4",
"mockery/mockery": "^1.6.12", "mockery/mockery": "^1.6.12",
"nunomaduro/termwind": "^2.3.1", "nunomaduro/termwind": "^2.3.3",
"pestphp/pest": "^2.36.0" "pestphp/pest": "^3.8.4"
}, },
"bin": [ "bin": [
"builds/pint" "builds/pint"
@@ -6627,6 +6627,7 @@
"description": "An opinionated code formatter for PHP.", "description": "An opinionated code formatter for PHP.",
"homepage": "https://laravel.com", "homepage": "https://laravel.com",
"keywords": [ "keywords": [
"dev",
"format", "format",
"formatter", "formatter",
"lint", "lint",
@@ -6637,7 +6638,7 @@
"issues": "https://github.com/laravel/pint/issues", "issues": "https://github.com/laravel/pint/issues",
"source": "https://github.com/laravel/pint" "source": "https://github.com/laravel/pint"
}, },
"time": "2025-09-19T02:57:12+00:00" "time": "2025-11-25T21:15:52+00:00"
}, },
{ {
"name": "laravel/sail", "name": "laravel/sail",
@@ -9380,12 +9381,12 @@
], ],
"aliases": [], "aliases": [],
"minimum-stability": "stable", "minimum-stability": "stable",
"stability-flags": {}, "stability-flags": [],
"prefer-stable": true, "prefer-stable": true,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {
"php": "^8.2" "php": "^8.2"
}, },
"platform-dev": {}, "platform-dev": [],
"plugin-api-version": "2.6.0" "plugin-api-version": "2.6.0"
} }
View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+1 -1
View File
@@ -6,7 +6,7 @@
"": { "": {
"devDependencies": { "devDependencies": {
"@tailwindcss/vite": "^4.0.0", "@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0", "axios": "^1.13.2",
"concurrently": "^9.0.1", "concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0", "laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0", "tailwindcss": "^4.0.0",
+1 -1
View File
@@ -8,7 +8,7 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/vite": "^4.0.0", "@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0", "axios": "^1.13.2",
"concurrently": "^9.0.1", "concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0", "laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0", "tailwindcss": "^4.0.0",
+72 -9
View File
@@ -2,18 +2,81 @@
use App\Http\Controllers\AuthController; use App\Http\Controllers\AuthController;
use App\Http\Controllers\GameController; use App\Http\Controllers\GameController;
use Illuminate\Http\Request; use App\Http\Controllers\MatchController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(function () {
// Public Routes
Route::post('/login', [AuthController::class, 'login']); Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::middleware('auth:sanctum')->group(function () { // Authenticated Routes
Route::get('/users/me', function (Request $request) { Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
return $request->user(); Route::post('/logout', [AuthController::class, 'logout']);
});
Route::post('logout', [AuthController::class, 'logout']); Route::prefix('users/me')->group(function () {
Route::get('/', [ProfileController::class, 'show']);
Route::put('/', [ProfileController::class, 'update']);
Route::delete('/', [ProfileController::class, 'destroy']);
Route::put('/password', [
ProfileController::class,
'updatePassword',
]);
Route::post('/avatar', [ProfileController::class, 'uploadAvatar']);
}); });
Route::apiResource('games', GameController::class); // User Resources
Route::prefix('/users')->group(function () {
Route::get('/{user}', [UserController::class, 'show']);
Route::get('/{user}/matches', [
UserController::class,
'getMatches',
]);
});
// Game Resources
Route::prefix('games')->group(function () {
Route::apiResource('/', GameController::class)->parameters([
'' => 'game',
]);
Route::post('/{game}/join', [GameController::class, 'join']);
Route::post('/{game}/resign', [GameController::class, 'resign']);
});
// Match Resources
Route::prefix('matches')->group(function () {
Route::apiResource('/', MatchController::class)->parameters([
'' => 'match',
]);
Route::post('/{match}/join', [
MatchController::class,
'join',
]);
});
// Admin Routes
Route::middleware('user.type:A')
->prefix('admin')
->group(function () {
Route::prefix('users')->group(function () {
Route::get('/', [UserController::class, 'index']);
Route::post('/', [UserController::class, 'store']);
Route::put('/{user}', [UserController::class, 'update']);
Route::delete('/{user}', [
UserController::class,
'destroy',
]);
Route::post('/{user}/block', [
UserController::class,
'block',
]);
Route::post('/{user}/unblock', [
UserController::class,
'unblock',
]);
});
});
});
});
+9
View File
@@ -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"
}
+20
View File
@@ -0,0 +1,20 @@
meta {
name: Get Users
type: http
seq: 1
}
get {
url: {{api_url}}/admin/users/
body: none
auth: inherit
}
headers {
Authorization: Bearer {{token}}
}
settings {
encodeUrl: true
timeout: 0
}
+8
View File
@@ -0,0 +1,8 @@
meta {
name: Admin
seq: 4
}
auth {
mode: inherit
}
+1 -1
View File
@@ -5,7 +5,7 @@ meta {
} }
post { post {
url: {{api_url}}/auth/login url: {{api_url}}/login
body: json body: json
auth: none auth: none
} }
+1 -1
View File
@@ -5,7 +5,7 @@ meta {
} }
get { get {
url: {{api_url}}/games url: {{api_url}}/games/1
body: none body: none
auth: none auth: none
} }
@@ -1,5 +1,5 @@
vars { vars {
base_url: http://localhost:8085 base_url: http://localhost:8000
api_url: http://localhost:8085/api api_url: http://localhost:8000/api/v1
token: token:
} }
+1 -1
View File
@@ -17,7 +17,7 @@ spec:
priorityClassName: low-priority priorityClassName: low-priority
containers: containers:
- name: web - name: web
image: registry-172.22.21.115.sslip.io/dad-group-x/web:v1.0.0 image: registry-172.22.21.115.sslip.io/dad-group-46/web:v1.0.1
resources: resources:
requests: requests:
memory: "64Mi" memory: "64Mi"
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/src/index.css" /> <link rel="stylesheet" href="/src/index.css" />
<title>Vite App</title> <title>Bisca</title>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+417 -469
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -42,12 +42,13 @@ const logout = () => {
success: () => { success: () => {
return 'Logout Sucessfull ' 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() socketStore.handleConnection()
}) })
@@ -24,6 +24,9 @@
<NavigationMenuLink> <NavigationMenuLink>
<a @click.prevent="logoutClickHandler">Logout</a> <a @click.prevent="logoutClickHandler">Logout</a>
</NavigationMenuLink> </NavigationMenuLink>
<NavigationMenuLink>
<RouterLink to="/user">Profile</RouterLink>
</NavigationMenuLink>
</NavigationMenuItem> </NavigationMenuItem>
</NavigationMenuList> </NavigationMenuList>
</NavigationMenu> </NavigationMenu>
@@ -39,6 +42,7 @@ import {
NavigationMenuList, NavigationMenuList,
NavigationMenuTrigger, NavigationMenuTrigger,
} from '@/components/ui/navigation-menu' } from '@/components/ui/navigation-menu'
import router from '@/router';
const emits = defineEmits(['logout']) const emits = defineEmits(['logout'])
@@ -46,5 +50,6 @@ const { userLoggedIn } = defineProps(['userLoggedIn'])
const logoutClickHandler = () => { const logoutClickHandler = () => {
emits('logout') emits('logout')
router.push('/login')
} }
</script> </script>
+2 -1
View File
@@ -13,7 +13,7 @@ console.log('[main.js] ws connection', wsConnection)
const app = createApp(App) const app = createApp(App)
app.provide('socket', io(wsConnection)) //app.provide('socket', io(wsConnection))
app.provide('serverBaseURL', `http://${apiDomain}`) app.provide('serverBaseURL', `http://${apiDomain}`)
app.provide('apiBaseURL', `http://${apiDomain}/api`) app.provide('apiBaseURL', `http://${apiDomain}/api`)
@@ -21,3 +21,4 @@ app.use(createPinia())
app.use(router) app.use(router)
app.mount('#app') app.mount('#app')
+19 -11
View File
@@ -1,5 +1,5 @@
<template> <template>
<div class="flex min-h-screen items-center justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:px-8"> <div class="flex min-h-screen items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
<div class="w-full max-w-md space-y-8"> <div class="w-full max-w-md space-y-8">
<div> <div>
<h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900"> <h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
@@ -27,6 +27,14 @@
<Input id="password" v-model="formData.password" type="password" autocomplete="current-password" <Input id="password" v-model="formData.password" type="password" autocomplete="current-password"
required placeholder="••••••••" /> required placeholder="••••••••" />
</div> </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> </div>
@@ -59,21 +67,21 @@ const router = useRouter()
const formData = ref({ const formData = ref({
email: 'pa@mail.pt', email: 'pa@mail.pt',
password: '123' password: '123',
rememberMe: false
}) })
const handleSubmit = async () => { const handleSubmit = async () => {
const promise = authStore.login(formData.value)
toast.promise(authStore.login(formData.value), { toast.promise(promise, {
loading: 'Calling API', loading: 'Calling API',
success: (data) => { success: (user) => {
return `Login Sucessfull - ${data?.name}`
},
error: (data) => `[API] Error saving game - ${data?.response?.data?.message}`,
})
router.push('/') router.push('/')
return `Login Successful - ${user.name}`
},
error: (error) =>
error.response?.data?.message
})
} }
</script> </script>
+19
View File
@@ -0,0 +1,19 @@
/* UserPage.css - Custom styles that can't be done with Tailwind */
.spinner {
width: 40px;
height: 40px;
border: 3px solid #f0f0f0;
border-top: 3px solid #000;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
+621
View File
@@ -0,0 +1,621 @@
<template>
<div class="min-h-screen p-8 flex items-center justify-center">
<!-- Loading State -->
<div v-if="loading" class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full">
<div class="flex flex-col items-center gap-6">
<div class="spinner"></div>
<p>Loading your profile...</p>
</div>
</div>
<!-- Error State -->
<div v-else-if="error" class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full text-gray-800">
<svg class="w-12 h-12 mx-auto mb-4 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="2"/>
<line x1="12" y1="8" x2="12" y2="12" stroke-width="2"/>
<line x1="12" y1="16" x2="12.01" y2="16" stroke-width="2"/>
</svg>
<h3 class="text-2xl mb-2 text-black">Oops! Something went wrong</h3>
<p class="text-gray-600 mb-6">{{ error }}</p>
<button @click="retry" class="flex items-center gap-2 px-6 py-3 bg-black text-white cursor-pointer text-base font-medium transition-colors hover:bg-gray-800 mx-auto">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M1 4v6h6M23 20v-6h-6" stroke-width="2"/>
<path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke-width="2"/>
</svg>
Try Again
</button>
</div>
<!-- User Profile -->
<div v-else-if="authStore.currentUser" class="bg-white border border-gray-300 shadow-lg max-w-4xl w-full overflow-hidden">
<div class="bg-black p-12 text-center relative text-white border-b border-gray-300">
<div class="mb-6 relative inline-block">
<img
v-if="authStore.currentUser.photo_avatar_filename"
:src="`${API_BASE_URL.replace('/api', '')}/storage/photos_avatars/${authStore.currentUser.photo_avatar_filename}`"
:alt="authStore.currentUser.name"
class="w-24 h-24 border-[3px] border-white object-cover"
/>
<div v-else class="w-24 h-24 border-[3px] border-white bg-white text-black flex items-center justify-center text-4xl font-semibold">
{{ authStore.currentUser.name.charAt(0).toUpperCase() }}
</div>
<button @click="triggerFileInput" class="absolute bottom-0 right-0 w-9 h-9 bg-white border-2 border-black cursor-pointer flex items-center justify-center transition-colors hover:bg-gray-100">
<svg class="w-5 h-5 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" stroke-width="1.5"/>
<circle cx="12" cy="13" r="4" stroke-width="1.5"/>
</svg>
</button>
<input
ref="fileInput"
type="file"
accept="image/*"
@change="handleAvatarUpload"
class="hidden"
/>
</div>
<div>
<h1 class="text-3xl font-semibold mb-2">{{ authStore.currentUser.name }}</h1>
<p class="text-base opacity-80">@{{ authStore.currentUser.nickname }}</p>
</div>
<div class="inline-flex items-center gap-2 bg-white text-black px-4 py-2 mt-6 font-medium text-base border border-gray-300">
<svg class="w-5 h-5 text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="1.5"/>
<text x="12" y="16" text-anchor="middle" fill="currentColor" font-size="12" font-weight="bold">$</text>
</svg>
<span>{{ authStore.currentUser.coins_balance }} coins</span>
</div>
</div>
<div>
<!-- Tab Navigation -->
<div class="flex border-b border-gray-300 bg-gray-50">
<button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'info' }]"
@click="activeTab = 'info'"
>
Profile Information
</button>
<button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'edit' }]"
@click="activeTab = 'edit'"
>
Edit Profile
</button>
<button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'password' }]"
@click="activeTab = 'password'"
>
Change Password
</button>
<button
:class="['flex-1 p-4 bg-transparent border-none border-b-2 border-transparent cursor-pointer text-sm font-medium text-gray-600 transition-all hover:bg-gray-100 hover:text-black', { 'border-b-black text-black bg-white': activeTab === 'delete' }]"
@click="activeTab = 'delete'"
>
Delete Account
</button>
</div>
<!-- Profile Information Tab -->
<div v-if="activeTab === 'info'" class="p-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
<polyline points="22,6 12,13 2,6"/>
</svg>
</div>
<div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Email</label>
<p class="text-sm text-black">{{ authStore.currentUser.email }}</p>
</div>
</div>
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
<circle cx="12" cy="7" r="4"/>
</svg>
</div>
<div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Account Type</label>
<p class="text-sm text-black">{{ authStore.currentUser.type === 'P' ? 'Player' : 'Other' }}</p>
</div>
</div>
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
<line x1="16" y1="2" x2="16" y2="6"/>
<line x1="8" y1="2" x2="8" y2="6"/>
<line x1="3" y1="10" x2="21" y2="10"/>
</svg>
</div>
<div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Member Since</label>
<p class="text-sm text-black">{{ formatDate(authStore.currentUser.created_at) }}</p>
</div>
</div>
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<circle cx="12" cy="12" r="10"/>
<path d="M9 12l2 2 4-4"/>
</svg>
</div>
<div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Status</label>
<p>
<span :class="['inline-block px-3 py-1 text-sm font-medium border', authStore.currentUser.blocked ? 'bg-black text-white border-black' : 'bg-white text-black border-black']">
{{ authStore.currentUser.blocked ? 'Blocked' : 'Active' }}
</span>
</p>
</div>
</div>
<div v-if="authStore.currentUser.email_verified_at" class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
<polyline points="22 4 12 14.01 9 11.01"/>
</svg>
</div>
<div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Email Verified</label>
<p class="text-sm text-black">{{ formatDate(authStore.currentUser.email_verified_at) }}</p>
</div>
</div>
<div class="flex items-start gap-4 p-5 bg-white border border-gray-300 transition-shadow hover:shadow-md">
<div class="w-10 h-10 flex items-center justify-center flex-shrink-0 text-gray-600">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<polyline points="23 4 23 10 17 10"/>
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
</svg>
</div>
<div class="flex-1">
<label class="block text-xs font-semibold text-gray-500 mb-1 uppercase tracking-wider">Last Updated</label>
<p class="text-sm text-black">{{ formatDate(authStore.currentUser.updated_at) }}</p>
</div>
</div>
</div>
</div>
<!-- Edit Profile Tab -->
<div v-if="activeTab === 'edit'" class="p-8">
<form @submit.prevent="updateProfile" class="max-w-lg">
<div class="mb-6">
<label for="name" class="block text-sm font-semibold text-gray-800 mb-2">Name</label>
<input
id="name"
v-model="profileForm.name"
type="text"
required
:disabled="updatingProfile"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
</div>
<div class="mb-6">
<label for="nickname" class="block text-sm font-semibold text-gray-800 mb-2">Nickname</label>
<input
id="nickname"
v-model="profileForm.nickname"
type="text"
required
:disabled="updatingProfile"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
</div>
<div class="flex gap-4 mt-8">
<button type="button" @click="resetProfileForm" :disabled="updatingProfile" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-white text-black hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed">
Cancel
</button>
<button type="submit" :disabled="updatingProfile" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-black text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed">
{{ updatingProfile ? 'Saving...' : 'Save Changes' }}
</button>
</div>
<div v-if="profileMessage" :class="['mt-4 px-3 py-3 border text-sm', profileMessageType === 'success' ? 'bg-blue-50 border-black text-black' : 'bg-red-50 border-black text-black']">
{{ profileMessage }}
</div>
</form>
</div>
<!-- Change Password Tab -->
<div v-if="activeTab === 'password'" class="p-8">
<form @submit.prevent="changePassword" class="max-w-lg">
<div class="mb-6">
<label for="current_password" class="block text-sm font-semibold text-gray-800 mb-2">Current Password</label>
<input
id="current_password"
v-model="passwordForm.current_password"
type="password"
required
:disabled="updatingPassword"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
</div>
<div class="mb-6">
<label for="new_password" class="block text-sm font-semibold text-gray-800 mb-2">New Password</label>
<input
id="new_password"
v-model="passwordForm.new_password"
type="password"
required
minlength="8"
:disabled="updatingPassword"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
<small class="block mt-1 text-xs text-gray-600">Password must be at least 8 characters long</small>
</div>
<div class="mb-6">
<label for="confirm_password" class="block text-sm font-semibold text-gray-800 mb-2">Confirm New Password</label>
<input
id="confirm_password"
v-model="passwordForm.confirm_password"
type="password"
required
:disabled="updatingPassword"
class="w-full px-3 py-3 border border-gray-300 text-base transition-colors focus:outline-none focus:border-black disabled:bg-gray-100 disabled:cursor-not-allowed"
/>
</div>
<div class="flex gap-4 mt-8">
<button type="button" @click="resetPasswordForm" :disabled="updatingPassword" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-white text-black hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed">
Cancel
</button>
<button type="submit" :disabled="updatingPassword" class="px-6 py-3 border border-black cursor-pointer text-base font-medium transition-all bg-black text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed">
{{ updatingPassword ? 'Updating...' : 'Change Password' }}
</button>
</div>
<div v-if="passwordMessage" :class="['mt-4 px-3 py-3 border text-sm', passwordMessageType === 'success' ? 'bg-blue-50 border-black text-black' : 'bg-red-50 border-black text-black']">
{{ passwordMessage }}
</div>
</form>
</div>
<!-- Delete Account Tab -->
<div v-if="activeTab === 'delete'" class="p-8 flex flex-col items-center">
<div class="max-w-lg">
<div class="border border-red-600 bg-red-50 p-6 mb-6">
<div class="flex items-start gap-3">
<svg class="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
<line x1="12" y1="9" x2="12" y2="13"/>
<line x1="12" y1="17" x2="12.01" y2="17"/>
</svg>
<div>
<h3 class="text-lg font-semibold text-red-900 mb-2">Danger Zone</h3>
<p class="text-sm text-red-800 mb-2">
Deleting your account is permanent and cannot be undone. This action will:
</p>
<ul class="text-sm text-red-800 list-disc list-inside space-y-1">
<li>Permanently delete all your account data</li>
<li>Forfeit your current coin balance of <strong>{{ authStore.currentUser.coins_balance }} coins</strong></li>
<li>Remove your access to all games and matches</li>
<li>Delete your profile and all associated information</li>
</ul>
</div>
</div>
</div>
<div class="bg-white border border-gray-300 p-6">
<h4 class="text-base font-semibold text-gray-900 mb-4">
Are you absolutely sure?
</h4>
<p class="text-sm text-gray-600 mb-4">
To confirm deletion, please type your email address: <strong class="text-black">{{ authStore.currentUser.email }}</strong>
</p>
<input
v-model="deleteConfirmEmail"
type="text"
placeholder="Enter your email to confirm"
class="w-full px-3 py-3 border border-gray-300 text-base mb-4 focus:outline-none focus:border-red-600"
/>
<div class="flex gap-4">
<button
type="button"
@click="activeTab = 'info'"
class="flex-1 px-6 py-3 border border-gray-300 cursor-pointer text-base font-medium transition-all bg-white text-gray-700 hover:bg-gray-50"
>
Cancel
</button>
<button
@click="showDeleteConfirmation = true"
:disabled="deleteConfirmEmail !== authStore.currentUser.email"
class="flex-1 px-6 py-3 border border-red-600 cursor-pointer text-base font-medium transition-all bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-red-600"
>
Delete My Account
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div
v-if="showDeleteConfirmation"
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
@click.self="showDeleteConfirmation = false"
>
<div class="bg-white border border-gray-300 max-w-md w-full shadow-xl">
<div class="p-6 border-b border-gray-300">
<h3 class="text-xl font-semibold text-gray-900">Final Confirmation</h3>
</div>
<div class="p-6">
<div class="flex items-start gap-3 mb-4">
<svg class="w-12 h-12 text-red-600 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<line x1="15" y1="9" x2="9" y2="15"/>
<line x1="9" y1="9" x2="15" y2="15"/>
</svg>
<div>
<p class="text-base text-gray-900 font-semibold mb-2">
This is your last chance to cancel.
</p>
<p class="text-sm text-gray-600">
Once you click "Yes, Delete My Account", your account and all associated data will be permanently deleted. You will lose your <strong>{{ authStore.currentUser.coins_balance }} coins</strong> forever.
</p>
</div>
</div>
<div v-if="deletingAccount" class="text-center py-4">
<div class="spinner mx-auto mb-3"></div>
<p class="text-sm text-gray-600">Deleting your account...</p>
</div>
</div>
<div class="p-6 border-t border-gray-300 flex gap-3">
<button
@click="showDeleteConfirmation = false"
:disabled="deletingAccount"
class="flex-1 px-6 py-3 border border-gray-300 cursor-pointer text-base font-medium transition-all bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
Cancel
</button>
<button
@click="deleteAccount"
:disabled="deletingAccount"
class="flex-1 px-6 py-3 border border-red-600 cursor-pointer text-base font-medium transition-all bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
Yes, Delete My Account
</button>
</div>
</div>
</div>
<!-- No Data State -->
<div v-else-if="!authStore.isLoggedIn" class="bg-white border border-gray-300 p-12 text-center shadow-sm max-w-md w-full">
<div class="flex flex-col items-center gap-6">
<div class="spinner"></div>
<p>Redirecting to login...</p>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, inject, reactive } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useAPIStore } from '@/stores/api'
import { useRouter } from 'vue-router'
import axios from 'axios'
const authStore = useAuthStore()
const apiStore = useAPIStore()
const router = useRouter()
const API_BASE_URL = inject('apiBaseURL')
const loading = ref(false)
const error = ref(null)
const activeTab = ref('info')
const fileInput = ref(null)
// Profile form
const profileForm = reactive({
name: '',
nickname: ''
})
const updatingProfile = ref(false)
const profileMessage = ref('')
const profileMessageType = ref('')
// Password form
const passwordForm = reactive({
current_password: '',
new_password: '',
confirm_password: ''
})
const updatingPassword = ref(false)
const passwordMessage = ref('')
const passwordMessageType = ref('')
// Delete account
const deleteConfirmEmail = ref('')
const showDeleteConfirmation = ref(false)
const deletingAccount = ref(false)
const formatDate = (dateString) => {
const date = new Date(dateString)
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
}
const fetchProfile = async () => {
loading.value = true
error.value = null
try {
const response = await apiStore.getAuthUser()
authStore.currentUser = response.data
resetProfileForm()
} catch (err) {
error.value = err.response?.data?.message || 'Failed to fetch user profile'
if (err.response?.status === 401) {
await authStore.logout()
router.push('/login')
}
} finally {
loading.value = false
}
}
const retry = () => {
fetchProfile()
}
const resetProfileForm = () => {
profileForm.name = authStore.currentUser?.name || ''
profileForm.nickname = authStore.currentUser?.nickname || ''
profileMessage.value = ''
}
const resetPasswordForm = () => {
passwordForm.current_password = ''
passwordForm.new_password = ''
passwordForm.confirm_password = ''
passwordMessage.value = ''
}
const updateProfile = async () => {
profileMessage.value = ''
if (!profileForm.name.trim() || !profileForm.nickname.trim()) {
profileMessage.value = 'Name and nickname are required'
profileMessageType.value = 'error'
return
}
updatingProfile.value = true
try {
const response = await axios.put(`${API_BASE_URL}/users/me`, {
name: profileForm.name,
nickname: profileForm.nickname
})
authStore.currentUser = response.data
profileMessage.value = 'Profile updated successfully!'
profileMessageType.value = 'success'
} catch (err) {
profileMessage.value = err.response?.data?.message || 'Failed to update profile'
profileMessageType.value = 'error'
} finally {
updatingProfile.value = false
}
}
const changePassword = async () => {
passwordMessage.value = ''
if (passwordForm.new_password !== passwordForm.confirm_password) {
passwordMessage.value = 'New passwords do not match'
passwordMessageType.value = 'error'
return
}
if (passwordForm.new_password.length < 8) {
passwordMessage.value = 'Password must be at least 8 characters long'
passwordMessageType.value = 'error'
return
}
updatingPassword.value = true
try {
await axios.put(`${API_BASE_URL}/users/me/password`, {
current_password: passwordForm.current_password,
new_password: passwordForm.new_password,
new_password_confirmation: passwordForm.confirm_password
})
passwordMessage.value = 'Password changed successfully!'
passwordMessageType.value = 'success'
resetPasswordForm()
} catch (err) {
passwordMessage.value = err.response?.data?.message || 'Failed to change password'
passwordMessageType.value = 'error'
} finally {
updatingPassword.value = false
}
}
const triggerFileInput = () => {
fileInput.value?.click()
}
const handleAvatarUpload = async (event) => {
const file = event.target.files?.[0]
if (!file) return
const formData = new FormData()
formData.append('avatar', file)
try {
const response = await axios.post(`${API_BASE_URL}/users/me/avatar`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
authStore.currentUser = response.data
} catch (err) {
alert(err.response?.data?.message || 'Failed to upload avatar')
}
}
const deleteAccount = async () => {
deletingAccount.value = true
try {
await axios.delete(`${API_BASE_URL}/users/me`)
// Logout user
await authStore.logout()
// Close modal
showDeleteConfirmation.value = false
// Redirect to home/login
router.push('/login')
} catch (err) {
deletingAccount.value = false
showDeleteConfirmation.value = false
alert(err.response?.data?.message || 'Failed to delete account')
}
}
onMounted(async () => {
if (!authStore.isLoggedIn) {
router.push('/login')
return
}
if (!authStore.currentUser) {
await fetchProfile()
} else {
resetProfileForm()
}
})
</script>
<style scoped>
@import './UserPage.css';
</style>
+5
View File
@@ -2,6 +2,7 @@ import HomePage from '@/pages/home/HomePage.vue'
import LoginPage from '@/pages/login/LoginPage.vue' import LoginPage from '@/pages/login/LoginPage.vue'
import LaravelPage from '@/pages/testing/LaravelPage.vue' import LaravelPage from '@/pages/testing/LaravelPage.vue'
import WebsocketsPage from '@/pages/testing/WebsocketsPage.vue' import WebsocketsPage from '@/pages/testing/WebsocketsPage.vue'
import UserPage from '@/pages/user/UserPage.vue'
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({ const router = createRouter({
@@ -15,6 +16,10 @@ const router = createRouter({
path: '/login', path: '/login',
component: LoginPage, component: LoginPage,
}, },
{
path: '/user',
component: UserPage,
},
{ {
path: '/testing', path: '/testing',
children: [ children: [
+26 -1
View File
@@ -1,9 +1,11 @@
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'
import { useAuthStore } from './auth'
export const useAPIStore = defineStore('api', () => { export const useAPIStore = defineStore('api', () => {
const API_BASE_URL = inject('apiBaseURL') const API_BASE_URL = inject('apiBaseURL')
const authStore = useAuthStore()
const token = ref() const token = ref()
const gameQueryParameters = ref({ const gameQueryParameters = ref({
@@ -16,12 +18,35 @@ export const useAPIStore = defineStore('api', () => {
}, },
}) })
// AUTH 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 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
} }
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
+105 -6
View File
@@ -3,35 +3,134 @@ import { ref, computed } from 'vue'
import { useAPIStore } from './api' import { useAPIStore } from './api'
export const useAuthStore = defineStore('auth', () => { 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 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(() => { const isLoggedIn = computed(() => {
return currentUser.value !== undefined return currentUser.value !== undefined && token.value !== null && !isTokenAlmostExpired()
}) })
const currentUserID = computed(() => { const currentUserID = computed(() => {
return currentUser.value?.id return currentUser.value?.id
}) })
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
}
}
const getToken = () => {
return token.value
}
const login = async (credentials) => { const login = async (credentials) => {
await apiStore.postLogin(credentials) const apiStore = useAPIStore()
const response = await apiStore.getAuthUser() const loginResp = await apiStore.postLogin(credentials)
currentUser.value = response.data const userResp = await apiStore.getAuthUser()
return response.data
const jwtToken = loginResp.data.token
setToken(jwtToken, credentials.rememberMe)
currentUser.value = userResp.data
localStorage.setItem('currentUser', JSON.stringify(userResp.data))
return userResp.data
} }
const logout = async () => { const logout = async () => {
const apiStore = useAPIStore()
await apiStore.postLogout() await apiStore.postLogout()
currentUser.value = undefined 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 { return {
currentUser, currentUser,
isLoggedIn, isLoggedIn,
currentUserID, currentUserID,
token,
rememberMe,
setToken,
getToken,
login, login,
logout, logout,
resetTokenExpiry,
isTokenAlmostExpired,
checkTokenExpiry,
restoreSession,
} }
}) })
+8
View File
@@ -0,0 +1,8 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { toast } from 'vue-sonner'
import { useApiStore } from './api'
export const useGameStore = defineStore('game', () => {
})
+5
View File
@@ -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,
} }
}) })
+58
View File
@@ -0,0 +1,58 @@
import { defineStore } from 'pinia'
import axios from 'axios'
import { useAuthStore } from './auth'
export const useUserStore = defineStore('user', {
state: () => ({
user: null,
loading: false,
error: null
}),
getters: {
currentUser: (state) => state.user
},
actions: {
async fetchUserProfile() {
const authStore = useAuthStore()
const token = authStore.getToken()
if (!token) {
this.error = 'No authentication token found'
throw new Error('No authentication token found')
}
this.loading = true
this.error = null
try {
const response = await axios.get('/api/users/me', {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
})
this.user = response.data
return response.data
} catch (error) {
this.error = error.response?.data?.message || 'Failed to fetch user profile'
if (error.response?.status === 401) {
authStore.logout()
}
throw error
} finally {
this.loading = false
}
},
clearUser() {
this.user = null
this.error = null
this.loading = false
}
}
})
+1
View File
@@ -0,0 +1 @@
PORT=
+43 -2
View File
@@ -1,5 +1,46 @@
import { addUser, removeUser } from "../state/connection";
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
export const handleConnectionEvents = (io, socket) => { export const handleConnectionEvents = (io, socket) => {
socket.on("echo", (msg) => { let heartbeatInterval;
socket.emit("echo", msg); let heartbeatTimeout;
const startHeartbeat = () => {
heartbeatInterval = setInterval(() => {
socket.emit("heartbeat");
heartbeatTimeout = setTimeout(() => {
console.log(
`[Heartbeat] No response from ${socket.id}, disconnecting...`
);
socket.disconnect(true);
}, HEARTBEAT_TIMEOUT);
}, HEARTBEAT_INTERVAL);
};
socket.on("heartbeat_ack", () => {
clearTimeout(heartbeatTimeout);
console.log(`[Heartbeat] Received pong from ${socket.id}`);
});
socket.on("join", (user) => {
addUser(socket, user);
console.log(`[Connection] User ${user.name} has joined the server`);
console.log(`[Connection] ${getUserCount()} users online`);
});
socket.on("leave", () => {
const user = removeUser(socket.id);
if (user) {
console.log(`[Connection] User ${user.name} has left the server`);
console.log(`[Connection] ${getUserCount()} users online`);
}
});
socket.on("disconnect", () => {
console.log("Connection Lost:", socket.id);
removeUser(socket.id);
console.log(`[Connection] ${getUserCount()} users online`);
}); });
}; };
+19
View File
@@ -0,0 +1,19 @@
const users = new Map();
export const addUser = (socket, user) => {
users.set(socket.id, user);
};
export const removeUser = (socketID) => {
const userToDelete = { ...users.get(socketID) };
users.delete(socketID);
return userToDelete;
};
export const getUser = (socketID) => {
return users.get(socketID);
};
export const getUserCount = () => {
return users.size;
};