Skip to content
Open
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
134 changes: 134 additions & 0 deletions app/Http/Controllers/ApplicationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -360,4 +360,138 @@ public function delete($id)
'message' => 'Application deleted',
], 200);
}

/**
* @OA\Patch(
* path="/apps/{id}/activate",
* tags={"Applications"},
* summary="Activate an application by ID",
* operationId="activateApplication",
* security={},
* deprecated=true,
* @OA\Parameter(
* name="id",
* in="path",
* required=true,
* description="ID of the application to activate",
* @OA\Schema(type="integer", format="int64")
* ),
* @OA\Response(
* response=200,
* description="Successful response",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="data", type="array", @OA\Items(type="object"))
* )
* )
* )
*/
public function activate($id)
{
try {
$application = $this->repo->find($id);
} catch (\Exception $e) {
Log::error('Application not found', ['message' => $e->getMessage()]);

return response()->json([
'status' => 404,
'error_message' => 'Application does not exist',
'errors' => ['No matching Application'],
], 404);
}

if ($application->tenant_id !== $this->tenantId) {
return response()->json([
'status' => 403,
'error_message' => 'Application does not belong to tenant',
'errors' => ['Application does not belong to tenant'],
], 403);
}

try {
$this->repo->updateWithIdAndInput($id, ['is_active' => true]);
} catch (\Exception $e) {
Log::error('Application not activated', ['message' => $e->getMessage()]);

return response()->json([
'status' => 500,
'error_message' => 'Unable to activate Application',
'errors' => [$e->getMessage()],
], 500);
}

$application = $this->repo->find($id);

$resource = new \League\Fractal\Resource\Item($application, new ApplicationTransformer());
$response = $this->manager->createData($resource);

return response()->json($response->toArray(), 200);
}

/**
* @OA\Patch(
* path="/apps/{id}/deactivate",
* tags={"Applications"},
* summary="Deactivate an application by ID",
* operationId="deactivateApplication",
* security={},
* deprecated=true,
* @OA\Parameter(
* name="id",
* in="path",
* required=true,
* description="ID of the application to deactivate",
* @OA\Schema(type="integer", format="int64")
* ),
* @OA\Response(
* response=200,
* description="Successful response",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="data", type="array", @OA\Items(type="object"))
* )
* )
* )
*/
public function deactivate($id)
{
try {
$application = $this->repo->find($id);
} catch (\Exception $e) {
Log::error('Application not found', ['message' => $e->getMessage()]);

return response()->json([
'status' => 404,
'error_message' => 'Application does not exist',
'errors' => ['No matching Application'],
], 404);
}

if ($application->tenant_id !== $this->tenantId) {
return response()->json([
'status' => 403,
'error_message' => 'Application does not belong to tenant',
'errors' => ['Application does not belong to tenant'],
], 403);
}

try {
$this->repo->updateWithIdAndInput($id, ['is_active' => false]);
} catch (\Exception $e) {
Log::error('Application not deactivated', ['message' => $e->getMessage()]);

return response()->json([
'status' => 500,
'error_message' => 'Unable to deactivate Application',
'errors' => [$e->getMessage()],
], 500);
}

$application = $this->repo->find($id);

$resource = new \League\Fractal\Resource\Item($application, new ApplicationTransformer());
$response = $this->manager->createData($resource);

return response()->json($response->toArray(), 200);
}
}
45 changes: 31 additions & 14 deletions app/Http/Middleware/ApiAuthMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use App\Models\UsageLog;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Log;

class ApiAuthMiddleware extends BasicAuthMiddleware
{
Expand All @@ -19,22 +18,40 @@ class ApiAuthMiddleware extends BasicAuthMiddleware
*/
public function handle($request, Closure $next)
{
$application = Application::where('key', '=', $request->header('x-api-key'))->first();
$apiKey = $request->header('x-api-key');
$authHeader = $request->header('Authorization');
$isBasicAuth = $authHeader && str_starts_with($authHeader, 'Basic ');

if (! $application) {
if (!$apiKey && !$isBasicAuth) {
return response()->json(['error' => 'Authentication required. Provide API key or Basic auth'], 401);
}

if ($isBasicAuth) {
return parent::handle($request, $next);
}
$usageLog = new UsageLog;
$usageLog->application_id = $application->id;
$usageLog->method = $request->method();
$usageLog->endpoint = $request->path();
$usageLog->timestamp = Carbon::now()->toDateTimeString();
$usageLog->code_status = 200;
$usageLog->language = $request->input('language', false) ? $request->input('language', null) : $request->header('Accept-Language', null);
$usageLog->subnational = $request->input('subnational', null);
$usageLog->event_type = $request->input('eventType', null);
$usageLog->save();
$request->usageLog=$usageLog;

if ($apiKey) {
$application = Application::where('key', '=', $apiKey)->first();

if (!$application) {
return response()->json(['error' => 'Invalid API key'], 401);
}

if (!$application->is_active) {
return response()->json(['error' => 'Application is inactive'], 403);
}
$usageLog = new UsageLog;
$usageLog->application_id = $application->id;
$usageLog->method = $request->method();
$usageLog->endpoint = $request->path();
$usageLog->timestamp = Carbon::now()->toDateTimeString();
$usageLog->code_status = 200;
$usageLog->language = $request->input('language', false) ? $request->input('language', null) : $request->header('Accept-Language', null);
$usageLog->subnational = $request->input('subnational', null);
$usageLog->event_type = $request->input('eventType', null);
$usageLog->save();
$request->usageLog = $usageLog;
}

return $next($request);
}
Expand Down
25 changes: 23 additions & 2 deletions app/Models/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Application extends Model
*/
protected $table = 'applications';

public $timestamps = false;
public $timestamps = true;

/**
* The attributes that are mass assignable.
Expand All @@ -30,10 +30,31 @@ class Application extends Model
'description',
'estimated_users_count',
'key',
'is_active',
];

protected $dates = ['deleted_at'];

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'is_active' => 'boolean',
];

/**
* Scope to get only active applications
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('is_active', true);
}

/**
* A sure method to generate a unique API key
*
Expand All @@ -42,7 +63,7 @@ class Application extends Model
public static function generateKey()
{
do {
$newKey = str_random(32);
$newKey = \Illuminate\Support\Str::random(32);
} // Already in the DB? Fail. Try again
while (self::keyExists($newKey));

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

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

class AddIsActiveToAplicationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('applications', function (Blueprint $table) {
$table->boolean('is_active')->default(true)->after('key');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table) {
$table->dropColumn('is_active');
});
}
}
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"sass": "^1.15.2",
"sass-loader": "^7.1.0",
"vue-template-compiler": "^2.7.16"
},
"overrides": {
"cipher-base": "^1.0.5",
"sha.js": "^2.4.12"
}
}
8 changes: 7 additions & 1 deletion routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@
Route::delete('apps/{id}', 'ApplicationController@delete');
Route::patch('apps/{id}', 'ApplicationController@update');

// Rutas adicionales para manejar el estado activo/inactivo
Route::patch('apps/{id}/activate', 'ApplicationController@activate');
Route::patch('apps/{id}/deactivate', 'ApplicationController@deactivate');
Route::get('admin/apps', 'ApplicationController@getAllForAdmin');

// Usage log endpoints
Route::get('usage/applications', 'UsageLogController@getApplicationLogs');
Route::get('usage/endpoints', 'UsageLogController@getEndpointLogs');
Expand Down Expand Up @@ -95,4 +100,5 @@
'error' => 'API version v1 is no longer supported. Please use /v2/.'
], 410);
})->where('any', '.*');
});
});