feat: delete old controllers, add API tests, ApiKeys page, MCP route
- Remove old root-level controllers (moved to App/ namespace) - Remove old routes/settings.php (merged into routes/app.php) - Add routes/mcp.php placeholder for future MCP server - Add settings/ApiKeys.vue page with create/delete/copy token - Add API Keys nav item to settings layout - Add 26 API endpoint tests (auth, hashtags, labels, api-keys, workspace) - Add ApiToken factory - All 710 tests passing
This commit is contained in:
parent
6964cc8e6e
commit
298360c305
21 changed files with 959 additions and 1446 deletions
|
|
@ -1,150 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
|
||||
|
||||
class BillingController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the subscription selection page for new users.
|
||||
*/
|
||||
public function subscribe(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
// If already subscribed, redirect to billing
|
||||
if ($user->subscribed('default')) {
|
||||
return redirect()->route('billing.index');
|
||||
}
|
||||
|
||||
return Inertia::render('billing/Subscribe', [
|
||||
'trialDays' => config('cashier.trial_days'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the billing dashboard.
|
||||
*/
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
$subscription = $user->subscription('default');
|
||||
|
||||
return Inertia::render('billing/Index', [
|
||||
'hasSubscription' => $user->subscribed('default'),
|
||||
'onTrial' => $subscription?->onTrial() ?? false,
|
||||
'trialEndsAt' => $subscription?->trial_ends_at?->toFormattedDateString(),
|
||||
'subscription' => $subscription?->only([
|
||||
'stripe_status',
|
||||
'quantity',
|
||||
'ends_at',
|
||||
]),
|
||||
'workspacesCount' => $user->ownedWorkspacesCount(),
|
||||
'invoices' => $user->invoices()->map(fn ($invoice) => [
|
||||
'id' => $invoice->id,
|
||||
'date' => $invoice->date()->toFormattedDateString(),
|
||||
'total' => $invoice->total(),
|
||||
'status' => $invoice->status,
|
||||
'invoice_pdf' => $invoice->invoice_pdf,
|
||||
]),
|
||||
'defaultPaymentMethod' => $user->defaultPaymentMethod()?->card?->only([
|
||||
'brand',
|
||||
'last4',
|
||||
'exp_month',
|
||||
'exp_year',
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Stripe Checkout session for new subscription with trial.
|
||||
*/
|
||||
public function checkout(Request $request): SymfonyResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
$subscription = $user->newSubscription('default', config('cashier.plans.monthly.price_id'))
|
||||
->allowPromotionCodes()
|
||||
->trialDays(config('cashier.trial_days'))
|
||||
->quantity(1);
|
||||
|
||||
$checkoutSession = $subscription->checkout([
|
||||
'success_url' => route('billing.processing').'?status=success',
|
||||
'cancel_url' => route('billing.processing').'?status=cancelled',
|
||||
]);
|
||||
|
||||
return Inertia::location($checkoutSession->url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the checkout processing page.
|
||||
*/
|
||||
public function processing(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$status = $request->query('status', 'processing');
|
||||
|
||||
// If already subscribed, redirect to calendar
|
||||
if ($user->subscribed('default')) {
|
||||
return redirect()->route('calendar');
|
||||
}
|
||||
|
||||
// Validate status
|
||||
if (! in_array($status, ['processing', 'success', 'cancelled'])) {
|
||||
$status = 'processing';
|
||||
}
|
||||
|
||||
return Inertia::render('billing/Processing', [
|
||||
'userId' => $user->id,
|
||||
'status' => $status,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect to Stripe Customer Portal.
|
||||
*/
|
||||
public function portal(Request $request): RedirectResponse
|
||||
{
|
||||
return $request->user()->redirectToBillingPortal(
|
||||
route('billing.index')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a workspace to subscription (increment quantity).
|
||||
*/
|
||||
public function addWorkspace(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if (! $user->subscribed('default')) {
|
||||
return redirect()->route('billing.index')
|
||||
->withErrors(['subscription' => 'You need an active subscription.']);
|
||||
}
|
||||
|
||||
$user->incrementWorkspaceQuantity();
|
||||
|
||||
return back()->with('success', 'Workspace added to subscription.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a workspace from subscription (decrement quantity).
|
||||
*/
|
||||
public function removeWorkspace(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if (! $user->subscribed('default')) {
|
||||
return back();
|
||||
}
|
||||
|
||||
$user->decrementWorkspaceQuantity();
|
||||
|
||||
return back()->with('success', 'Workspace removed from subscription.');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\StoreChunkedMediaRequest;
|
||||
use App\Http\Requests\StoreMediaRequest;
|
||||
use App\Models\Media;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class MediaController extends Controller
|
||||
{
|
||||
public function store(StoreMediaRequest $request): JsonResponse
|
||||
{
|
||||
$model = $this->resolveModel($request->input('model'), $request->input('model_id'));
|
||||
$collection = $request->input('collection', 'default');
|
||||
|
||||
$media = $model->addMedia(
|
||||
$request->file('media'),
|
||||
$collection
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'id' => $media->id,
|
||||
'group_id' => $media->group_id,
|
||||
'url' => $media->url,
|
||||
'type' => $media->type->value,
|
||||
'original_filename' => $media->original_filename,
|
||||
]);
|
||||
}
|
||||
|
||||
public function storeChunked(StoreChunkedMediaRequest $request): JsonResponse
|
||||
{
|
||||
$tempFile = $this->chunkTempPath($request->chunkIdentifier());
|
||||
|
||||
$this->appendChunk($tempFile, $request->getContent(), $request->isFirstChunk());
|
||||
|
||||
if (! $request->isLastChunk()) {
|
||||
return response()->json([
|
||||
'done' => false,
|
||||
'progress' => $request->progress(),
|
||||
]);
|
||||
}
|
||||
|
||||
$model = $this->resolveModel($request->input('model'), $request->input('model_id'));
|
||||
|
||||
$media = $model->addMediaFromPath(
|
||||
$tempFile,
|
||||
$request->input('file_name'),
|
||||
$request->input('collection'),
|
||||
);
|
||||
|
||||
@unlink($tempFile);
|
||||
|
||||
return response()->json([
|
||||
'done' => true,
|
||||
'id' => $media->id,
|
||||
'group_id' => $media->group_id,
|
||||
'url' => $media->url,
|
||||
'type' => $media->type->value,
|
||||
'original_filename' => $media->original_filename,
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(string $modelId, Media $media): JsonResponse
|
||||
{
|
||||
if ($media->mediable_id !== $modelId) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$media->delete();
|
||||
|
||||
return response()->json(['success' => true]);
|
||||
}
|
||||
|
||||
public function reorder(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'media' => 'required|array',
|
||||
'media.*.id' => 'required|exists:medias,id',
|
||||
'media.*.order' => 'required|integer|min:0',
|
||||
]);
|
||||
|
||||
foreach ($request->input('media') as $item) {
|
||||
Media::where('id', $item['id'])->update(['order' => $item['order']]);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true]);
|
||||
}
|
||||
|
||||
public function duplicate(Media $media, Request $request): JsonResponse
|
||||
{
|
||||
$targets = $request->input('targets', []);
|
||||
|
||||
$duplicates = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$model = $this->resolveModel($target['model'], $target['model_id']);
|
||||
$collection = $target['collection'] ?? $media->collection;
|
||||
|
||||
$duplicate = $model->media()->create([
|
||||
'group_id' => $media->group_id,
|
||||
'collection' => $collection,
|
||||
'type' => $media->type,
|
||||
'path' => $media->path,
|
||||
'original_filename' => $media->original_filename,
|
||||
'mime_type' => $media->mime_type,
|
||||
'size' => $media->size,
|
||||
'order' => $media->order,
|
||||
'meta' => $media->meta,
|
||||
]);
|
||||
|
||||
$duplicates[] = [
|
||||
'id' => $duplicate->id,
|
||||
'group_id' => $duplicate->group_id,
|
||||
'mediable_id' => $duplicate->mediable_id,
|
||||
'mediable_type' => $duplicate->mediable_type,
|
||||
'url' => $duplicate->url,
|
||||
'type' => $duplicate->type->value,
|
||||
'original_filename' => $duplicate->original_filename,
|
||||
];
|
||||
}
|
||||
|
||||
return response()->json($duplicates);
|
||||
}
|
||||
|
||||
private function resolveModel(string $alias, string $id): Model
|
||||
{
|
||||
$modelClass = Relation::getMorphedModel($alias) ?? $alias;
|
||||
|
||||
return $modelClass::findOrFail($id);
|
||||
}
|
||||
|
||||
private function chunkTempPath(string $identifier): string
|
||||
{
|
||||
return storage_path("app/private/chunks/{$identifier}");
|
||||
}
|
||||
|
||||
private function appendChunk(string $path, string $content, bool $isFirst): void
|
||||
{
|
||||
$directory = dirname($path);
|
||||
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0755, true);
|
||||
}
|
||||
|
||||
file_put_contents($path, $content, $isFirst ? 0 : FILE_APPEND);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\User\Persona;
|
||||
use App\Enums\User\Setup;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
|
||||
|
||||
class OnboardingController extends Controller
|
||||
{
|
||||
/**
|
||||
* Step 1: Select persona (user type).
|
||||
*/
|
||||
public function step1(): Response
|
||||
{
|
||||
return Inertia::render('onboarding/Step1', [
|
||||
'personas' => Persona::toSelectArray(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store step 1 and proceed to step 2.
|
||||
*/
|
||||
public function storeStep1(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'persona' => ['required', Rule::enum(Persona::class)],
|
||||
]);
|
||||
|
||||
$request->user()->update([
|
||||
'persona' => $validated['persona'],
|
||||
'setup' => Setup::Connections,
|
||||
]);
|
||||
|
||||
return redirect()->route('onboarding.step2');
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 2: Connect social accounts.
|
||||
*/
|
||||
public function step2(Request $request): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
$workspace = $user->currentWorkspace;
|
||||
|
||||
$platforms = collect();
|
||||
|
||||
if ($workspace) {
|
||||
$connectedAccounts = $workspace->socialAccounts;
|
||||
|
||||
$platforms = collect(SocialPlatform::enabled())->map(function ($platform) use ($connectedAccounts) {
|
||||
$connected = $connectedAccounts->firstWhere('platform', $platform);
|
||||
|
||||
return [
|
||||
'value' => $platform->value,
|
||||
'label' => $platform->label(),
|
||||
'color' => $platform->color(),
|
||||
'connected' => $connected !== null,
|
||||
'account' => $connected,
|
||||
];
|
||||
})->values();
|
||||
}
|
||||
|
||||
return Inertia::render('onboarding/Step2', [
|
||||
'platforms' => $platforms,
|
||||
'hasWorkspace' => $workspace !== null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store step 2 and redirect to Stripe checkout (or complete if self-hosted).
|
||||
*/
|
||||
public function storeStep2(Request $request): SymfonyResponse|RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
// Skip payment for self-hosted mode
|
||||
if (config('trypost.self_hosted')) {
|
||||
$user->update([
|
||||
'setup' => Setup::Completed,
|
||||
]);
|
||||
|
||||
session()->flash('flash.banner', __('auth.flash.welcome'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('calendar');
|
||||
}
|
||||
|
||||
$user->update([
|
||||
'setup' => Setup::Subscription,
|
||||
]);
|
||||
|
||||
// Redirect to Stripe checkout
|
||||
$subscription = $user->newSubscription('default', config('cashier.plans.monthly.price_id'))
|
||||
->allowPromotionCodes()
|
||||
->trialDays(config('cashier.trial_days'))
|
||||
->quantity(1);
|
||||
|
||||
$checkoutSession = $subscription->checkout([
|
||||
'success_url' => route('onboarding.complete').'?session_id={CHECKOUT_SESSION_ID}',
|
||||
'cancel_url' => route('onboarding.step2'),
|
||||
]);
|
||||
|
||||
return Inertia::location($checkoutSession->url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete onboarding after successful Stripe checkout.
|
||||
*/
|
||||
public function complete(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
$user->update([
|
||||
'setup' => Setup::Completed,
|
||||
]);
|
||||
|
||||
session()->flash('flash.banner', __('auth.flash.welcome_trial'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('calendar');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,324 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\Post\Status as PostStatus;
|
||||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Http\Requests\UpdatePostRequest;
|
||||
use App\Jobs\PublishPost;
|
||||
use App\Models\Post;
|
||||
use App\Services\Social\PinterestPublisher;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class PostController extends Controller
|
||||
{
|
||||
public function index(Request $request, ?string $status = null): Response|RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
$query = $workspace->posts()
|
||||
->with(['postPlatforms' => function ($query) {
|
||||
$query->where('enabled', true)->with('socialAccount');
|
||||
}, 'user', 'labels']);
|
||||
|
||||
// Apply status filter if provided
|
||||
if ($status) {
|
||||
$query = match ($status) {
|
||||
'draft' => $query->draft(),
|
||||
'scheduled' => $query->scheduled(),
|
||||
'published' => $query->published(),
|
||||
default => $query,
|
||||
};
|
||||
}
|
||||
|
||||
return Inertia::render('posts/Index', [
|
||||
'workspace' => $workspace,
|
||||
'posts' => Inertia::scroll(fn () => $query->latest('scheduled_at')->paginate(15)),
|
||||
'currentStatus' => $status,
|
||||
]);
|
||||
}
|
||||
|
||||
public function calendar(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
$tz = $workspace->timezone;
|
||||
$view = $request->input('view', 'week');
|
||||
|
||||
// Day view
|
||||
$currentDay = $request->input('day')
|
||||
? Carbon::parse($request->input('day'), $tz)->startOfDay()
|
||||
: Carbon::now($tz)->startOfDay();
|
||||
|
||||
// Week view
|
||||
$weekStart = $request->input('week')
|
||||
? Carbon::parse($request->input('week'), $tz)->startOfWeek()
|
||||
: Carbon::now($tz)->startOfWeek();
|
||||
$weekEnd = $weekStart->copy()->endOfWeek();
|
||||
|
||||
// Month view
|
||||
$monthDate = $request->input('month')
|
||||
? Carbon::parse($request->input('month'), $tz)->startOfMonth()
|
||||
: Carbon::now($tz)->startOfMonth();
|
||||
$monthStart = $monthDate->copy()->startOfMonth()->startOfWeek();
|
||||
$monthEnd = $monthDate->copy()->endOfMonth()->endOfWeek();
|
||||
|
||||
// Get posts based on view
|
||||
$rangeStart = match ($view) {
|
||||
'day' => $currentDay,
|
||||
'month' => $monthStart,
|
||||
default => $weekStart,
|
||||
};
|
||||
$rangeEnd = match ($view) {
|
||||
'day' => $currentDay->copy()->endOfDay(),
|
||||
'month' => $monthEnd,
|
||||
default => $weekEnd,
|
||||
};
|
||||
|
||||
$posts = $workspace->posts()
|
||||
->with(['postPlatforms' => function ($query) {
|
||||
$query->where('enabled', true)->with('socialAccount');
|
||||
}])
|
||||
->whereBetween('scheduled_at', [$rangeStart->copy()->utc(), $rangeEnd->copy()->utc()])
|
||||
->orderBy('scheduled_at')
|
||||
->get()
|
||||
->groupBy(fn ($post) => $post->scheduled_at?->setTimezone($tz)->format('Y-m-d'));
|
||||
|
||||
return Inertia::render('posts/Calendar', [
|
||||
'workspace' => $workspace,
|
||||
'posts' => $posts,
|
||||
'currentDay' => $currentDay->format('Y-m-d'),
|
||||
'currentWeekStart' => $weekStart->format('Y-m-d'),
|
||||
'currentMonth' => $monthDate->format('Y-m-d'),
|
||||
'view' => $view,
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse|\Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
$socialAccounts = $workspace->socialAccounts;
|
||||
|
||||
if ($socialAccounts->isEmpty()) {
|
||||
session()->flash('flash.banner', __('posts.flash.connect_first'));
|
||||
session()->flash('flash.bannerStyle', 'danger');
|
||||
|
||||
return redirect()->route('accounts');
|
||||
}
|
||||
|
||||
// Create a draft post - default to today if no date provided
|
||||
$date = $request->input('date') ?: Carbon::now($workspace->timezone)->format('Y-m-d');
|
||||
$scheduledAt = Carbon::parse($date, $workspace->timezone)
|
||||
->setTime(9, 0)
|
||||
->utc();
|
||||
|
||||
$post = $workspace->posts()->create([
|
||||
'user_id' => $request->user()->id,
|
||||
'status' => PostStatus::Draft,
|
||||
'synced' => true,
|
||||
'scheduled_at' => $scheduledAt,
|
||||
]);
|
||||
|
||||
// Create post_platforms for each connected account
|
||||
foreach ($socialAccounts as $account) {
|
||||
$post->postPlatforms()->create([
|
||||
'social_account_id' => $account->id,
|
||||
'platform' => $account->platform->value,
|
||||
'content' => '',
|
||||
'content_type' => ContentType::defaultFor($account->platform),
|
||||
'status' => 'pending',
|
||||
'enabled' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
return Inertia::location(route('posts.edit', $post));
|
||||
}
|
||||
|
||||
public function edit(Request $request, Post $post): Response|RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($post->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$post->load(['postPlatforms.socialAccount', 'postPlatforms.media', 'labels']);
|
||||
$socialAccounts = $workspace->socialAccounts;
|
||||
$labels = $workspace->labels;
|
||||
$hashtags = $workspace->hashtags;
|
||||
|
||||
$platformConfigs = $socialAccounts->mapWithKeys(function ($account) {
|
||||
$platform = $account->platform;
|
||||
|
||||
return [
|
||||
$account->id => [
|
||||
'maxContentLength' => $platform->maxContentLength(),
|
||||
'maxImages' => $platform->maxImages(),
|
||||
'allowedMediaTypes' => array_map(fn ($type) => $type->value, $platform->allowedMediaTypes()),
|
||||
'supportsTextOnly' => $platform->supportsTextOnly(),
|
||||
],
|
||||
];
|
||||
});
|
||||
|
||||
// Fetch Pinterest boards if Pinterest account exists
|
||||
$pinterestBoards = [];
|
||||
$pinterestAccount = $socialAccounts->firstWhere('platform', Platform::Pinterest);
|
||||
if ($pinterestAccount) {
|
||||
try {
|
||||
$pinterestBoards = app(PinterestPublisher::class)->getBoards($pinterestAccount);
|
||||
} catch (\Exception $e) {
|
||||
// Silently fail - boards will be empty
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('posts/Edit', [
|
||||
'workspace' => $workspace,
|
||||
'post' => $post,
|
||||
'socialAccounts' => $socialAccounts,
|
||||
'platformConfigs' => $platformConfigs,
|
||||
'pinterestBoards' => $pinterestBoards,
|
||||
'labels' => $labels,
|
||||
'hashtags' => $hashtags,
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(UpdatePostRequest $request, Post $post): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($post->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if ($post->status === PostStatus::Published) {
|
||||
session()->flash('flash.banner', __('posts.flash.cannot_edit_published'));
|
||||
session()->flash('flash.bannerStyle', 'danger');
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
$scheduledAt = $post->scheduled_at;
|
||||
if ($request->has('scheduled_at') && $request->input('scheduled_at')) {
|
||||
$scheduledAt = Carbon::parse($request->input('scheduled_at'), $workspace->timezone)->utc();
|
||||
}
|
||||
|
||||
$status = $request->input('status', $post->status);
|
||||
|
||||
$post->update([
|
||||
'status' => $status === 'publishing' ? PostStatus::Publishing : $status,
|
||||
'synced' => $request->input('synced', $post->synced),
|
||||
'scheduled_at' => $scheduledAt,
|
||||
]);
|
||||
|
||||
// Sync labels
|
||||
if ($request->has('label_ids')) {
|
||||
$post->labels()->sync($request->input('label_ids', []));
|
||||
}
|
||||
|
||||
// Get selected platform IDs
|
||||
$selectedPlatformIds = collect($request->input('platforms', []))->pluck('id')->toArray();
|
||||
|
||||
// Update all platforms - disable those not selected, update content for selected ones
|
||||
$post->postPlatforms()->update(['enabled' => false]);
|
||||
|
||||
foreach ($request->input('platforms', []) as $platformData) {
|
||||
$updateData = [
|
||||
'enabled' => true,
|
||||
'content' => $platformData['content'],
|
||||
'content_type' => $platformData['content_type'] ?? null,
|
||||
];
|
||||
|
||||
if (isset($platformData['meta'])) {
|
||||
$postPlatform = $post->postPlatforms()->where('id', $platformData['id'])->first();
|
||||
$updateData['meta'] = array_merge($postPlatform->meta ?? [], $platformData['meta']);
|
||||
}
|
||||
|
||||
$post->postPlatforms()
|
||||
->where('id', $platformData['id'])
|
||||
->update($updateData);
|
||||
}
|
||||
|
||||
// Dispatch publish job if publishing now
|
||||
if ($status === 'publishing') {
|
||||
$post->update(['scheduled_at' => now()]);
|
||||
PublishPost::dispatch($post);
|
||||
|
||||
session()->flash('flash.banner', __('posts.flash.publishing'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('posts.edit', $post);
|
||||
}
|
||||
|
||||
// Redirect to show page for schedule action
|
||||
if ($status === 'scheduled') {
|
||||
session()->flash('flash.banner', __('posts.flash.scheduled'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('posts.edit', $post);
|
||||
}
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function destroy(Request $request, Post $post): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($post->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$post->delete();
|
||||
|
||||
session()->flash('flash.banner', __('posts.flash.deleted'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
if ($redirect = $request->input('redirect')) {
|
||||
return redirect()->route($redirect);
|
||||
}
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Settings;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Settings\PasswordUpdateRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class PasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the user's password settings page.
|
||||
*/
|
||||
public function edit(): Response
|
||||
{
|
||||
return Inertia::render('settings/Password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's password.
|
||||
*/
|
||||
public function update(PasswordUpdateRequest $request): RedirectResponse
|
||||
{
|
||||
$request->user()->update([
|
||||
'password' => $request->password,
|
||||
]);
|
||||
|
||||
session()->flash('flash.banner', __('settings.flash.password_updated'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Settings;
|
||||
|
||||
use App\Enums\UserWorkspace\Role;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Settings\ProfileDeleteRequest;
|
||||
use App\Http\Requests\Settings\ProfileUpdateRequest;
|
||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the user's profile settings page.
|
||||
*/
|
||||
public function edit(Request $request): Response
|
||||
{
|
||||
return Inertia::render('settings/Profile', [
|
||||
'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail,
|
||||
'status' => $request->session()->get('status'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's profile information.
|
||||
*/
|
||||
public function update(ProfileUpdateRequest $request): RedirectResponse
|
||||
{
|
||||
$request->user()->fill($request->validated());
|
||||
|
||||
if ($request->user()->isDirty('email')) {
|
||||
$request->user()->email_verified_at = null;
|
||||
}
|
||||
|
||||
$request->user()->save();
|
||||
|
||||
session()->flash('flash.banner', __('settings.flash.profile_updated'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return to_route('profile.edit');
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's language.
|
||||
*/
|
||||
public function updateLanguage(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'language_id' => ['required', 'exists:languages,id'],
|
||||
]);
|
||||
|
||||
$request->user()->update([
|
||||
'language_id' => $request->language_id,
|
||||
]);
|
||||
|
||||
// Refresh the user model to clear cached language relationship
|
||||
$request->user()->refresh();
|
||||
|
||||
session()->flash('flash.banner', __('settings.flash.language_updated'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the user's profile.
|
||||
*/
|
||||
public function destroy(ProfileDeleteRequest $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
DB::transaction(function () use ($user) {
|
||||
// Cancel active Stripe subscription and delete subscription records
|
||||
if ($user->subscribed('default')) {
|
||||
$user->subscription('default')->cancelNow();
|
||||
}
|
||||
$user->subscriptions()->delete();
|
||||
|
||||
// Clear current workspace reference
|
||||
$user->update(['current_workspace_id' => null]);
|
||||
|
||||
// Delete all workspaces owned by the user
|
||||
$ownedWorkspaces = $user->workspaces()->wherePivot('role', Role::Owner->value)->get();
|
||||
|
||||
foreach ($ownedWorkspaces as $workspace) {
|
||||
// Update members who have this as current_workspace_id
|
||||
foreach ($workspace->members as $member) {
|
||||
if ($member->id !== $user->id && $member->current_workspace_id === $workspace->id) {
|
||||
// Find another workspace for this member
|
||||
$otherWorkspace = $member->workspaces()
|
||||
->where('workspaces.id', '!=', $workspace->id)
|
||||
->first();
|
||||
|
||||
$member->update(['current_workspace_id' => $otherWorkspace?->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$workspace->posts()->delete();
|
||||
$workspace->socialAccounts()->delete();
|
||||
$workspace->hashtags()->delete();
|
||||
$workspace->labels()->delete();
|
||||
$workspace->invites()->delete();
|
||||
$workspace->members()->detach();
|
||||
$workspace->delete();
|
||||
}
|
||||
|
||||
// Remove user from workspaces where they are a member
|
||||
$user->workspaces()->detach();
|
||||
});
|
||||
|
||||
Auth::logout();
|
||||
|
||||
$user->delete();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect('/');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,169 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\StoreWorkspaceRequest;
|
||||
use App\Http\Requests\UpdateWorkspaceRequest;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class WorkspaceController extends Controller
|
||||
{
|
||||
/**
|
||||
* List all workspaces.
|
||||
*/
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
$workspaces = $user->workspaces()
|
||||
->withCount(['socialAccounts', 'posts'])
|
||||
->latest()
|
||||
->get();
|
||||
|
||||
return Inertia::render('workspaces/Index', [
|
||||
'workspaces' => $workspaces,
|
||||
'currentWorkspaceId' => $user->current_workspace_id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show create workspace form.
|
||||
*/
|
||||
public function create(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
// First workspace is free, subsequent ones require subscription
|
||||
if ($user->ownedWorkspacesCount() > 0 && ! $user->hasActiveSubscription()) {
|
||||
return redirect()->route('billing.index')
|
||||
->with('message', 'Subscribe to create more workspaces.');
|
||||
}
|
||||
|
||||
return Inertia::render('workspaces/Create');
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a new workspace.
|
||||
*/
|
||||
public function store(StoreWorkspaceRequest $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
// First workspace is free, subsequent ones require subscription
|
||||
if ($user->ownedWorkspacesCount() > 0 && ! $user->hasActiveSubscription()) {
|
||||
return redirect()->route('billing.index')
|
||||
->with('message', 'Subscribe to create more workspaces.');
|
||||
}
|
||||
|
||||
$workspace = Workspace::create([
|
||||
'user_id' => $user->id,
|
||||
...$request->validated(),
|
||||
'timezone' => config('app.timezone', 'UTC'),
|
||||
]);
|
||||
|
||||
// Add user as owner member
|
||||
$workspace->members()->attach($user->id, ['role' => 'owner']);
|
||||
|
||||
// Set as current workspace
|
||||
$user->switchWorkspace($workspace);
|
||||
|
||||
// Increment subscription quantity if user has subscription
|
||||
if ($user->hasActiveSubscription()) {
|
||||
$user->incrementWorkspaceQuantity();
|
||||
}
|
||||
|
||||
return redirect()->route('calendar')
|
||||
->with('success', 'Workspace created successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch to a different workspace.
|
||||
*/
|
||||
public function switch(Request $request, Workspace $workspace): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if (! $user->belongsToWorkspace($workspace)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$user->switchWorkspace($workspace);
|
||||
|
||||
return redirect()->route('calendar');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show workspace settings.
|
||||
*/
|
||||
public function settings(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$workspace = $user->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('update', $workspace);
|
||||
|
||||
$timezones = collect(timezone_identifiers_list())
|
||||
->mapWithKeys(fn ($tz) => [$tz => $tz])
|
||||
->toArray();
|
||||
|
||||
return Inertia::render('settings/Workspace', [
|
||||
'workspace' => $workspace,
|
||||
'timezones' => $timezones,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update workspace settings.
|
||||
*/
|
||||
public function updateSettings(UpdateWorkspaceRequest $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$workspace = $user->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('update', $workspace);
|
||||
|
||||
$workspace->update($request->validated());
|
||||
|
||||
session()->flash('flash.banner', __('settings.flash.workspace_updated'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('workspace.settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a workspace.
|
||||
*/
|
||||
public function destroy(Request $request, Workspace $workspace): RedirectResponse
|
||||
{
|
||||
$this->authorize('delete', $workspace);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
// If deleting current workspace, clear it
|
||||
if ($user->current_workspace_id === $workspace->id) {
|
||||
$user->update(['current_workspace_id' => null]);
|
||||
}
|
||||
|
||||
$workspace->delete();
|
||||
|
||||
// Decrement subscription quantity if user has subscription
|
||||
if ($user->hasActiveSubscription()) {
|
||||
$user->decrementWorkspaceQuantity();
|
||||
}
|
||||
|
||||
return redirect()->route('workspaces.index')
|
||||
->with('success', 'Workspace deleted successfully!');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\WorkspaceHashtag;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class WorkspaceHashtagController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
return Inertia::render('hashtags/Index', [
|
||||
'workspace' => $workspace,
|
||||
'hashtags' => $workspace->hashtags()->latest()->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'hashtags' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
$workspace->hashtags()->create($validated);
|
||||
|
||||
session()->flash('flash.banner', __('hashtags.flash.created'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('hashtags.index');
|
||||
}
|
||||
|
||||
public function update(Request $request, WorkspaceHashtag $hashtag): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($hashtag->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'hashtags' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
$hashtag->update($validated);
|
||||
|
||||
session()->flash('flash.banner', __('hashtags.flash.updated'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('hashtags.index');
|
||||
}
|
||||
|
||||
public function destroy(Request $request, WorkspaceHashtag $hashtag): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($hashtag->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$hashtag->delete();
|
||||
|
||||
session()->flash('flash.banner', __('hashtags.flash.deleted'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('hashtags.index');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,140 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\UserWorkspace\Role as WorkspaceRole;
|
||||
use App\Http\Requests\StoreWorkspaceInviteRequest;
|
||||
use App\Mail\WorkspaceInvite as WorkspaceInviteMail;
|
||||
use App\Models\WorkspaceInvite;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class WorkspaceInviteController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageTeam', $workspace);
|
||||
|
||||
return Inertia::render('settings/Members', [
|
||||
'workspace' => $workspace,
|
||||
'invites' => $workspace->invites()
|
||||
->latest()
|
||||
->get(),
|
||||
'members' => $workspace->members()
|
||||
->where('user_id', '!=', $workspace->user_id)
|
||||
->get()
|
||||
->map(fn ($member) => [
|
||||
'id' => $member->id,
|
||||
'name' => $member->name,
|
||||
'email' => $member->email,
|
||||
'role' => $member->pivot->role,
|
||||
]),
|
||||
'owner' => [
|
||||
'id' => $workspace->owner->id,
|
||||
'name' => $workspace->owner->name,
|
||||
'email' => $workspace->owner->email,
|
||||
'role' => WorkspaceRole::Owner->value,
|
||||
],
|
||||
'roles' => collect(WorkspaceRole::cases())
|
||||
->filter(fn ($role) => $role !== WorkspaceRole::Owner)
|
||||
->map(fn ($role) => [
|
||||
'value' => $role->value,
|
||||
'label' => $role->label(),
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(StoreWorkspaceInviteRequest $request): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageTeam', $workspace);
|
||||
|
||||
$existingInvite = $workspace->invites()
|
||||
->where('email', $request->email)
|
||||
->first();
|
||||
|
||||
if ($existingInvite) {
|
||||
return back()->withErrors([
|
||||
'email' => 'An invite already exists for this email.',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($workspace->members()->where('email', $request->email)->exists()) {
|
||||
return back()->withErrors([
|
||||
'email' => 'This user is already a member of the workspace.',
|
||||
]);
|
||||
}
|
||||
|
||||
$invite = $workspace->invites()->create([
|
||||
'email' => $request->email,
|
||||
'role' => $request->role ?? WorkspaceRole::Member,
|
||||
]);
|
||||
|
||||
Mail::to($invite->email)->send(new WorkspaceInviteMail($invite));
|
||||
|
||||
session()->flash('flash.banner', __('settings.members.flash.invite_sent'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function destroy(Request $request, WorkspaceInvite $invite): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageTeam', $workspace);
|
||||
|
||||
if ($invite->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$invite->delete();
|
||||
|
||||
session()->flash('flash.banner', __('settings.members.flash.invite_deleted'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function removeMember(Request $request, string $userId): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageTeam', $workspace);
|
||||
|
||||
if ($workspace->user_id === $userId) {
|
||||
return back()->withErrors(['member' => 'Cannot remove the workspace owner.']);
|
||||
}
|
||||
|
||||
$workspace->members()->detach($userId);
|
||||
|
||||
session()->flash('flash.banner', __('settings.members.flash.member_removed'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\WorkspaceLabel;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class WorkspaceLabelController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
return Inertia::render('labels/Index', [
|
||||
'workspace' => $workspace,
|
||||
'labels' => $workspace->labels()->latest()->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'color' => ['required', 'string', 'max:7', 'regex:/^#[0-9A-Fa-f]{6}$/'],
|
||||
]);
|
||||
|
||||
$workspace->labels()->create($validated);
|
||||
|
||||
session()->flash('flash.banner', __('labels.flash.created'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('labels.index');
|
||||
}
|
||||
|
||||
public function update(Request $request, WorkspaceLabel $label): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($label->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'color' => ['required', 'string', 'max:7', 'regex:/^#[0-9A-Fa-f]{6}$/'],
|
||||
]);
|
||||
|
||||
$label->update($validated);
|
||||
|
||||
session()->flash('flash.banner', __('labels.flash.updated'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('labels.index');
|
||||
}
|
||||
|
||||
public function destroy(Request $request, WorkspaceLabel $label): RedirectResponse
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('view', $workspace);
|
||||
|
||||
if ($label->workspace_id !== $workspace->id) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$label->delete();
|
||||
|
||||
session()->flash('flash.banner', __('labels.flash.deleted'));
|
||||
session()->flash('flash.bannerStyle', 'success');
|
||||
|
||||
return redirect()->route('labels.index');
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,8 @@
|
|||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->trustProxies(at: '*');
|
||||
|
||||
$middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
|
||||
|
||||
$middleware->web(append: [
|
||||
|
|
@ -32,7 +34,7 @@
|
|||
'api.auth' => AuthenticateApiToken::class,
|
||||
]);
|
||||
|
||||
$middleware->validateCsrfTokens(except: [
|
||||
$middleware->preventRequestForgery(except: [
|
||||
'stripe/*',
|
||||
]);
|
||||
})
|
||||
|
|
|
|||
50
database/factories/ApiTokenFactory.php
Normal file
50
database/factories/ApiTokenFactory.php
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @extends Factory<ApiToken>
|
||||
*/
|
||||
class ApiTokenFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* The plain token generated during creation.
|
||||
*/
|
||||
public static ?string $lastPlainToken = null;
|
||||
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function definition(): array
|
||||
{
|
||||
$plainToken = 'tp_'.Str::random(48);
|
||||
static::$lastPlainToken = $plainToken;
|
||||
|
||||
return [
|
||||
'workspace_id' => Workspace::factory(),
|
||||
'name' => fake()->words(2, true),
|
||||
'token_lookup' => substr($plainToken, 3, 16),
|
||||
'token_hash' => Hash::make($plainToken),
|
||||
'last_used_at' => null,
|
||||
'expires_at' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the token as expired.
|
||||
*/
|
||||
public function expired(): static
|
||||
{
|
||||
return $this->state(fn () => [
|
||||
'expires_at' => now()->subDay(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import Heading from '@/components/Heading.vue';
|
|||
import { useActiveUrl } from '@/composables/useActiveUrl';
|
||||
import { toUrl } from '@/lib/utils';
|
||||
import { members } from '@/routes/app';
|
||||
import { index as apiKeys } from '@/routes/app/api-keys';
|
||||
import { index as billing } from '@/routes/app/billing';
|
||||
import { edit as editProfile } from '@/routes/app/profile';
|
||||
import { edit as editPassword } from '@/routes/app/user-password';
|
||||
|
|
@ -39,6 +40,10 @@ const navItems = computed<NavItem[]>(() => {
|
|||
title: trans('settings.nav.members'),
|
||||
href: members(),
|
||||
},
|
||||
{
|
||||
title: 'API Keys',
|
||||
href: apiKeys(),
|
||||
},
|
||||
);
|
||||
|
||||
if (!page.props.selfHosted) {
|
||||
|
|
|
|||
267
resources/js/pages/settings/ApiKeys.vue
Normal file
267
resources/js/pages/settings/ApiKeys.vue
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
<script setup lang="ts">
|
||||
import { Head, useForm, usePage } from '@inertiajs/vue3';
|
||||
import { IconKey, IconCopy, IconTrash, IconPlus } from '@tabler/icons-vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
|
||||
import HeadingSmall from '@/components/HeadingSmall.vue';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import date from '@/date';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import SettingsLayout from '@/layouts/settings/Layout.vue';
|
||||
import { index as apiKeysIndex, store as storeApiKey, destroy as destroyApiKey } from '@/routes/app/api-keys';
|
||||
import { type BreadcrumbItem } from '@/types';
|
||||
|
||||
interface ApiToken {
|
||||
id: string;
|
||||
name: string;
|
||||
key_hint: string;
|
||||
status: 'active' | 'expired';
|
||||
last_used_at: string | null;
|
||||
expires_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface Workspace {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
workspace: Workspace;
|
||||
apiTokens: ApiToken[];
|
||||
}
|
||||
|
||||
defineProps<Props>();
|
||||
|
||||
const page = usePage();
|
||||
|
||||
const breadcrumbItems = computed<BreadcrumbItem[]>(() => [
|
||||
{ title: 'API Keys', href: apiKeysIndex.url() },
|
||||
]);
|
||||
|
||||
const isCreateDialogOpen = ref(false);
|
||||
const isTokenDialogOpen = ref(false);
|
||||
const plainToken = ref<string | null>(null);
|
||||
const copied = ref(false);
|
||||
const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
|
||||
|
||||
const form = useForm({
|
||||
name: '',
|
||||
expires_at: '',
|
||||
});
|
||||
|
||||
watch(() => page.props.flash, (flash: Record<string, unknown> | undefined) => {
|
||||
if (flash?.plainToken) {
|
||||
plainToken.value = flash.plainToken as string;
|
||||
isCreateDialogOpen.value = false;
|
||||
isTokenDialogOpen.value = true;
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
const submitCreate = () => {
|
||||
form.post(storeApiKey.url(), {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const copyToken = async () => {
|
||||
if (!plainToken.value) return;
|
||||
await navigator.clipboard.writeText(plainToken.value);
|
||||
copied.value = true;
|
||||
setTimeout(() => {
|
||||
copied.value = false;
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
const handleDelete = (tokenId: string) => {
|
||||
deleteModal.value?.open({
|
||||
url: destroyApiKey.url(tokenId),
|
||||
});
|
||||
};
|
||||
|
||||
const closeTokenDialog = () => {
|
||||
isTokenDialogOpen.value = false;
|
||||
plainToken.value = null;
|
||||
copied.value = false;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout :breadcrumbs="breadcrumbItems">
|
||||
<Head title="API Keys" />
|
||||
|
||||
<h1 class="sr-only">API Keys</h1>
|
||||
|
||||
<SettingsLayout>
|
||||
<div class="flex flex-col space-y-6">
|
||||
<div class="flex items-center justify-between">
|
||||
<HeadingSmall
|
||||
title="API Keys"
|
||||
description="Manage API keys for programmatic access to your workspace."
|
||||
/>
|
||||
<Button @click="isCreateDialogOpen = true">
|
||||
<IconPlus class="mr-2 h-4 w-4" />
|
||||
Create API Key
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="apiTokens.length === 0" class="flex flex-col items-center justify-center rounded-lg border border-dashed py-16">
|
||||
<div class="flex h-16 w-16 items-center justify-center rounded-full bg-muted mb-4">
|
||||
<IconKey class="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 class="text-lg font-semibold mb-2">No API keys yet</h3>
|
||||
<p class="text-muted-foreground mb-4 max-w-sm text-center">
|
||||
Create an API key to access your workspace programmatically.
|
||||
</p>
|
||||
<Button @click="isCreateDialogOpen = true">
|
||||
<IconPlus class="mr-2 h-4 w-4" />
|
||||
Create your first API key
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="token in apiTokens"
|
||||
:key="token.id"
|
||||
class="flex items-center justify-between rounded-lg border p-4"
|
||||
>
|
||||
<div class="flex items-center gap-4 min-w-0">
|
||||
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-muted">
|
||||
<IconKey class="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<p class="font-medium truncate">{{ token.name }}</p>
|
||||
<Badge
|
||||
:variant="token.status === 'active' ? 'default' : 'destructive'"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ token.status }}
|
||||
</Badge>
|
||||
</div>
|
||||
<p class="text-sm text-muted-foreground font-mono">
|
||||
{{ token.key_hint }}
|
||||
</p>
|
||||
<div class="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
|
||||
<span>Created {{ date.diffForHumans(token.created_at) }}</span>
|
||||
<span v-if="token.last_used_at">
|
||||
Last used {{ date.diffForHumans(token.last_used_at) }}
|
||||
</span>
|
||||
<span v-else>Never used</span>
|
||||
<span v-if="token.expires_at">
|
||||
Expires {{ date.diffForHumans(token.expires_at) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="shrink-0"
|
||||
@click="handleDelete(token.id)"
|
||||
>
|
||||
<IconTrash class="h-4 w-4 text-red-500" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsLayout>
|
||||
</AppLayout>
|
||||
|
||||
<Dialog :open="isCreateDialogOpen" @update:open="isCreateDialogOpen = $event">
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create API Key</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new API key for programmatic access to your workspace.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form @submit.prevent="submitCreate" class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="token-name">Name</Label>
|
||||
<Input
|
||||
id="token-name"
|
||||
v-model="form.name"
|
||||
placeholder="e.g. Production API Key"
|
||||
:class="{ 'border-red-500': form.errors.name }"
|
||||
/>
|
||||
<p v-if="form.errors.name" class="text-sm text-red-500">
|
||||
{{ form.errors.name }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Label for="token-expires">Expiration date (optional)</Label>
|
||||
<Input
|
||||
id="token-expires"
|
||||
v-model="form.expires_at"
|
||||
type="date"
|
||||
:class="{ 'border-red-500': form.errors.expires_at }"
|
||||
/>
|
||||
<p v-if="form.errors.expires_at" class="text-sm text-red-500">
|
||||
{{ form.errors.expires_at }}
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" @click="isCreateDialogOpen = false">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" :disabled="form.processing">
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog :open="isTokenDialogOpen" @update:open="closeTokenDialog">
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>API Key Created</DialogTitle>
|
||||
<DialogDescription>
|
||||
Copy your API key now. You will not be able to see it again.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<Input
|
||||
:model-value="plainToken ?? ''"
|
||||
readonly
|
||||
class="font-mono text-sm"
|
||||
/>
|
||||
<Button variant="outline" size="icon" class="shrink-0" @click="copyToken">
|
||||
<IconCopy class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p v-if="copied" class="text-sm text-green-600">Copied to clipboard!</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button @click="closeTokenDialog">
|
||||
Done
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDeleteModal
|
||||
ref="deleteModal"
|
||||
title="Delete API Key"
|
||||
description="Are you sure you want to delete this API key? Any applications using this key will lose access immediately."
|
||||
action="Delete"
|
||||
cancel="Cancel"
|
||||
/>
|
||||
</template>
|
||||
14
routes/mcp.php
Normal file
14
routes/mcp.php
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::group(
|
||||
[
|
||||
'domain' => 'mcp.'.parse_url(config('app.url'), PHP_URL_HOST),
|
||||
],
|
||||
function () {
|
||||
//
|
||||
}
|
||||
);
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
<?php
|
||||
|
||||
use App\Http\Controllers\Settings\PasswordController;
|
||||
use App\Http\Controllers\Settings\ProfileController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['auth'])->group(function () {
|
||||
Route::get('settings/profile', [ProfileController::class, 'edit'])->name('profile.edit');
|
||||
Route::patch('settings/profile', [ProfileController::class, 'update'])->name('profile.update');
|
||||
Route::patch('settings/language', [ProfileController::class, 'updateLanguage'])->name('profile.language');
|
||||
});
|
||||
|
||||
Route::middleware(['auth', 'verified'])->group(function () {
|
||||
Route::delete('settings/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
|
||||
|
||||
Route::get('settings/password', [PasswordController::class, 'edit'])->name('user-password.edit');
|
||||
|
||||
Route::put('settings/password', [PasswordController::class, 'update'])
|
||||
->middleware('throttle:6,1')
|
||||
->name('user-password.update');
|
||||
});
|
||||
127
tests/Feature/Api/ApiKeyApiTest.php
Normal file
127
tests/Feature/Api/ApiKeyApiTest.php
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
<?php
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @return array{token: ApiToken, plain_token: string, workspace: Workspace}
|
||||
*/
|
||||
function createApiKeyApiToken(array $overrides = []): array
|
||||
{
|
||||
$plainToken = 'tp_'.Str::random(48);
|
||||
|
||||
$workspace = data_get($overrides, 'workspace') ?? Workspace::factory()->create();
|
||||
|
||||
$factoryOverrides = collect($overrides)->except('workspace')->toArray();
|
||||
|
||||
$apiToken = ApiToken::factory()->create(array_merge([
|
||||
'workspace_id' => $workspace->id,
|
||||
'token_lookup' => substr($plainToken, 3, 16),
|
||||
'token_hash' => Hash::make($plainToken),
|
||||
], $factoryOverrides));
|
||||
|
||||
return [
|
||||
'token' => $apiToken,
|
||||
'plain_token' => $plainToken,
|
||||
'workspace' => $workspace,
|
||||
];
|
||||
}
|
||||
|
||||
test('list api keys', function () {
|
||||
$result = createApiKeyApiToken();
|
||||
|
||||
// The authenticating token itself is one, create two more
|
||||
ApiToken::factory()->count(2)->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.api-keys.index'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonCount(3);
|
||||
});
|
||||
|
||||
test('create api key returns plain token', function () {
|
||||
$result = createApiKeyApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.api-keys.store'),
|
||||
[
|
||||
'name' => 'CI/CD Token',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertCreated();
|
||||
$response->assertJsonStructure([
|
||||
'token' => ['id', 'name', 'key_hint', 'status'],
|
||||
'plain_token',
|
||||
]);
|
||||
|
||||
$plainToken = $response->json('plain_token');
|
||||
expect($plainToken)->toStartWith('tp_');
|
||||
expect(strlen($plainToken))->toBe(51);
|
||||
});
|
||||
|
||||
test('create api key validation errors', function () {
|
||||
$result = createApiKeyApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.api-keys.store'),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnprocessable();
|
||||
$response->assertJsonValidationErrors(['name']);
|
||||
});
|
||||
|
||||
test('delete api key', function () {
|
||||
$result = createApiKeyApiToken();
|
||||
|
||||
$tokenToDelete = ApiToken::factory()->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->deleteJson(
|
||||
route('api.api-keys.destroy', $tokenToDelete),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertNoContent();
|
||||
|
||||
expect(ApiToken::find($tokenToDelete->id))->toBeNull();
|
||||
});
|
||||
|
||||
test('cannot delete api key from another workspace', function () {
|
||||
$result = createApiKeyApiToken();
|
||||
|
||||
$otherWorkspace = Workspace::factory()->create();
|
||||
$otherToken = ApiToken::factory()->create([
|
||||
'workspace_id' => $otherWorkspace->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->deleteJson(
|
||||
route('api.api-keys.destroy', $otherToken),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertNotFound();
|
||||
});
|
||||
117
tests/Feature/Api/AuthenticateApiTokenTest.php
Normal file
117
tests/Feature/Api/AuthenticateApiTokenTest.php
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
<?php
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @return array{token: ApiToken, plain_token: string, workspace: Workspace}
|
||||
*/
|
||||
function createApiToken(array $overrides = []): array
|
||||
{
|
||||
$plainToken = 'tp_'.Str::random(48);
|
||||
|
||||
$workspace = data_get($overrides, 'workspace') ?? Workspace::factory()->create();
|
||||
|
||||
$factoryOverrides = collect($overrides)->except('workspace')->toArray();
|
||||
|
||||
$apiToken = ApiToken::factory()->create(array_merge([
|
||||
'workspace_id' => $workspace->id,
|
||||
'token_lookup' => substr($plainToken, 3, 16),
|
||||
'token_hash' => Hash::make($plainToken),
|
||||
], $factoryOverrides));
|
||||
|
||||
return [
|
||||
'token' => $apiToken,
|
||||
'plain_token' => $plainToken,
|
||||
'workspace' => $workspace,
|
||||
];
|
||||
}
|
||||
|
||||
test('returns 401 without token', function () {
|
||||
$response = $this->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnauthorized();
|
||||
$response->assertJson(['message' => 'Missing API key.']);
|
||||
});
|
||||
|
||||
test('returns 401 with invalid token format', function () {
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer invalid-token',
|
||||
])->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnauthorized();
|
||||
$response->assertJson(['message' => 'Invalid API key.']);
|
||||
});
|
||||
|
||||
test('returns 401 with wrong token', function () {
|
||||
createApiToken();
|
||||
|
||||
$wrongToken = 'tp_'.Str::random(48);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$wrongToken,
|
||||
])->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnauthorized();
|
||||
$response->assertJson(['message' => 'Invalid API key.']);
|
||||
});
|
||||
|
||||
test('returns 401 with expired token', function () {
|
||||
$result = createApiToken();
|
||||
|
||||
$result['token']->update(['expires_at' => now()->subDay()]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnauthorized();
|
||||
$response->assertJson(['message' => 'API key has expired.']);
|
||||
});
|
||||
|
||||
test('authenticates with valid token', function () {
|
||||
$result = createApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
});
|
||||
|
||||
test('updates last_used_at on successful auth', function () {
|
||||
$this->freezeTime();
|
||||
|
||||
$result = createApiToken();
|
||||
|
||||
expect($result['token']->last_used_at)->toBeNull();
|
||||
|
||||
$this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$result['token']->refresh();
|
||||
|
||||
expect($result['token']->last_used_at)->not->toBeNull();
|
||||
expect($result['token']->last_used_at->toDateTimeString())->toBe(now()->toDateTimeString());
|
||||
});
|
||||
149
tests/Feature/Api/HashtagApiTest.php
Normal file
149
tests/Feature/Api/HashtagApiTest.php
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
<?php
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceHashtag;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @return array{token: ApiToken, plain_token: string, workspace: Workspace}
|
||||
*/
|
||||
function createHashtagApiToken(array $overrides = []): array
|
||||
{
|
||||
$plainToken = 'tp_'.Str::random(48);
|
||||
|
||||
$workspace = data_get($overrides, 'workspace') ?? Workspace::factory()->create();
|
||||
|
||||
$factoryOverrides = collect($overrides)->except('workspace')->toArray();
|
||||
|
||||
$apiToken = ApiToken::factory()->create(array_merge([
|
||||
'workspace_id' => $workspace->id,
|
||||
'token_lookup' => substr($plainToken, 3, 16),
|
||||
'token_hash' => Hash::make($plainToken),
|
||||
], $factoryOverrides));
|
||||
|
||||
return [
|
||||
'token' => $apiToken,
|
||||
'plain_token' => $plainToken,
|
||||
'workspace' => $workspace,
|
||||
];
|
||||
}
|
||||
|
||||
test('list hashtags', function () {
|
||||
$result = createHashtagApiToken();
|
||||
|
||||
WorkspaceHashtag::factory()->count(3)->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.hashtags.index'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonCount(3);
|
||||
});
|
||||
|
||||
test('create hashtag', function () {
|
||||
$result = createHashtagApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.hashtags.store'),
|
||||
[
|
||||
'name' => 'Marketing Tags',
|
||||
'hashtags' => '#marketing #growth #saas',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertCreated();
|
||||
$response->assertJsonPath('name', 'Marketing Tags');
|
||||
|
||||
expect($result['workspace']->hashtags()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('create hashtag validation errors', function () {
|
||||
$result = createHashtagApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.hashtags.store'),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnprocessable();
|
||||
$response->assertJsonValidationErrors(['name', 'hashtags']);
|
||||
});
|
||||
|
||||
test('update hashtag', function () {
|
||||
$result = createHashtagApiToken();
|
||||
|
||||
$hashtag = WorkspaceHashtag::factory()->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
'name' => 'Old Name',
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->putJson(
|
||||
route('api.hashtags.update', $hashtag),
|
||||
[
|
||||
'name' => 'Updated Name',
|
||||
'hashtags' => '#updated #tags',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('name', 'Updated Name');
|
||||
});
|
||||
|
||||
test('delete hashtag', function () {
|
||||
$result = createHashtagApiToken();
|
||||
|
||||
$hashtag = WorkspaceHashtag::factory()->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->deleteJson(
|
||||
route('api.hashtags.destroy', $hashtag),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertNoContent();
|
||||
|
||||
expect(WorkspaceHashtag::find($hashtag->id))->toBeNull();
|
||||
});
|
||||
|
||||
test('cannot access hashtags from another workspace', function () {
|
||||
$result = createHashtagApiToken();
|
||||
|
||||
$otherWorkspace = Workspace::factory()->create();
|
||||
$hashtag = WorkspaceHashtag::factory()->create([
|
||||
'workspace_id' => $otherWorkspace->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->putJson(
|
||||
route('api.hashtags.update', $hashtag),
|
||||
[
|
||||
'name' => 'Hacked Name',
|
||||
'hashtags' => '#hacked',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertNotFound();
|
||||
});
|
||||
170
tests/Feature/Api/LabelApiTest.php
Normal file
170
tests/Feature/Api/LabelApiTest.php
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
<?php
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceLabel;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @return array{token: ApiToken, plain_token: string, workspace: Workspace}
|
||||
*/
|
||||
function createLabelApiToken(array $overrides = []): array
|
||||
{
|
||||
$plainToken = 'tp_'.Str::random(48);
|
||||
|
||||
$workspace = data_get($overrides, 'workspace') ?? Workspace::factory()->create();
|
||||
|
||||
$factoryOverrides = collect($overrides)->except('workspace')->toArray();
|
||||
|
||||
$apiToken = ApiToken::factory()->create(array_merge([
|
||||
'workspace_id' => $workspace->id,
|
||||
'token_lookup' => substr($plainToken, 3, 16),
|
||||
'token_hash' => Hash::make($plainToken),
|
||||
], $factoryOverrides));
|
||||
|
||||
return [
|
||||
'token' => $apiToken,
|
||||
'plain_token' => $plainToken,
|
||||
'workspace' => $workspace,
|
||||
];
|
||||
}
|
||||
|
||||
test('list labels', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
WorkspaceLabel::factory()->count(3)->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.labels.index'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonCount(3);
|
||||
});
|
||||
|
||||
test('create label', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.labels.store'),
|
||||
[
|
||||
'name' => 'Marketing',
|
||||
'color' => '#FF0000',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertCreated();
|
||||
$response->assertJsonPath('name', 'Marketing');
|
||||
$response->assertJsonPath('color', '#FF0000');
|
||||
|
||||
expect($result['workspace']->labels()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('create label validation errors', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.labels.store'),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnprocessable();
|
||||
$response->assertJsonValidationErrors(['name', 'color']);
|
||||
});
|
||||
|
||||
test('create label validates color format', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->postJson(
|
||||
route('api.labels.store'),
|
||||
[
|
||||
'name' => 'Bad Color',
|
||||
'color' => 'not-a-color',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnprocessable();
|
||||
$response->assertJsonValidationErrors(['color']);
|
||||
});
|
||||
|
||||
test('update label', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
$label = WorkspaceLabel::factory()->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
'name' => 'Old Name',
|
||||
'color' => '#000000',
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->putJson(
|
||||
route('api.labels.update', $label),
|
||||
[
|
||||
'name' => 'Updated Name',
|
||||
'color' => '#FFFFFF',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('name', 'Updated Name');
|
||||
$response->assertJsonPath('color', '#FFFFFF');
|
||||
});
|
||||
|
||||
test('delete label', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
$label = WorkspaceLabel::factory()->create([
|
||||
'workspace_id' => $result['workspace']->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->deleteJson(
|
||||
route('api.labels.destroy', $label),
|
||||
[],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertNoContent();
|
||||
|
||||
expect(WorkspaceLabel::find($label->id))->toBeNull();
|
||||
});
|
||||
|
||||
test('cannot access labels from another workspace', function () {
|
||||
$result = createLabelApiToken();
|
||||
|
||||
$otherWorkspace = Workspace::factory()->create();
|
||||
$label = WorkspaceLabel::factory()->create([
|
||||
'workspace_id' => $otherWorkspace->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->putJson(
|
||||
route('api.labels.update', $label),
|
||||
[
|
||||
'name' => 'Hacked Name',
|
||||
'color' => '#FF0000',
|
||||
],
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertNotFound();
|
||||
});
|
||||
57
tests/Feature/Api/WorkspaceApiTest.php
Normal file
57
tests/Feature/Api/WorkspaceApiTest.php
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @return array{token: ApiToken, plain_token: string, workspace: Workspace}
|
||||
*/
|
||||
function createWorkspaceApiToken(array $overrides = []): array
|
||||
{
|
||||
$plainToken = 'tp_'.Str::random(48);
|
||||
|
||||
$workspace = data_get($overrides, 'workspace') ?? Workspace::factory()->create();
|
||||
|
||||
$factoryOverrides = collect($overrides)->except('workspace')->toArray();
|
||||
|
||||
$apiToken = ApiToken::factory()->create(array_merge([
|
||||
'workspace_id' => $workspace->id,
|
||||
'token_lookup' => substr($plainToken, 3, 16),
|
||||
'token_hash' => Hash::make($plainToken),
|
||||
], $factoryOverrides));
|
||||
|
||||
return [
|
||||
'token' => $apiToken,
|
||||
'plain_token' => $plainToken,
|
||||
'workspace' => $workspace,
|
||||
];
|
||||
}
|
||||
|
||||
test('show current workspace', function () {
|
||||
$workspace = Workspace::factory()->create([
|
||||
'name' => 'Test Workspace',
|
||||
]);
|
||||
|
||||
$result = createWorkspaceApiToken(['workspace' => $workspace]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$result['plain_token'],
|
||||
])->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertOk();
|
||||
$response->assertJsonPath('name', 'Test Workspace');
|
||||
});
|
||||
|
||||
test('show workspace requires authentication', function () {
|
||||
$response = $this->getJson(
|
||||
route('api.workspace.show'),
|
||||
['HTTP_HOST' => 'api.trypost.test']
|
||||
);
|
||||
|
||||
$response->assertUnauthorized();
|
||||
});
|
||||
Loading…
Reference in a new issue