47 lines
1.5 KiB
PHP
47 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\V2;
|
|
|
|
use App\Enums\ApiError;
|
|
use App\Exceptions\Api\V2\ApiErrorException;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Lib\Helper;
|
|
use App\Models\Service;
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class ApiController extends Controller
|
|
{
|
|
public function ping()
|
|
{
|
|
return response()->json();
|
|
}
|
|
|
|
public function authenticate(Request $request)
|
|
{
|
|
$bearerToken = null;
|
|
try {
|
|
$bearerToken = Helper::getBearerTokenFromRequest($request);
|
|
if (!$bearerToken) {
|
|
Log::debug('authenticate: missing bearerToken');
|
|
throw new ApiErrorException(ApiError::missingParameter());
|
|
}
|
|
/** @var \App\Models\Service */
|
|
$service = Service::getFromBearerToken($bearerToken);
|
|
} catch (ModelNotFoundException $e) {
|
|
$bearerToken = Hash::make($bearerToken);
|
|
Log::debug("authenticate: service not found $bearerToken");
|
|
throw new ApiErrorException(ApiError::apiAuthFailed());
|
|
}
|
|
if (!Hash::check($request->bearer_pwd, $service->bearer_pwd)) {
|
|
Log::debug('authenticate: wrong credentials');
|
|
throw new ApiErrorException(ApiError::apiAuthFailed());
|
|
}
|
|
|
|
$apiToken = $service->generateApiToken();
|
|
$service->saveOrFail();
|
|
return response()->json(['api_token' => $apiToken]);
|
|
}
|
|
}
|