Skip to content

A self-hosted media server and file management system

fix: sessions test and code smells

aminnausin01d67ef88d04
diff --git a/app/Http/Controllers/Api/V1/SessionController.php b/app/Http/Controllers/Api/V1/SessionController.php
index 7307c2f5..61e9cf02 100644
--- a/app/Http/Controllers/Api/V1/SessionController.php
+++ b/app/Http/Controllers/Api/V1/SessionController.php
@@ -10,7 +10,6 @@ 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')
@@ -20,7 +19,7 @@ class SessionController extends Controller {
'id' => $session->id,
'ip_address' => $session->ip_address,
'user_agent' => $session->user_agent,
- 'is_current' => $session->id === $request->session()->getId(),
+ 'is_current' => $request->hasSession() && $session->id === $request->session()->getId(),
'last_active' => Carbon::createFromTimestamp($session->last_activity)->diffForHumans(),
];
});
diff --git a/phpunit.xml b/phpunit.xml
index 403d5b6a..917bdbe1 100755
--- a/phpunit.xml
+++ b/phpunit.xml
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
- bootstrap="vendor/autoload.php"
- colors="true"
+ xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
+ bootstrap="vendor/autoload.php"
+ colors="true"
>
<testsuites>
<testsuite name="Unit">
@@ -18,20 +18,20 @@
</include>
</source>
<php>
- <env name="APP_ENV" value="testing"/>
- <env name="APP_MAINTENANCE_DRIVER" value="file"/>
- <env name="BCRYPT_ROUNDS" value="4"/>
- <env name="CACHE_DRIVER" value="array"/>
- <env name="CACHE_STORE" value="array"/>
- <env name="LOG_CHANNEL" value="stderr"/>
+ <env name="APP_ENV" value="testing" />
+ <env name="APP_MAINTENANCE_DRIVER" value="file" />
+ <env name="BCRYPT_ROUNDS" value="4" />
+ <env name="CACHE_DRIVER" value="array" />
+ <env name="CACHE_STORE" value="array" />
+ <env name="LOG_CHANNEL" value="stderr" />
- <env name="DB_CONNECTION" value="pgsql"/>
- <env name="DB_DATABASE" value="laravel_test"/>
+ <env name="DB_CONNECTION" value="pgsql" />
+ <env name="DB_DATABASE" value="laravel_test" />
- <env name="MAIL_MAILER" value="array"/>
- <env name="PULSE_ENABLED" value="false"/>
- <env name="QUEUE_CONNECTION" value="sync"/>
- <env name="SESSION_DRIVER" value="array"/>
- <env name="TELESCOPE_ENABLED" value="false"/>
+ <env name="MAIL_MAILER" value="array" />
+ <env name="PULSE_ENABLED" value="false" />
+ <env name="QUEUE_CONNECTION" value="sync" />
+ <env name="SESSION_DRIVER" value="array" />
+ <env name="TELESCOPE_ENABLED" value="false" />
</php>
-</phpunit>
+</phpunit>
\ No newline at end of file
diff --git a/resources/js/router/index.ts b/resources/js/router/index.ts
index 57890c57..45ec3760 100644
--- a/resources/js/router/index.ts
+++ b/resources/js/router/index.ts
@@ -18,7 +18,7 @@ import ErrorView from '@/views/ErrorView.vue';
import SetupView from '@/views/SetupView.vue';
import RootView from '@/views/RootView.vue';
-interface routeMeta {
+interface RouteMeta {
title?: string;
protected?: boolean;
redirect?: string;
@@ -152,7 +152,7 @@ const router = createRouter({
],
});
-const redirectAfterLogin = async (to: RouteLocationNormalizedGeneric, next: NavigationGuardNext, meta: routeMeta) => {
+const redirectAfterLogin = async (to: RouteLocationNormalizedGeneric, next: NavigationGuardNext, meta: RouteMeta) => {
const { auth } = useAuthStore();
if (await auth()) {
@@ -189,7 +189,7 @@ const redirectGuest = async (next: NavigationGuardNext) => {
};
router.beforeEach(async (to, from, next) => {
- const meta = to.meta as routeMeta;
+ const meta = to.meta as RouteMeta;
// If going to a route that isnt included in the list, set the page title to the route title
if (to?.name && ['logout', 'root', 'home'].indexOf(to.name.toString()) === -1) {
diff --git a/resources/js/views/SettingsView.vue b/resources/js/views/SettingsView.vue
index f514280d..843a9d4a 100755
--- a/resources/js/views/SettingsView.vue
+++ b/resources/js/views/SettingsView.vue
@@ -2,7 +2,6 @@
import type { SidebarTabItem } from '@/types/types';
import { computed, onMounted, ref, watch } from 'vue';
-import { useSettingsStore } from '@/stores/SettingsStore';
import { useAuthStore } from '@/stores/AuthStore';
import { useAppStore } from '@/stores/AppStore';
import { storeToRefs } from 'pinia';
@@ -17,11 +16,12 @@ import ProiconsSettings from '~icons/proicons/settings';
import CircumGrid31 from '~icons/circum/grid-3-1';
import LucideUser from '~icons/lucide/user';
-const {} = storeToRefs(useSettingsStore());
const { pageTitle, selectedSideBar } = storeToRefs(useAppStore());
const { cycleSideBar } = useAppStore();
const { userData } = storeToRefs(useAuthStore());
+const dev = true;
+
const settingsTab = ref<{ name: string; title?: string; icon?: any }>();
const settingsTabs = computed<SidebarTabItem[]>(() => {
@@ -43,13 +43,13 @@ const settingsTabs = computed<SidebarTabItem[]>(() => {
name: 'profile',
title: 'Profile',
description: 'Profile Settings', // Visibility, Avatar, Banner
- disabled: true || !userData.value,
+ disabled: dev || !userData.value,
},
{
name: 'server',
title: 'Server',
description: 'Server Settings', // Disable features
- disabled: true || (!userData.value && userData.value?.id !== 1),
+ disabled: dev || !userData.value || userData.value?.id !== 1,
},
];
});
diff --git a/routes/api.php b/routes/api.php
index 189a8617..a534494f 100755
--- a/routes/api.php
+++ b/routes/api.php
@@ -36,8 +36,8 @@ Route::group(['middleware' => ['auth:sanctum']], function () {
Route::delete('/logout', [AuthController::class, 'destroy']); // New
Route::prefix('settings')->group(function () {
- Route::put('/password', [PasswordController::class, 'update'])->name('password.update');
Route::get('/sessions', [SessionController::class, 'index'])->name('sessions.list');
+ Route::put('/password', [PasswordController::class, 'update'])->name('password.update');
Route::put('/email', [EmailController::class, 'update'])->name('email.update');
});
diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php
deleted file mode 100755
index 11219c6b..00000000
--- a/tests/Feature/ExampleTest.php
+++ /dev/null
@@ -1,17 +0,0 @@
-<?php
-
-namespace Tests\Feature;
-
-// use Illuminate\Foundation\Testing\RefreshDatabase;
-use Tests\TestCase;
-
-class ExampleTest extends TestCase {
- /**
- * A basic test example.
- */
- public function test_the_application_returns_a_successful_response(): void {
- $response = $this->get('/');
-
- $response->assertStatus(302);
- }
-}
diff --git a/tests/Feature/Settings/EmailControllerTest.php b/tests/Feature/Settings/EmailControllerTest.php
index bede0fe1..a94e0ce4 100644
--- a/tests/Feature/Settings/EmailControllerTest.php
+++ b/tests/Feature/Settings/EmailControllerTest.php
@@ -12,7 +12,7 @@ class EmailControllerTest extends TestCase {
private const CHANGE_EMAIL_ENDPOINT = '/api/settings/email';
- public function user_can_update_email_with_correct_password() {
+ public function test_user_can_update_email_with_correct_password() {
$user = User::factory()->create([
'email' => '[email protected]',
'password' => Hash::make('old-password'),
@@ -29,7 +29,7 @@ class EmailControllerTest extends TestCase {
$this->assertTrue($user->fresh()->email === '[email protected]');
}
- public function update_fails_with_incorrect_password() {
+ public function test_update_fails_with_incorrect_password() {
$user = User::factory()->create([
'email' => '[email protected]',
'password' => Hash::make('current-password'),
@@ -46,7 +46,7 @@ class EmailControllerTest extends TestCase {
$response->assertJsonValidationErrors('password');
}
- public function update_fails_if_email_exists() {
+ public function test_update_fails_if_email_exists() {
$testUser = $this->getFakeUser();
$otherUser = $this->getFakeUser();
@@ -71,7 +71,7 @@ class EmailControllerTest extends TestCase {
$response->assertJsonValidationErrors('email');
}
- public function update_fails_if_email_is_the_same() {
+ public function test_update_fails_if_email_is_the_same() {
$testUser = $this->getFakeUser();
$user = User::factory()->create([
diff --git a/tests/Feature/Settings/PasswordControllerTest.php b/tests/Feature/Settings/PasswordControllerTest.php
index 17edab94..1bfe23fc 100644
--- a/tests/Feature/Settings/PasswordControllerTest.php
+++ b/tests/Feature/Settings/PasswordControllerTest.php
@@ -12,7 +12,7 @@ class PasswordControllerTest extends TestCase {
private const CHANGE_PASSWORD_ENDPOINT = '/api/settings/password';
- public function user_can_update_password_with_correct_current_password() {
+ public function test_user_can_update_password_with_correct_current_password() {
$user = User::factory()->create([
'password' => Hash::make('old-password'),
]);
@@ -29,7 +29,7 @@ class PasswordControllerTest extends TestCase {
$this->assertTrue(Hash::check('new-secure-password', $user->fresh()->password));
}
- public function update_fails_with_incorrect_current_password() {
+ public function test_update_fails_with_incorrect_current_password() {
$user = User::factory()->create([
'password' => Hash::make('old-password'),
]);
@@ -46,7 +46,7 @@ class PasswordControllerTest extends TestCase {
$response->assertJsonValidationErrors('current_password');
}
- public function update_fails_if_passwords_do_not_match() {
+ public function test_update_fails_if_passwords_do_not_match() {
$user = User::factory()->create([
'password' => Hash::make('old-password'),
]);
@@ -63,7 +63,7 @@ class PasswordControllerTest extends TestCase {
$response->assertJsonValidationErrors('password');
}
- public function update_fails_if_password_does_not_meet_requirements() {
+ public function test_update_fails_if_password_does_not_meet_requirements() {
$user = User::factory()->create([
'password' => Hash::make('old-password'),
]);
diff --git a/tests/Feature/Settings/SessionControllerTest.php b/tests/Feature/Settings/SessionControllerTest.php
index 0302fcf1..b9d5fa4c 100644
--- a/tests/Feature/Settings/SessionControllerTest.php
+++ b/tests/Feature/Settings/SessionControllerTest.php
@@ -2,58 +2,63 @@
namespace Tests\Feature\Settings;
+use App\Http\Controllers\API\V1\SessionController;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;
+use Illuminate\Testing\TestResponse;
use Tests\TestCase;
class SessionControllerTest extends TestCase {
use RefreshDatabase;
- public function returns_sessions_for_authenticated_user_only() {
+ public function test_returns_sessions_for_authenticated_user_only() {
+ $baseSession = $this->getBaseSession();
$user = User::factory()->create();
$user2 = User::factory()->create();
- $this->actingAs($user);
+ $sessionId = Str::random(40);
// 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,
- ]
+ array_merge(['id' => $sessionId, 'user_id' => $user->id], $baseSession),
+ array_merge(['id' => Str::random(40), 'user_id' => $user2->id], $baseSession),
);
- // Set current session ID
- session()->setId($sessionId);
- session()->start();
+ // Create a request manually
+ $request = Request::create('/fake', 'GET', [], [
+ config('session.cookie') => $sessionId,
+ ]);
+ $request->setUserResolver(fn () => $user);
+ $request->setLaravelSession(app('session.store'));
+ app('session.store')->setId($sessionId);
+ app('session.store')->start();
- $response = $this->getJson('/api/settings/sessions');
+ $controller = new SessionController;
+ $response = TestResponse::fromBaseResponse($controller->index($request));
- $response->assertOk()
- ->assertJsonCount(1)
- ->assertJsonFragment([
- 'id' => $sessionId,
- 'ip_address' => '127.0.0.1',
- 'user_agent' => 'FakeAgent/1.0',
- 'is_current' => true,
- ]);
+ $response->assertOk();
+ $response->assertJsonCount(1);
+ $response->assertJsonFragment([
+ 'id' => $sessionId,
+ 'ip_address' => $baseSession['ip_address'],
+ 'user_agent' => $baseSession['user_agent'],
+ 'is_current' => true,
+ ]);
}
- public function unauthenticated_users_cannot_access_sessions() {
+ public function test_unauthenticated_users_cannot_access_sessions() {
$response = $this->getJson('/api/settings/sessions');
$response->assertUnauthorized(); // 401
}
+
+ private function getBaseSession(): array {
+ return [
+ 'ip_address' => '127.0.0.1',
+ 'user_agent' => 'FakeAgent/1.0',
+ 'payload' => '',
+ 'last_activity' => now()->timestamp,
+ ];
+ }
}
diff --git a/tests/Unit/ExampleTest.php b/tests/Unit/ExampleTest.php
deleted file mode 100755
index 7d80b3c7..00000000
--- a/tests/Unit/ExampleTest.php
+++ /dev/null
@@ -1,14 +0,0 @@
-<?php
-
-namespace Tests\Unit;
-
-use PHPUnit\Framework\TestCase;
-
-class ExampleTest extends TestCase {
- /**
- * A basic test example.
- */
- public function test_that_true_is_true(): void {
- $this->assertTrue(true);
- }
-}