67 lines
1.8 KiB
PHP
67 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Constants\ErrorCode;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Services\Auth\TokenService;
|
|
use App\Traits\ApiResponse;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class AuthController extends Controller
|
|
{
|
|
use ApiResponse;
|
|
|
|
public function __construct(
|
|
private readonly TokenService $tokenService,
|
|
) {}
|
|
|
|
/**
|
|
* 获取访问令牌
|
|
*
|
|
* @param Request $request
|
|
* @return JsonResponse
|
|
*/
|
|
public function getAccessToken(Request $request): JsonResponse
|
|
{
|
|
try {
|
|
$validated = $request->validate([
|
|
'auth_token' => 'required|string|size:64',
|
|
]);
|
|
|
|
$result = $this->tokenService->generateAccessToken($validated['auth_token']);
|
|
|
|
return $this->success([
|
|
'access_token' => $result['token'],
|
|
'expires_at' => $result['expires_at'],
|
|
]);
|
|
|
|
} catch (ValidationException $e) {
|
|
return $this->error(
|
|
ErrorCode::VALIDATION_ERROR,
|
|
ErrorCode::getMessage(ErrorCode::VALIDATION_ERROR),
|
|
$e->errors()
|
|
);
|
|
} catch (\InvalidArgumentException $e) {
|
|
return $this->error(
|
|
ErrorCode::TOKEN_INVALID,
|
|
$e->getMessage()
|
|
);
|
|
} catch (\Exception $e) {
|
|
Log::error('Error generating access token', [
|
|
'error' => $e->getMessage(),
|
|
'trace' => $e->getTraceAsString(),
|
|
]);
|
|
|
|
return $this->error(
|
|
ErrorCode::SERVER_ERROR,
|
|
ErrorCode::getMessage(ErrorCode::SERVER_ERROR)
|
|
);
|
|
}
|
|
}
|
|
}
|