2021-03-14 10:45:42 +01:00
|
|
|
<?php
|
|
|
|
|
|
2021-07-28 14:18:47 +02:00
|
|
|
namespace App\Http\Controllers\Api\V2;
|
2021-03-14 10:45:42 +01:00
|
|
|
|
|
|
|
|
use App\Enums\ApiError;
|
2021-07-28 14:18:47 +02:00
|
|
|
use App\Exceptions\Api\V2\ApiErrorException;
|
2021-03-14 10:45:42 +01:00
|
|
|
use App\Http\Controllers\Controller;
|
2021-08-16 18:47:31 +02:00
|
|
|
use App\Lib\Helper;
|
2021-03-14 10:45:42 +01:00
|
|
|
use App\Models\Service;
|
|
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
|
|
|
use Illuminate\Http\Request;
|
2021-08-02 11:46:08 +02:00
|
|
|
use Illuminate\Support\Facades\Hash;
|
2021-03-14 10:45:42 +01:00
|
|
|
|
|
|
|
|
class ApiController extends Controller
|
|
|
|
|
{
|
|
|
|
|
public function ping()
|
|
|
|
|
{
|
|
|
|
|
return response()->json();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function authenticate(Request $request)
|
|
|
|
|
{
|
|
|
|
|
try {
|
2021-08-16 18:47:31 +02:00
|
|
|
$bearerToken = Helper::getBearerTokenFromRequest($request);
|
|
|
|
|
if (!$bearerToken) {
|
2021-08-16 16:31:15 +02:00
|
|
|
throw new ApiErrorException(ApiError::missingParameter());
|
|
|
|
|
}
|
2021-03-14 10:45:42 +01:00
|
|
|
/** @var \App\Models\Service */
|
2021-08-16 18:47:31 +02:00
|
|
|
$service = Service::getFromBearerToken($bearerToken);
|
2021-03-14 10:45:42 +01:00
|
|
|
} catch (ModelNotFoundException $e) {
|
2021-10-19 17:08:51 +02:00
|
|
|
throw new ApiErrorException(ApiError::apiAuthFailed());
|
2021-03-14 10:45:42 +01:00
|
|
|
}
|
2021-08-02 11:46:08 +02:00
|
|
|
if (!Hash::check($request->bearer_pwd, $service->bearer_pwd)) {
|
2021-10-19 17:08:51 +02:00
|
|
|
throw new ApiErrorException(ApiError::apiAuthFailed());
|
2021-08-02 11:46:08 +02:00
|
|
|
}
|
|
|
|
|
|
2021-08-09 17:35:28 +02:00
|
|
|
$apiToken = $service->generateApiToken();
|
2021-08-02 11:46:08 +02:00
|
|
|
$service->saveOrFail();
|
2021-08-09 17:35:28 +02:00
|
|
|
return response()->json(['api_token' => $apiToken]);
|
2021-03-14 10:45:42 +01:00
|
|
|
}
|
|
|
|
|
}
|