50 lines
1.8 KiB
PHP
50 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use App\Models\Service;
|
|
use Carbon\Carbon;
|
|
use Exception;
|
|
use Illuminate\Http\Request;
|
|
|
|
class AuthenticationController extends Controller
|
|
{
|
|
/**
|
|
* Check if the signature is valid.
|
|
*
|
|
* @param Request $request
|
|
* @return boolean
|
|
* @throws Exception With message and error OR ENUM.
|
|
*/
|
|
public function check(Request $request)
|
|
{
|
|
if (!\is_string($request->timestamp) or !Carbon::hasFormat($request->timestamp, 'Y-m-d H:i:s')) {
|
|
throw new Exception('wrongTimeStamp 1', 151);
|
|
}
|
|
if (
|
|
Carbon::parse($request->timestamp, 'utc')
|
|
->isBefore(Carbon::now('UTC')->subSeconds(config('api.timestampTimeout', 10)))
|
|
) {
|
|
throw new Exception('wrongTimeStamp', 151);
|
|
}
|
|
$service = Service::where('bearer_token', $request->bearer_token)->firstOrFail();
|
|
// ! Hack to prevent Laravel to cast empty strings to null or the opposite.
|
|
// ! If cannot decode json user legacy all() method.
|
|
$data = \json_decode($request->getContent(), true);
|
|
$data = (\is_array($data) and \json_last_error() === \JSON_ERROR_NONE) ?
|
|
array_replace_recursive($request->all(), $data) : $request->all();
|
|
// Generate a hash with corrects datas.
|
|
$calculatedHash = ToolboxHelper::signRequest(
|
|
$service->bearer_pwd,
|
|
$request->getUri(),
|
|
$request->getMethod(),
|
|
$data
|
|
);
|
|
dump('hash : ' . $calculatedHash . ' : fin.
|
|
signature : ' . $request->signature . ' : fin.');
|
|
$result = \hash_equals($calculatedHash, $request->signature) ? 'ok' : 'non';
|
|
return $result;
|
|
}
|
|
}
|