llmbackend/app/Http/Controllers/Api/AuthController.php
Jethro Lin c44c25d86f 4. [API 详细说明](#4-api-详细说明)
- [4.1 认证 API](#41-认证-api)
     - [4.1.1 获取访问令牌](#411-获取访问令牌)
   - [4.2 客户用户 API](#42-客户用户-api)
     - [4.2.1 发送提示词请求](#421-发送提示词请求)
   - [4.3 管理员 API](#43-管理员-api)
     - [4.3.1 LLM 提供商管理](#431-llm-提供商管理)
       - [4.3.1.1 新增 LLM 提供商](#4311-新增-llm-提供商)
       - [4.3.1.2 修改 LLM 提供商](#4312-修改-llm-提供商)
       - [4.3.1.3 删除 LLM 提供商](#4313-删除-llm-提供商)
       - [4.3.1.4 获取 LLM 提供商列表](#4314-获取-llm-提供商列表)
2024-12-04 12:01:56 +08:00

87 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Rules\ThrottleAuthToken;
use App\Services\Auth\TokenService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function __construct(
private readonly TokenService $tokenService
) {}
/**
* Get access token using auth token
*
* @param Request $request
* @return JsonResponse
*
* Request body:
* {
* "auth_token": "string"
* }
*
* Success response:
* {
* "access_token": "string",
* "expires_in": 3600
* }
*
* Error response:
* {
* "error": "error_code",
* "message": "错误描述"
* }
*/
public function getAccessToken(Request $request): JsonResponse
{
try {
$validated = $request->validate([
'auth_token' => [
'required',
'string',
'size:64',
new ThrottleAuthToken,
],
]);
$authToken = $this->tokenService->validateAuthToken($validated['auth_token']);
if (!$authToken) {
return response()->json([
'error' => 'invalid_auth_token',
'message' => '认证令牌无效。',
], 401);
}
$result = $this->tokenService->generateAccessToken($authToken);
return response()->json($result);
} catch (ValidationException $e) {
return response()->json([
'error' => 'invalid_request',
'message' => '请求参数缺失或格式错误。',
'details' => $e->errors(),
], 400);
} catch (\Exception $e) {
Log::error('Error generating access token', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return response()->json([
'error' => 'server_error',
'message' => '服务器内部错误。',
], 500);
}
}
}