Compare commits

...
Author SHA1 Message Date
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
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
AfonsoCMSousa a0ad35bb08 Merge branch 'feature/login-page' into feature/profile-page 2025-12-11 21:18:31 +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
21 changed files with 1507 additions and 603 deletions
+3
View File
@@ -99,3 +99,6 @@ Desktop.ini
# If you have any local secrets or files not to track, add them here:
# /path/to/some/file
package-lock.json
.vscode
-3
View File
@@ -1,3 +0,0 @@
{
"postman.settings.dotenv-detection-notification-visibility": false
}
+93 -58
View File
@@ -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,66 +95,79 @@ 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'])
->exists();
->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);
return response()->json($game);
}
}
}
+12 -18
View File
@@ -2,7 +2,6 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
@@ -11,30 +10,27 @@ use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable, HasApiTokens, SoftDeletes;
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'nickname',
'photo_avatar_filename',
'type',
'blocked',
'photo_avatar_filename',
'coins_balance',
'custom',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
* @var array<int, string>
*/
protected $hidden = [
'password',
@@ -42,16 +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
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'blocked' => 'boolean',
];
}
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'blocked' => 'boolean',
'deleted_at' => 'datetime',
];
}
+97 -26
View File
@@ -1,38 +1,109 @@
<?php
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();
});
// Update user profile (name and nickname)
Route::put('/me', function (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);
});
// Change password
Route::put('/me/password', function (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'
]);
});
// Upload avatar
Route::post('/me/avatar', function (Request $request) {
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$user = $request->user();
// Delete old avatar if exists
if ($user->photo_avatar_filename) {
\Storage::disk('public')->delete('photos_avatars/' . $user->photo_avatar_filename);
}
// Store new avatar
$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);
});
// Delete account
Route::delete('/me', function (Request $request) {
$user = $request->user();
$user->tokens()->delete();
$user->delete();
return response()->json([
'message' => 'Account deleted successfully'
]);
});
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']);
});
});
+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"
}
+1 -1
View File
@@ -17,7 +17,7 @@ spec:
priorityClassName: low-priority
containers:
- 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:
requests:
memory: "64Mi"
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/src/index.css" />
<title>Vite App</title>
<title>Bisca</title>
</head>
<body>
<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: () => {
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()
})
@@ -24,6 +24,9 @@
<NavigationMenuLink>
<a @click.prevent="logoutClickHandler">Logout</a>
</NavigationMenuLink>
<NavigationMenuLink>
<RouterLink to="/user">Profile</RouterLink>
</NavigationMenuLink>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
@@ -39,6 +42,7 @@ import {
NavigationMenuList,
NavigationMenuTrigger,
} from '@/components/ui/navigation-menu'
import router from '@/router';
const emits = defineEmits(['logout'])
@@ -46,5 +50,6 @@ const { userLoggedIn } = defineProps(['userLoggedIn'])
const logoutClickHandler = () => {
emits('logout')
router.push('/login')
}
</script>
+2 -1
View File
@@ -13,7 +13,7 @@ console.log('[main.js] ws connection', wsConnection)
const app = createApp(App)
app.provide('socket', io(wsConnection))
//app.provide('socket', io(wsConnection))
app.provide('serverBaseURL', `http://${apiDomain}`)
app.provide('apiBaseURL', `http://${apiDomain}/api`)
@@ -21,3 +21,4 @@ app.use(createPinia())
app.use(router)
app.mount('#app')
+1 -1
View File
@@ -8,4 +8,4 @@
</script>
<style scoped></style>`
<style scoped></style>`
+18 -10
View File
@@ -1,5 +1,5 @@
<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>
<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"
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,21 +67,21 @@ const router = useRouter()
const formData = ref({
email: 'pa@mail.pt',
password: '123'
password: '123',
rememberMe: false
})
const handleSubmit = async () => {
toast.promise(authStore.login(formData.value), {
const promise = authStore.login(formData.value)
toast.promise(promise, {
loading: 'Calling API',
success: (data) => {
return `Login Sucessfull - ${data?.name}`
success: (user) => {
router.push('/')
return `Login Successful - ${user.name}`
},
error: (data) => `[API] Error saving game - ${data?.response?.data?.message}`,
error: (error) =>
error.response?.data?.message
})
router.push('/')
}
</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 LaravelPage from '@/pages/testing/LaravelPage.vue'
import WebsocketsPage from '@/pages/testing/WebsocketsPage.vue'
import UserPage from '@/pages/user/UserPage.vue'
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
@@ -15,6 +16,10 @@ const router = createRouter({
path: '/login',
component: LoginPage,
},
{
path: '/user',
component: UserPage,
},
{
path: '/testing',
children: [
+26 -1
View File
@@ -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,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 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
+105 -6
View File
@@ -3,35 +3,134 @@ 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
return currentUser.value !== undefined && token.value !== null && !isTokenAlmostExpired()
})
const currentUserID = computed(() => {
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) => {
await apiStore.postLogin(credentials)
const response = await apiStore.getAuthUser()
currentUser.value = response.data
return response.data
const apiStore = useAPIStore()
const loginResp = await apiStore.postLogin(credentials)
const userResp = await apiStore.getAuthUser()
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 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 {
currentUser,
isLoggedIn,
currentUserID,
token,
rememberMe,
setToken,
getToken,
login,
logout,
resetTokenExpiry,
isTokenAlmostExpired,
checkTokenExpiry,
restoreSession,
}
})
+11 -6
View File
@@ -5,15 +5,20 @@ export const useSocketStore = defineStore('socket', () => {
const socket = inject('socket')
const handleConnection = () => {
socket.on('connect', () => {
console.log(`[Socket] Connected -- ${socket.id}`)
})
socket.on('disconnect', () => {
console.log(`[Socket] Disconnected -- ${socket.id}`)
})
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,
}
})
+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
}
}
})