Skip to content

Commit

Permalink
Organize API static keys functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
Arman001011 committed Jan 11, 2025
1 parent 5483834 commit 0b7365a
Show file tree
Hide file tree
Showing 12 changed files with 367 additions and 1 deletion.
12 changes: 12 additions & 0 deletions app/Http/Controllers/Api/TestController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

class TestController extends Controller
{
public function index() {
return response()->json(['success' => true]);
}
}
27 changes: 27 additions & 0 deletions app/Http/Middleware/ApiStaticKeyMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ApiStaticKeyMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$apiKey = $request->header('X-STATIC-KEY');

// @todo change to model
if (!$apiKey || !\DB::table('api_static_keys')->where('key', $apiKey)->exists()) {
return response()->json(['message' => 'Unauthorized.'], 401);
}

return $next($request);
}
}
1 change: 1 addition & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"require": {
"php": "^8.2",
"laravel/framework": "^11.31",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.9"
},
"require-dev": {
Expand Down
66 changes: 65 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

83 changes: 83 additions & 0 deletions config/sanctum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

use Laravel\Sanctum\Sanctum;

return [

/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),

/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/

'guard' => ['web'],

/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/

'expiration' => null,

/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/

'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),

/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/

'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],

];
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
if (!Schema::hasTable('api_static_keys')) {
Schema::create('api_static_keys', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->timestamps();
});
}
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('api_static_keys');
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};
20 changes: 20 additions & 0 deletions database/seeders/ApiStaticKeysSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class ApiStaticKeysSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
\DB::table('api_static_keys')->insert([
['key' => 'static-key-1'],
['key' => 'static-key-2'],
]);
}
}
85 changes: 85 additions & 0 deletions postman_collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{
"info": {
"_postman_id": "cfeb0529-cc78-4bd1-8fd4-e322b2653986",
"name": "Organizations",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "40947894"
},
"item": [
{
"name": "Test",
"item": [
{
"name": "test",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "{{host}}/api/test",
"host": [
"{{host}}"
],
"path": [
"api",
"test"
]
}
},
"response": []
}
]
}
],
"auth": {
"type": "apikey",
"apikey": [
{
"key": "value",
"value": "static-key-1",
"type": "string"
},
{
"key": "key",
"value": "X-STATIC-KEY",
"type": "string"
}
]
},
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
}
],
"variable": [
{
"key": "host",
"value": "http://organizations.loc"
},
{
"key": "host_local",
"value": "http://organizations.loc",
"type": "string"
}
]
}
Loading

0 comments on commit 0b7365a

Please sign in to comment.