trypost/app/Http/Controllers/Auth/SocialController.php

223 lines
7.4 KiB
PHP
Raw Normal View History

2026-01-15 01:13:44 +00:00
<?php
declare(strict_types=1);
2026-01-15 01:13:44 +00:00
namespace App\Http\Controllers\Auth;
use App\Actions\SocialAccount\ToggleSocialAccount;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
2026-01-15 01:13:44 +00:00
use App\Http\Controllers\Controller;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
2026-01-15 01:13:44 +00:00
use Inertia\Inertia;
use Inertia\Response;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class SocialController extends Controller
{
protected SocialPlatform $platform;
protected function ensurePlatformEnabled(): void
{
if (isset($this->platform) && ! $this->platform->isEnabled()) {
abort(403, 'This platform is currently unavailable.');
}
}
public function index(Request $request): Response|RedirectResponse
2026-01-15 01:13:44 +00:00
{
$workspace = $request->user()->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
2026-01-15 01:13:44 +00:00
$this->authorize('view', $workspace);
$connectedAccounts = $workspace->socialAccounts;
$platforms = collect(SocialPlatform::enabled())->map(function ($platform) use ($connectedAccounts) {
2026-01-15 01:13:44 +00:00
$connected = $connectedAccounts->firstWhere('platform', $platform);
return [
'value' => $platform->value,
'label' => $platform->label(),
'color' => $platform->color(),
'connected' => $connected !== null,
'account' => $connected,
];
})->values();
2026-01-15 01:13:44 +00:00
return Inertia::render('accounts/Index', [
'workspace' => $workspace,
'platforms' => $platforms,
]);
}
public function disconnect(Request $request, SocialAccount $account): RedirectResponse
2026-01-15 01:13:44 +00:00
{
$workspace = $request->user()->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
2026-01-15 17:24:39 +00:00
$this->authorize('manageAccounts', $workspace);
2026-01-15 01:13:44 +00:00
if ($account->workspace_id !== $workspace->id) {
abort(403);
}
$account->delete();
2026-01-22 01:08:18 +00:00
session()->flash('flash.banner', __('accounts.flash.disconnected'));
2026-01-15 17:24:39 +00:00
session()->flash('flash.bannerStyle', 'success');
return back();
2026-01-15 01:13:44 +00:00
}
2026-03-31 00:18:07 +00:00
public function toggleActive(Request $request, SocialAccount $account): RedirectResponse
{
$workspace = $request->user()->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
2026-03-31 00:18:07 +00:00
$this->authorize('manageAccounts', $workspace);
if ($account->workspace_id !== $workspace->id) {
abort(403);
}
ToggleSocialAccount::execute($account);
2026-03-31 00:18:07 +00:00
$status = $account->is_active ? 'activated' : 'deactivated';
session()->flash('flash.banner', __("accounts.flash.{$status}"));
session()->flash('flash.bannerStyle', 'success');
return back();
}
protected function redirectToProvider(Request $request, string $driver, array $scopes): SymfonyResponse
2026-01-15 01:13:44 +00:00
{
$workspace = $request->user()->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
2026-01-15 01:13:44 +00:00
session(['social_connect_workspace' => $workspace->id]);
session(['social_connect_onboarding' => $request->boolean('onboarding')]);
2026-01-15 01:13:44 +00:00
return Inertia::location(
Socialite::driver($driver)
->scopes($scopes)
->redirect()
->getTargetUrl()
);
}
protected function handleCallback(
Request $request,
SocialPlatform $platform,
string $driver
): View {
2026-01-15 01:13:44 +00:00
$workspaceId = session('social_connect_workspace');
if (! $workspaceId) {
return $this->popupCallback(false, 'Session expired. Please try again.', $platform->value);
2026-01-15 01:13:44 +00:00
}
$workspace = Workspace::find($workspaceId);
2026-01-15 17:24:39 +00:00
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, 'Workspace not found.', $platform->value);
2026-01-15 01:13:44 +00:00
}
try {
$socialUser = Socialite::driver($driver)->user();
$existingAccount = $workspace->socialAccounts()
->where('platform', $platform->value)
->first();
// If account exists and is connected, don't allow duplicate
if ($existingAccount && ! $existingAccount->isDisconnected()) {
return $this->popupCallback(false, 'This platform is already connected.', $platform->value);
}
2026-01-15 01:13:44 +00:00
$avatarPath = uploadFromUrl($socialUser->getAvatar());
if ($existingAccount) {
// Reconnect existing account
$existingAccount->update([
'platform_user_id' => $socialUser->getId(),
'username' => $socialUser->getNickname(),
'display_name' => $socialUser->getName(),
'avatar_url' => $avatarPath,
'access_token' => $socialUser->token,
'refresh_token' => $socialUser->refreshToken,
'token_expires_at' => $socialUser->expiresIn ? now()->addSeconds($socialUser->expiresIn) : null,
'scopes' => $socialUser->approvedScopes ?? null,
]);
$existingAccount->markAsConnected();
return $this->popupCallback(true, 'Account reconnected!', $platform->value);
}
// Create new account
2026-01-15 01:13:44 +00:00
$workspace->socialAccounts()->create([
'platform' => $platform->value,
'platform_user_id' => $socialUser->getId(),
'username' => $socialUser->getNickname(),
'display_name' => $socialUser->getName(),
'avatar_url' => $avatarPath,
'access_token' => $socialUser->token,
'refresh_token' => $socialUser->refreshToken,
'token_expires_at' => $socialUser->expiresIn ? now()->addSeconds($socialUser->expiresIn) : null,
'scopes' => $socialUser->approvedScopes ?? null,
'status' => Status::Connected,
2026-01-15 01:13:44 +00:00
]);
return $this->popupCallback(true, 'Account connected!', $platform->value);
2026-01-15 01:13:44 +00:00
} catch (\Exception $e) {
Log::error('Social OAuth Error', [
'platform' => $platform->value,
'error' => $e->getMessage(),
]);
return $this->popupCallback(false, 'Error connecting account. Please try again.', $platform->value);
2026-01-15 01:13:44 +00:00
}
}
protected function forgetSocialConnectSession(): void
{
session()->forget(['social_connect_workspace', 'social_connect_onboarding']);
}
protected function getRedirectRoute(): string
{
refactor: auth split layout, subscribe redesign, onboarding, i18n, cookie locale Auth pages: - Create AuthSplitLayout with animated feature slides (6 slides, 3 languages) - All auth pages use split layout (form left, visual right) - Add show/hide password toggle with tooltip on Register - Legal footer only shown on Register via showLegal prop Subscribe page: - Redesign to match auth card pattern (centered, clean) - Platform icons, feature checklist, dynamic trial days (trialDays - 1) - Add "Switch workspace" link - Full i18n (en, es, pt-BR) Onboarding: - Rename URLs: step1 -> role, step2 -> connect - Add enforceStep() to prevent skipping/going back steps - Redirect /onboarding to /onboarding/role - Redesign Step2 with AuthSplitLayout and compact platform list - 21 tests covering all step enforcement scenarios Workspaces page: - Redesign with AuthSplitLayout (list with avatars, current badge) Language system: - Move locale from DB to cookie (forever, unencrypted, session.domain) - Create SetLocale middleware (sets cookie if missing, validates against config) - Rename lang/pt-br to lang/pt-BR - Add dayjs es locale Other: - Copy utils.ts from sendkit (formatNumber, formatMoney, copyToClipboard) - ConfirmDeleteModal with text confirmation (sendkit pattern) - i18n for ConfirmDeleteModal internal strings (common.php) - EmptyState component for posts index - Exact match for "All" posts in sidebar - Posts breadcrumbs show current status filter - DialogFooter buttons aligned left - API Keys page redesign with Table, DropdownMenu, EmptyState - Extract CreateApiKeyDialog and InviteMemberDialog to components - Remove API Keys from sidebar - DropdownMenuItem destructive variant for Remove action
2026-03-30 14:53:42 +00:00
return session('social_connect_onboarding', false) ? 'onboarding.connect' : 'accounts';
}
/**
* Return a view that closes the popup and notifies the parent window.
*/
protected function popupCallback(bool $success, string $message, ?string $platform = null): View
{
$this->forgetSocialConnectSession();
return view('auth.social-callback', [
'success' => $success,
'message' => $message,
'platform' => $platform,
]);
}
2026-01-15 01:13:44 +00:00
}