Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions app/Models/ApiKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace App\Models;

use Database\Factories\ApiKeyFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[Fillable(['user_id', 'name', 'token_hash', 'last_used_at', 'revoked_at'])]
final class ApiKey extends Model
{
/** @use HasFactory<ApiKeyFactory> */
use HasFactory;

protected function casts(): array
{
return [
'last_used_at' => 'datetime',
'revoked_at' => 'datetime',
];
}

public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}

public function isRevoked(): bool
{
return $this->revoked_at !== null;
}
}
5 changes: 5 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,9 @@ public function conversionJobs(): HasMany
{
return $this->hasMany(ConversionJob::class);
}

public function apiKeys(): HasMany
{
return $this->hasMany(ApiKey::class);
}
}
33 changes: 33 additions & 0 deletions database/factories/ApiKeyFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\ApiKey;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
* @extends Factory<ApiKey>
*/
final class ApiKeyFactory extends Factory
{
protected $model = ApiKey::class;

public function definition(): array
{
return [
'user_id' => User::factory(),
'name' => $this->faker->words(2, true),
'token_hash' => hash('sha256', 'fc_'.$this->faker->unique()->regexify('[A-Za-z0-9]{64}')),
'last_used_at' => null,
'revoked_at' => null,
];
}

public function revoked(): static
{
return $this->state(fn () => ['revoked_at' => now()]);
}
}
22 changes: 22 additions & 0 deletions tests/Feature/Models/ApiKeyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

use App\Models\ApiKey;
use App\Models\User;

it('belongs api key to user', function () {
$user = User::factory()->create();
$apiKey = ApiKey::factory()->for($user)->create();

expect($apiKey->user->is($user))->toBeTrue();
expect($user->apiKeys()->first()->is($apiKey))->toBeTrue();
});

it('checks if api key is revoked', function () {
$active = ApiKey::factory()->create(['revoked_at' => null]);
$revoked = ApiKey::factory()->create(['revoked_at' => now()]);

expect($active->isRevoked())->toBeFalse();
expect($revoked->isRevoked())->toBeTrue();
});