94 lines
2.3 KiB
PHP
94 lines
2.3 KiB
PHP
<?php
|
|
|
|
use App\Http\Resources\SessionResource;
|
|
use App\Models\User;
|
|
use App\Repositories\Session\SessionRepository;
|
|
use Carbon\Carbon;
|
|
use Facades\Tests\Setup\UserFactory;
|
|
use Illuminate\Support\Str;
|
|
use Tests\Feature\ApiTestCase;
|
|
|
|
beforeEach(function () {
|
|
config(['session.driver' => 'database']);
|
|
});
|
|
|
|
test('unauthenticated', function () {
|
|
$user = User::factory()->create();
|
|
|
|
$session = createSession($user);
|
|
|
|
$this->getJson("/api/sessions/{$session->id}")
|
|
->assertStatus(401);
|
|
});
|
|
|
|
test('get session which belongs to other user', function () {
|
|
$this->login();
|
|
|
|
$user2 = User::factory()->create();
|
|
|
|
$session = createSession($user2);
|
|
|
|
$this->getJson("/api/sessions/{$session->id}")
|
|
->assertStatus(403);
|
|
});
|
|
|
|
test('get session', function () {
|
|
$user = $this->login();
|
|
|
|
$session = createSession($user);
|
|
|
|
$this->getJson("/api/sessions/{$session->id}")
|
|
->assertStatus(200)
|
|
->assertJson([
|
|
'data' => (new SessionResource($session))->resolve(),
|
|
]);
|
|
});
|
|
|
|
test('invalidate his own session', function () {
|
|
$user = $this->login();
|
|
|
|
$session = createSession($user);
|
|
|
|
$this->deleteJson("/api/sessions/{$session->id}")
|
|
->assertStatus(200)
|
|
->assertJson(['success' => true]);
|
|
});
|
|
|
|
test('invalidate session for other user', function () {
|
|
$user = UserFactory::withPermissions('users.manage')->create();
|
|
$user2 = User::factory()->create();
|
|
$session = createSession($user2);
|
|
|
|
$this->actingAs($user, ApiTestCase::API_GUARD)
|
|
->deleteJson("/api/sessions/{$session->id}")
|
|
->assertOk()
|
|
->assertJson(['success' => true]);
|
|
});
|
|
|
|
test('invalidate session for other user without permission', function () {
|
|
$this->login();
|
|
$user2 = User::factory()->create();
|
|
$session = createSession($user2);
|
|
|
|
$this->deleteJson("/api/sessions/{$session->id}")
|
|
->assertStatus(403);
|
|
});
|
|
|
|
function createSession(User $user)
|
|
{
|
|
$sessionId = Str::random(40);
|
|
|
|
$data = [
|
|
'id' => $sessionId,
|
|
'user_id' => $user->id,
|
|
'ip_address' => '127.0.0.1',
|
|
'user_agent' => 'foo',
|
|
'payload' => Str::random(),
|
|
'last_activity' => Carbon::now()->timestamp,
|
|
];
|
|
|
|
DB::table('sessions')->insert($data);
|
|
|
|
return app(SessionRepository::class)->find($sessionId);
|
|
}
|