81 lines
2.3 KiB
PHP
81 lines
2.3 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,
|
|
) {}
|
|
|
|
/**
|
|
* 獲取訪問令牌
|
|
*/
|
|
public function getAccessToken(Request $request): JsonResponse
|
|
{
|
|
try {
|
|
$validated = $request->validate([
|
|
'auth_token' => 'required|string|size:64',
|
|
]);
|
|
|
|
$authTokenData = $this->tokenService->validateAuthToken($validated['auth_token']);
|
|
|
|
if (!$authTokenData) {
|
|
return $this->error(
|
|
ErrorCode::TOKEN_INVALID,
|
|
'認證令牌無效。'
|
|
);
|
|
}
|
|
|
|
if (now()->isAfter($authTokenData['expires_at'])) {
|
|
return $this->error(
|
|
ErrorCode::TOKEN_EXPIRED,
|
|
'認證令牌已過期,請重新獲取。'
|
|
);
|
|
}
|
|
|
|
$result = $this->tokenService->generateAccessToken($authTokenData);
|
|
|
|
return $this->success([
|
|
'access_token' => $result['access_token'],
|
|
'expires_in' => $result['expires_in'],
|
|
'token_type' => $result['token_type'],
|
|
]);
|
|
|
|
} catch (ValidationException $e) {
|
|
return $this->error(
|
|
ErrorCode::VALIDATION_ERROR,
|
|
ErrorCode::getMessage(ErrorCode::VALIDATION_ERROR),
|
|
$e->errors()
|
|
);
|
|
} catch (\InvalidArgumentException $e) {
|
|
return $this->error(
|
|
ErrorCode::TOKEN_EXPIRED,
|
|
$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)
|
|
);
|
|
}
|
|
}
|
|
}
|