added pargar
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\ConfigService;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class PargarAuth
|
||||
{
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if (! app(ConfigService::class)->isPargarAccounting()) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Pargar integration is disabled',
|
||||
'data' => null,
|
||||
], 503);
|
||||
}
|
||||
|
||||
$auth = $request->header('Authorization') ?? $request->header('pargar');
|
||||
$token = is_string($auth) ? trim(str_replace('Bearer ', '', $auth)) : '';
|
||||
|
||||
if ($token === '' || ! $this->tokenValid($token)) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Invalid credentials!',
|
||||
'data' => null,
|
||||
], 401);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
public static function issueToken(string $username): string
|
||||
{
|
||||
$token = bin2hex(random_bytes(32));
|
||||
Cache::put(self::cacheKey($token), $username, now()->addDay());
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public static function tokenValid(string $token): bool
|
||||
{
|
||||
$config = app(ConfigService::class);
|
||||
$static = trim($config->getString('pargar_api_token', ''));
|
||||
if ($static !== '' && hash_equals($static, $token)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return Cache::has(self::cacheKey($token));
|
||||
}
|
||||
|
||||
private static function cacheKey(string $token): string
|
||||
{
|
||||
return 'pargar_api_token:' . $token;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user