Skip to content

A self-hosted media server and file management system

feat: user sessions backend

aminnausin987efcf139a6
diff --git a/app/Http/Controllers/Api/V1/SessionController.php b/app/Http/Controllers/Api/V1/SessionController.php
new file mode 100644
index 00000000..7307c2f5
--- /dev/null
+++ b/app/Http/Controllers/Api/V1/SessionController.php
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Controllers\API\V1;
+
+use App\Http\Controllers\Controller;
+use Illuminate\Http\Request;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Facades\DB;
+
+class SessionController extends Controller {
+ public function index(Request $request) {
+ $user = $request->user();
+
+ $sessions = DB::table('sessions')
+ ->where('user_id', $user->id)
+ ->orderByDesc('last_activity')
+ ->get()
+ ->map(function ($session) use ($request) {
+ return [
+ 'id' => $session->id,
+ 'ip_address' => $session->ip_address,
+ 'user_agent' => $session->user_agent,
+ 'is_current' => $session->id === $request->session()->getId(),
+ 'last_active' => Carbon::createFromTimestamp($session->last_activity)->diffForHumans(),
+ ];
+ });
+
+ return response()->json($sessions);
+ }
+
+ public function delete(Request $request) {
+ // Unimplemented
+ }
+}
diff --git a/resources/js/service/authAPI.ts b/resources/js/service/authAPI.ts
index ccbff943..884400d4 100644
--- a/resources/js/service/authAPI.ts
+++ b/resources/js/service/authAPI.ts
@@ -1,3 +1,4 @@
+import type { ChangeEmailRequest, ChangePasswordRequest } from '@/types/requests';
import { WEB, API } from './api';
export const getCSRF = async () => {
@@ -44,3 +45,15 @@ export const authenticate = async (token: string | null) => {
throw error instanceof Error ? error : new Error(String(error));
}
};
+
+export function changePassword(data: ChangePasswordRequest) {
+ return API.put(`/settings/password`, data);
+}
+
+export function changeEmail(data: ChangeEmailRequest) {
+ return API.put(`/settings/email`, data);
+}
+
+export function getSessions() {
+ return API.get('/settings/sessions');
+}
diff --git a/resources/js/service/queries.ts b/resources/js/service/queries.ts
index 23380ddf..02d0868f 100644
--- a/resources/js/service/queries.ts
+++ b/resources/js/service/queries.ts
@@ -1,10 +1,12 @@
import type { CategoryResource, FolderResource, TaskResource, UserResource } from '@/types/resources';
import type { AppManifest, PulseResponse, TaskStatsResponse } from '@/types/types.ts';
+import type { Session } from '@/types/model';
import type { Ref } from 'vue';
import { getSiteAnalytics, getPulse, getUsers, getTasks, getTaskStats, getActiveSessions, getManifest } from '@/service/siteAPI.ts';
import { useAuthStore } from '@/stores/AuthStore';
import { storeToRefs } from 'pinia';
+import { getSessions } from '@/service/authAPI';
import { useQuery } from '@tanstack/vue-query';
import mediaAPI, { getCategories, getFolders } from '@/service/mediaAPI.ts';
@@ -125,23 +127,16 @@ export const useGetManifest = () => {
});
};
-// export const useGetChatRoomMessagesQuery = (chat_id: number | null) => {
-// return useInfiniteQuery({
-// queryKey: ['chatroom-messages', chat_id],
-// initialPageParam: `/chat/chatroom/${chat_id}/messages/?page=${1}`,
-// getNextPageParam: (lastPage) => lastPage.next,
-// queryFn: async ({ pageParam }: { pageParam: string }): Promise<PaginatedResponse<MessageResponse>> => {
-// if (!chat_id)
-// return {
-// count: 0,
-// total_pages: 0,
-// page_size: 0,
-// next: null,
-// previous: null,
-// results: [],
-// };
-// const response = await axios.get(pageParam);
-// return response.data;
-// },
-// });
-// };
+/**
+ *
+ * @returns List of logged in sessions for the logged in user
+ */
+export const useGetSessions = () => {
+ return useQuery<Session[]>({
+ queryKey: ['sessions'],
+ queryFn: async () => {
+ const { data: response } = await getSessions();
+ return response;
+ },
+ });
+};
diff --git a/resources/js/stores/SettingsStore.ts b/resources/js/stores/SettingsStore.ts
new file mode 100644
index 00000000..8d7c22f0
--- /dev/null
+++ b/resources/js/stores/SettingsStore.ts
@@ -0,0 +1,19 @@
+import type { Session } from '@/types/model';
+
+import { useGetSessions } from '@/service/queries';
+import { defineStore } from 'pinia';
+import { ref, watch } from 'vue';
+
+export const useSettingsStore = defineStore('Settings', () => {
+ const { data: rawSessions, isLoading: isLoadingSessions } = useGetSessions();
+ const stateSessions = ref<Session[]>([]);
+
+ watch(rawSessions, (v) => {
+ stateSessions.value = v ?? [];
+ });
+
+ return {
+ stateSessions,
+ isLoadingSessions,
+ };
+});
diff --git a/resources/js/types/model.ts b/resources/js/types/model.ts
index 56c8d3aa..5497c685 100644
--- a/resources/js/types/model.ts
+++ b/resources/js/types/model.ts
@@ -138,3 +138,11 @@ export interface FolderTag {
created_at?: string;
updated_at?: string;
}
+
+export interface Session {
+ id: string;
+ ip_address: string;
+ user_agent: string;
+ is_current: boolean;
+ last_active: string;
+}
diff --git a/tests/Feature/Settings/SessionControllerTest.php b/tests/Feature/Settings/SessionControllerTest.php
new file mode 100644
index 00000000..0302fcf1
--- /dev/null
+++ b/tests/Feature/Settings/SessionControllerTest.php
@@ -0,0 +1,59 @@
+<?php
+
+namespace Tests\Feature\Settings;
+
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+use Tests\TestCase;
+
+class SessionControllerTest extends TestCase {
+ use RefreshDatabase;
+
+ public function returns_sessions_for_authenticated_user_only() {
+ $user = User::factory()->create();
+ $user2 = User::factory()->create();
+ $this->actingAs($user);
+
+ // Create a session manually
+ DB::table('sessions')->insert(
+ [
+ 'id' => $sessionId = Str::random(40),
+ 'user_id' => $user->id,
+ 'ip_address' => '127.0.0.1',
+ 'user_agent' => 'FakeAgent/1.0',
+ 'payload' => '',
+ 'last_activity' => now()->timestamp,
+ ],
+ [
+ 'id' => $sessionId = Str::random(40),
+ 'user_id' => $user2->id,
+ 'ip_address' => '127.0.0.1',
+ 'user_agent' => 'FakeAgent/1.0',
+ 'payload' => '',
+ 'last_activity' => now()->timestamp,
+ ]
+ );
+
+ // Set current session ID
+ session()->setId($sessionId);
+ session()->start();
+
+ $response = $this->getJson('/api/settings/sessions');
+
+ $response->assertOk()
+ ->assertJsonCount(1)
+ ->assertJsonFragment([
+ 'id' => $sessionId,
+ 'ip_address' => '127.0.0.1',
+ 'user_agent' => 'FakeAgent/1.0',
+ 'is_current' => true,
+ ]);
+ }
+
+ public function unauthenticated_users_cannot_access_sessions() {
+ $response = $this->getJson('/api/settings/sessions');
+ $response->assertUnauthorized(); // 401
+ }
+}