Skip to content

Commit

Permalink
Completed the website.
Browse files Browse the repository at this point in the history
  • Loading branch information
3m1n3nc3 committed Aug 14, 2024
1 parent 7a80f72 commit 94c361a
Show file tree
Hide file tree
Showing 135 changed files with 1,826 additions and 1,265 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/.phpunit.cache
/node_modules
/**/*/dist
/**/*/.yarn
/**/*/.dist
/website/.vitepress/cache
/**/*/node_modules
/public/build
/public/hot
Expand Down
Binary file modified .yarn/install-state.gz
Binary file not shown.
Binary file modified app/.DS_Store
Binary file not shown.
6 changes: 3 additions & 3 deletions app/Http/Controllers/Auth/RegisteredUserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function store(Request $request)
public function createUser(Request $request)
{
$firstname = str($request->get('name'))->explode(' ')->first(null, $request->firstname);
$lastname = str($request->get('name'))->explode(' ')->last(fn ($n) => $n !== $firstname, $request->lastname);
$lastname = str($request->get('name'))->explode(' ')->last(fn($n) => $n !== $firstname, $request->lastname);

$user = User::create([
'role' => 'user',
Expand All @@ -76,7 +76,7 @@ public function setUserData(Request $request, User $user)
$dev = new DeviceDetector($request->userAgent());

$device = $dev->getBrandName()
? ($dev->getBrandName().$dev->getDeviceName())
? ($dev->getBrandName() . $dev->getDeviceName())
: $request->userAgent();

$user->save();
Expand Down Expand Up @@ -117,4 +117,4 @@ public function preflight($token)
'try_at' => $dateAdd->toDateTimeLocalString(),
]);
}
}
}
42 changes: 40 additions & 2 deletions app/Http/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,47 @@

namespace App\Http\Controllers;

use App\Helpers\Providers;
use App\Models\Log;
use App\Services\Trend;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
//
}
public function index(Request $request): \Illuminate\Http\Response
{
/** @var \App\Models\User $user */
$user = $request->user();

$userScope = fn($q) => $q->whereUserId($user->id);

$usage = Log::whereHas('apiKey', $userScope)->count();

$weeklyUsage = Log::whereHas('apiKey', $userScope)->whereBetween('created_at', [
now()->subWeek(),
now(),
])->count();

$dailyUsage = Log::whereHas('apiKey', $userScope)->whereBetween('created_at', [
now()->subDay(),
now(),
])->count();

$usageRate = (Log::whereHas('apiKey', $userScope)->count() / Log::count()) * 100;


return Providers::response()->success([
'data' => [
'usage' => $usage,
'dailyUsage' => $dailyUsage,
'weeklyUsage' => $weeklyUsage,
'totalKeys' => $user->apiKeys()->count(),
'usageRate' => round($usageRate, 2),
'usageTrend' => Trend::usageTrend($user->id, 6)
]
]);
}
}
19 changes: 16 additions & 3 deletions app/Http/Middleware/ApiAccessMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Helpers\Providers;
use App\Models\ApiKey;
use App\Models\Log;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
Expand Down Expand Up @@ -31,11 +32,11 @@ public function handle(Request $request, Closure $next): Response
}
}

if (!$request->hasHeader('X-Api-key')) {
if (!$request->hasHeader('X-Api-Key')) {
throw new AuthenticationException('Unauthorized. You do not have access to this resource.');
};

$key = ApiKey::where('key', $request->header('X-Api-key'))->first();
$key = ApiKey::where('key', $request->header('X-Api-Key'))->first();

if (!$key) {
throw new AuthenticationException('Unauthorized. Invalid API key.');
Expand All @@ -57,6 +58,18 @@ public function handle(Request $request, Closure $next): Response
RateLimiter::hit('api-access:' . $key->id);
}

$log = [
'endpoint' => parse_url($request->url(), PHP_URL_PATH),
'ip_address' => $request->ip(),
'api_key_id' => $key->id,
];

if ($request->route()->parameters) {
collect($request->route()->parameters)->last()->logs()->create($log);
} else {
Log::create($log);
}

return $response;
}
}
}
17 changes: 0 additions & 17 deletions app/Http/Middleware/EncryptCookies.php

This file was deleted.

17 changes: 0 additions & 17 deletions app/Http/Middleware/VerifyCsrfToken.php

This file was deleted.

