Skip to content

Commit

Permalink
feat(middleware): add check admin middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
tikrack committed Jan 29, 2025
1 parent 8bfc959 commit 40b6276
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
32 changes: 32 additions & 0 deletions app/Http/Middleware/CheckAdminMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace App\Http\Middleware;

use App\Http\Trait\ApiResponseTrait;
use Closure;
use Illuminate\Http\Request;
use Laravel\Sanctum\PersonalAccessToken;
use Symfony\Component\HttpFoundation\Response;

class CheckAdminMiddleware
{
use ApiResponseTrait;
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$authHeader = $request->header('authorization');
$token = $authHeader && strlen($authHeader) > 7 ? substr($authHeader, 7) : null;
$personalAccessToken = $token ? PersonalAccessToken::findToken($token) : null;
$user = $personalAccessToken?->tokenable;

if ($user and $user?->getRoleNames()->toArray()[0] === "admin") {
return $next($request);
}else {
return $this->fail();
}
}
}
4 changes: 4 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
use App\Http\Controllers\Auth\AuthController;
use App\Http\Controllers\CodeController;
use App\Http\Controllers\InfoController;
use App\Http\Middleware\CheckAdminMiddleware;
use Illuminate\Support\Facades\Route;

Route::name('api.')->group(function () {
Route::prefix('v1')->name('v1.')->group(function () {
Route::post("test", function () {
echo "ok";
})->middleware(CheckAdminMiddleware::class);
Route::post('auth', [AuthController::class, 'auth'])->name('auth');
Route::post('verify', [AuthController::class, 'verify'])->name('verify');
Route::resource('code', CodeController::class)->except(['create', 'edit', 'store', 'destroy']);
Expand Down

0 comments on commit 40b6276

Please sign in to comment.