Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions app/Http/Controllers/Settings/ApiKeyController.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,32 @@ public function destroy(Request $request): RedirectResponse

return redirect()->route('api-keys.edit')->with('success', 'API key deleted successfully.');
}

/**
* Store the OpenAI API key (used by onboarding)
*/
public function store(Request $request)
{
$request->validate([
'api_key' => ['required', 'string', 'min:20'],
]);

$apiKey = $request->input('api_key');

// Validate the API key
if (!$this->apiKeyService->validateApiKey($apiKey)) {
return response()->json([
'success' => false,
'message' => 'The provided API key is invalid. Please check and try again.',
], 422);
}

// Store the API key
$this->apiKeyService->setApiKey($apiKey);

return response()->json([
'success' => true,
'message' => 'API key saved successfully.',
]);
}
}
57 changes: 57 additions & 0 deletions app/Http/Middleware/CheckOnboarding.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace App\Http\Middleware;

use App\Services\ApiKeyService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckOnboarding
{
protected ApiKeyService $apiKeyService;

public function __construct(ApiKeyService $apiKeyService)
{
$this->apiKeyService = $apiKeyService;
}

/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
// Routes that should be accessible without API key
$excludedRoutes = [
'onboarding',
'api-keys.edit',
'api-keys.update',
'api-keys.destroy',
'api.openai.status',
'api.openai.api-key.store',
'appearance',
];

// Skip check for excluded routes
if ($request->route() && in_array($request->route()->getName(), $excludedRoutes)) {
return $next($request);
}

// Skip if API request (they handle their own errors)
if ($request->is('api/*')) {
return $next($request);
}

// Check if API key exists
if (!$this->apiKeyService->hasApiKey()) {
// If not on onboarding page and no API key, redirect to onboarding
if ($request->route() && $request->route()->getName() !== 'onboarding') {
return redirect()->route('onboarding');
}
}

return $next($request);
}
}
2 changes: 2 additions & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use App\Http\Middleware\CheckOnboarding;
use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
use Illuminate\Foundation\Application;
Expand All @@ -17,6 +18,7 @@
$middleware->encryptCookies(except: ['appearance', 'sidebar_state']);

$middleware->web(append: [
CheckOnboarding::class,
HandleAppearance::class,
HandleInertiaRequests::class,
AddLinkHeadersForPreloadedAssets::class,
Expand Down
292 changes: 292 additions & 0 deletions resources/js/pages/Onboarding.vue

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion resources/js/pages/RealtimeAgent/Main.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2657,7 +2657,7 @@ onMounted(async () => {
try {
const response = await axios.get('/api/openai/status');
hasApiKey.value = response.data.hasApiKey;

if (!hasApiKey.value) {
// Redirect to settings page if no API key
window.location.href = '/settings/api-keys';
Expand Down
2 changes: 1 addition & 1 deletion resources/js/pages/Welcome.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Head, Link } from '@inertiajs/vue3';
import { Head } from '@inertiajs/vue3';
</script>

<template>
Expand Down
5 changes: 4 additions & 1 deletion resources/js/pages/settings/ApiKeys.vue
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,10 @@ const deleteApiKey = () => {
</p>
</div>

<div v-if="form.errors.openai_api_key" class="flex items-center gap-2 rounded-md border border-red-500 bg-red-50 p-3 text-sm text-red-800 dark:border-red-700 dark:bg-red-950 dark:text-red-200">
<div
v-if="form.errors.openai_api_key"
class="flex items-center gap-2 rounded-md border border-red-500 bg-red-50 p-3 text-sm text-red-800 dark:border-red-700 dark:bg-red-950 dark:text-red-200"
>
<AlertCircle class="h-4 w-4" />
<span>{{ form.errors.openai_api_key }}</span>
</div>
Expand Down
3 changes: 3 additions & 0 deletions routes/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
Route::put('settings/api-keys', [ApiKeyController::class, 'update'])->name('api-keys.update');
Route::delete('settings/api-keys', [ApiKeyController::class, 'destroy'])->name('api-keys.destroy');

// API endpoint for saving API key (used by onboarding)
Route::post('/api/openai/api-key', [ApiKeyController::class, 'store'])->name('api.openai.api-key.store');

Route::get('settings/appearance', function () {
return Inertia::render('settings/Appearance');
})->name('appearance');
Expand Down
20 changes: 20 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
return Inertia::render('Welcome');
})->name('home');

// Onboarding Route
Route::get('/onboarding', function () {
return Inertia::render('Onboarding');
})->name('onboarding');

Route::get('dashboard', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
Expand All @@ -40,6 +45,21 @@
]);
})->name('api.openai.status');

// Open external URL in default browser (for NativePHP)
Route::post('/api/open-external', function (\Illuminate\Http\Request $request) {
$url = $request->input('url');

// Validate URL
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return response()->json(['error' => 'Invalid URL'], 400);
}

// Use NativePHP Shell to open in default browser
\Native\Laravel\Facades\Shell::openExternal($url);

return response()->json(['success' => true]);
})->name('api.open-external');