8 changes: 7 additions & 1 deletion app/Models/City.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class City extends Model
{
Expand All @@ -23,6 +24,11 @@ public function resolveRouteBinding($value, $field = null)
->firstOrFail();
}

public function logs(): MorphMany
{
return $this->morphMany(Log::class, 'model');
}

/**
* Get the state that owns the Ward
*
Expand All @@ -32,4 +38,4 @@ public function state(): BelongsTo
{
return $this->belongsTo(State::class);
}
}
}
6 changes: 6 additions & 0 deletions app/Models/Lga.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class Lga extends Model
{
Expand All @@ -25,6 +26,11 @@ public function resolveRouteBinding($value, $field = null)
->firstOrFail();
}

public function logs(): MorphMany
{
return $this->morphMany(Log::class, 'model');
}

/**
* Get the state that owns the Ward
*
Expand Down
26 changes: 25 additions & 1 deletion app/Models/Log.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,32 @@

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class Log extends Model
{
use HasFactory;
}

/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'ip_address',
'api_key_id',
'endpoint',
];

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

public function model(): MorphTo
{
return $this->morphTo('model');
}
}
6 changes: 6 additions & 0 deletions app/Models/State.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;

/**
* @property Collection<int, Lga> $lgas
Expand Down Expand Up @@ -71,4 +72,9 @@ public function cities(): HasMany
{
return $this->hasMany(City::class);
}

public function logs(): MorphMany
{
return $this->morphMany(Log::class, 'model');
}
}
8 changes: 7 additions & 1 deletion app/Models/Unit.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class Unit extends Model
{
Expand Down Expand Up @@ -33,6 +34,11 @@ public function lga(): BelongsTo
return $this->belongsTo(Lga::class);
}

public function logs(): MorphMany
{
return $this->morphMany(Log::class, 'model');
}

/**
* Get the state that owns the Ward
*
Expand All @@ -52,4 +58,4 @@ public function ward(): BelongsTo
{
return $this->belongsTo(Ward::class);
}
}
}
6 changes: 6 additions & 0 deletions app/Models/Ward.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class Ward extends Model
{
Expand Down Expand Up @@ -34,6 +35,11 @@ public function lga(): BelongsTo
return $this->belongsTo(Lga::class);
}

public function logs(): MorphMany
{
return $this->morphMany(Log::class, 'model');
}

/**
* Get the state that owns the Ward
*
Expand Down
50 changes: 50 additions & 0 deletions app/Services/Trend.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Services;

use App\Models\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class Trend
{
/**
* Create a new class instance.
*/
public function __construct()
{
//
}

public static function usageTrend(int $userId, int $period = 6)
{
$months = [];
for ($i = 0; $i < 6; $i++) {
$months[] = now()->subMonths($period - 1)->addMonths($i)->format('Y-m');
}

// Fetch the logs for the last 6 months, grouped by month
$logsByMonth = Log::where('created_at', '>=', now()->subMonths($period))
->select(
DB::raw("strftime('%Y', created_at) as year"),
DB::raw("strftime('%m', created_at) as month"),
DB::raw('COUNT(*) as total_logs'),
DB::raw("SUM(CASE WHEN (select user_id from api_keys where logs.api_key_id = api_keys.id) = {$userId} THEN 1 ELSE 0 END) as user_logs")
)
->groupBy('year', 'month')
->orderBy('year', 'desc')
->get()->keyBy(function ($log) {
return sprintf('%04d-%02d', $log->year, $log->month);
});

// Calculate the usage rate per month
return collect($months)->map(function ($month) use ($logsByMonth) {
$log = $logsByMonth->get($month);

return [
'month' => Carbon::createFromFormat('Y-m', $month)->format('F Y'),
'usageRate' => round($log ? ($log->user_logs / $log->total_logs) * 100 : 0, 2),
];
});
}
}
9 changes: 5 additions & 4 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,10 @@
Request::HEADER_X_FORWARDED_AWS_ELB
);

$middleware->web(prepend: [
\App\Http\Middleware\EncryptCookies::class,
\App\Http\Middleware\VerifyCsrfToken::class,
$middleware->validateCsrfTokens(except: [
'api/*',
'api.*',
'portal/*',
]);

$middleware->api(append: [
Expand All @@ -77,4 +78,4 @@
return (new ExceptionHandler())->render($request, $e);
});
}
})->create();
})->create();
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,4 @@
},
"minimum-stability": "stable",
"prefer-stable": true
}
}
Loading

0 comments on commit 94c361a

Please sign in to comment.