// Template Routes
Route::get('/templates', [\App\Http\Controllers\TemplateController::class, 'index'])
->name('templates.index');
Expand Down
146 changes: 146 additions & 0 deletions tests/Feature/ApiKeyStoreTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
<?php

namespace Tests\Feature;

use App\Services\ApiKeyService;
use Mockery;
use Tests\TestCase;

class ApiKeyStoreTest extends TestCase
{

protected function setUp(): void
{
parent::setUp();
}

protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}

public function test_stores_valid_api_key_successfully(): void
{
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$validApiKey = 'sk-1234567890abcdef1234567890abcdef1234567890abcdef';

$mockApiKeyService->shouldReceive('validateApiKey')
->once()
->with($validApiKey)
->andReturn(true);

$mockApiKeyService->shouldReceive('setApiKey')
->once()
->with($validApiKey);

$response = $this->postJson('/api/openai/api-key', [
'api_key' => $validApiKey
]);

$response->assertStatus(200)
->assertJson([
'success' => true,
'message' => 'API key saved successfully.'
]);
}

public function test_rejects_invalid_api_key(): void
{
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$invalidApiKey = 'sk-1234567890abcdef1234567890abcdef1234567890invalid';

$mockApiKeyService->shouldReceive('validateApiKey')
->once()
->with($invalidApiKey)
->andReturn(false);

$mockApiKeyService->shouldNotReceive('setApiKey');

$response = $this->postJson('/api/openai/api-key', [
'api_key' => $invalidApiKey
]);

$response->assertStatus(422)
->assertJson([
'success' => false,
'message' => 'The provided API key is invalid. Please check and try again.'
]);
}

public function test_validates_required_api_key_field(): void
{
$response = $this->postJson('/api/openai/api-key', []);

$response->assertStatus(422)
->assertJsonValidationErrors(['api_key']);
}

public function test_validates_api_key_minimum_length(): void
{
$response = $this->postJson('/api/openai/api-key', [
'api_key' => 'sk-short'
]);

$response->assertStatus(422)
->assertJsonValidationErrors(['api_key']);
}

public function test_validates_api_key_is_string(): void
{
$response = $this->postJson('/api/openai/api-key', [
'api_key' => 123456
]);

$response->assertStatus(422)
->assertJsonValidationErrors(['api_key']);
}

public function test_handles_api_key_service_exception(): void
{
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$validApiKey = 'sk-1234567890abcdef1234567890abcdef1234567890abcdef';

$mockApiKeyService->shouldReceive('validateApiKey')
->once()
->with($validApiKey)
->andThrow(new \Exception('Service error'));

$response = $this->postJson('/api/openai/api-key', [
'api_key' => $validApiKey
]);

// Controller doesn't handle exceptions, so it returns 500
$response->assertStatus(500);
}

public function test_api_key_endpoint_accessible_without_existing_api_key(): void
{
// This test ensures the middleware allows access to the API key store endpoint
// even when no API key is configured

$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$validApiKey = 'sk-1234567890abcdef1234567890abcdef1234567890abcdef';

$mockApiKeyService->shouldReceive('validateApiKey')
->once()
->andReturn(true);

$mockApiKeyService->shouldReceive('setApiKey')
->once();

$response = $this->postJson('/api/openai/api-key', [
'api_key' => $validApiKey
]);

$response->assertStatus(200);
}
}
6 changes: 6 additions & 0 deletions tests/Feature/Controllers/ConversationControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
use App\Models\ConversationSession;
use App\Models\ConversationTranscript;
use App\Models\ConversationInsight;
use App\Services\ApiKeyService;

beforeEach(function () {
// Mock API key service to return true (API key exists) for all conversation tests
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$mockApiKeyService->shouldReceive('hasApiKey')->andReturn(true);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

// Create a test conversation session for some tests
$this->session = ConversationSession::create([
'user_id' => null,
Expand Down
12 changes: 12 additions & 0 deletions tests/Feature/DashboardTest.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
<?php

use App\Services\ApiKeyService;

test('dashboard page is accessible', function () {
// Mock API key service to return true (API key exists)
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$mockApiKeyService->shouldReceive('hasApiKey')->andReturn(true);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$response = $this->get('/dashboard');
$response->assertStatus(200);
});

test('realtime agent page is accessible', function () {
// Mock API key service to return true (API key exists)
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$mockApiKeyService->shouldReceive('hasApiKey')->andReturn(true);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$response = $this->get('/realtime-agent');
$response->assertStatus(200);
});
7 changes: 7 additions & 0 deletions tests/Feature/ExampleTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
<?php

use App\Services\ApiKeyService;

it('returns a successful response', function () {
// Mock API key service to return true (API key exists)
$mockApiKeyService = Mockery::mock(ApiKeyService::class);
$mockApiKeyService->shouldReceive('hasApiKey')->andReturn(true);
$this->app->instance(ApiKeyService::class, $mockApiKeyService);

$response = $this->get('/');

$response->assertStatus(200);
Expand Down
Loading