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

304 lines
11 KiB
PHP
Raw Normal View History

2026-01-15 17:24:39 +00:00
<?php
declare(strict_types=1);
2026-01-15 17:24:39 +00:00
namespace App\Http\Controllers\Auth;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
2026-01-15 17:24:39 +00:00
use App\Models\Workspace;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
2026-01-15 17:24:39 +00:00
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
2026-01-15 17:24:39 +00:00
use Inertia\Inertia;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\Response;
class FacebookController extends SocialController
{
protected string $driver = 'facebook';
protected SocialPlatform $platform = SocialPlatform::Facebook;
protected array $scopes = [
'public_profile',
2026-01-15 17:24:39 +00:00
'pages_show_list',
'pages_read_engagement',
'pages_manage_posts',
2026-04-02 20:57:06 +00:00
'read_insights',
2026-01-15 17:24:39 +00:00
];
public function connect(Request $request): Response|RedirectResponse
2026-01-15 17:24:39 +00:00
{
$this->ensurePlatformEnabled();
$workspace = $request->user()->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
2026-01-15 17:24:39 +00:00
$this->authorize('manageAccounts', $workspace);
$this->ensureSocialAccountLimit($workspace);
2026-01-15 17:24:39 +00:00
session([
'social_connect_workspace' => $workspace->id,
'social_reconnect_id' => null,
'social_connect_onboarding' => $request->boolean('onboarding'),
]);
2026-01-15 17:24:39 +00:00
return Inertia::location(
Socialite::driver($this->driver)
2026-04-02 20:57:06 +00:00
->usingGraphVersion('v25.0')
2026-03-29 14:51:00 +00:00
->setScopes($this->scopes)
2026-01-15 17:24:39 +00:00
->redirect()
->getTargetUrl()
);
}
public function callback(Request $request): View|RedirectResponse
2026-01-15 17:24:39 +00:00
{
$workspaceId = session('social_connect_workspace');
if (! $workspaceId) {
return $this->popupCallback(false, 'Session expired. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$workspace = Workspace::find($workspaceId);
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, 'Workspace not found.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
try {
2026-04-02 20:57:06 +00:00
$socialUser = Socialite::driver($this->driver)->usingGraphVersion('v25.0')->user();
2026-01-15 17:24:39 +00:00
// Trigger public_profile and pages_show_list API calls
// These calls are needed for Meta app review permission verification
Http::get('https://graph.facebook.com/v25.0/me', [
'fields' => 'id,name',
'access_token' => $socialUser->token,
]);
2026-01-15 17:24:39 +00:00
// Fetch pages the user manages
$pages = $this->fetchPages($socialUser->token);
if (empty($pages)) {
return $this->popupCallback(false, 'No Facebook Pages found. You need to be an admin of at least one page.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
// If only one page, connect directly
if (count($pages) === 1) {
$page = $pages[0];
$avatarPath = uploadFromUrl(data_get($page, 'picture'));
2026-01-15 17:24:39 +00:00
$workspace->socialAccounts()->updateOrCreate(
[
'platform' => $this->platform->value,
'platform_user_id' => data_get($page, 'id'),
],
[
'username' => data_get($page, 'username', null),
'display_name' => data_get($page, 'name'),
'avatar_url' => $avatarPath,
'access_token' => data_get($page, 'access_token'),
'refresh_token' => null,
'token_expires_at' => null,
'scopes' => $this->scopes,
'status' => Status::Connected,
'error_message' => null,
'disconnected_at' => null,
'meta' => [
'page_id' => data_get($page, 'id'),
'user_id' => $socialUser->getId(),
'user_token' => $socialUser->token,
],
2026-01-15 17:24:39 +00:00
],
);
2026-01-15 17:24:39 +00:00
return $this->popupCallback(true, 'Facebook Page connected!', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
// Multiple pages - store data and show selection
session([
'facebook_oauth' => [
'user_token' => $socialUser->token,
'user_id' => $socialUser->getId(),
'pages' => $pages,
],
]);
return redirect()->route('app.social.facebook.select-page');
2026-01-15 17:24:39 +00:00
} catch (\Exception $e) {
Log::error('Facebook OAuth Error', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return $this->popupCallback(false, 'Error connecting account. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
}
public function selectPage(Request $request)
{
$oauthData = session('facebook_oauth');
$workspaceId = session('social_connect_workspace');
if (! $oauthData || ! $workspaceId) {
session()->flash('flash.banner', __('accounts.flash.session_expired'));
session()->flash('flash.bannerStyle', 'danger');
return redirect()->route('app.accounts');
2026-01-15 17:24:39 +00:00
}
$workspace = Workspace::find($workspaceId);
if (! $workspace) {
session()->flash('flash.banner', __('accounts.flash.workspace_not_found'));
session()->flash('flash.bannerStyle', 'danger');
return redirect()->route('app.accounts');
2026-01-15 17:24:39 +00:00
}
$pages = collect(data_get($oauthData, 'pages'))
->map(fn ($page) => Arr::except($page, ['access_token']))
->toArray();
2026-01-15 17:24:39 +00:00
return Inertia::render('accounts/FacebookPageSelect', [
'workspace' => $workspace,
'pages' => $pages,
2026-01-15 17:24:39 +00:00
]);
}
public function select(Request $request): View
2026-01-15 17:24:39 +00:00
{
$request->validate([
'page_id' => 'required|string',
]);
$oauthData = session('facebook_oauth');
$workspaceId = session('social_connect_workspace');
if (! $oauthData || ! $workspaceId) {
return $this->popupCallback(false, 'Session expired. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$workspace = Workspace::find($workspaceId);
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
return $this->popupCallback(false, 'Workspace not found.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
try {
$selectedPage = collect(data_get($oauthData, 'pages'))->firstWhere('id', $request->page_id);
2026-01-15 17:24:39 +00:00
if (! $selectedPage) {
return $this->popupCallback(false, 'Page not found.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
$avatarPath = uploadFromUrl(data_get($selectedPage, 'picture'));
$reconnectId = data_get($oauthData, 'reconnect_id');
if ($reconnectId) {
// Reconnect existing account
$existingAccount = $workspace->socialAccounts()->find($reconnectId);
if ($existingAccount) {
$existingAccount->update([
'platform_user_id' => data_get($selectedPage, 'id'),
'username' => data_get($selectedPage, 'username') ?? null,
'display_name' => data_get($selectedPage, 'name'),
'avatar_url' => $avatarPath,
'access_token' => data_get($selectedPage, 'access_token'),
'refresh_token' => null,
'token_expires_at' => null,
'scopes' => $this->scopes,
'meta' => [
'page_id' => data_get($selectedPage, 'id'),
'user_id' => data_get($oauthData, 'user_id'),
'user_token' => data_get($oauthData, 'user_token'),
],
]);
$existingAccount->markAsConnected();
session()->forget(['facebook_oauth', 'social_reconnect_id']);
return $this->popupCallback(true, 'Facebook Page reconnected!', $this->platform->value);
}
}
2026-01-15 17:24:39 +00:00
$workspace->socialAccounts()->updateOrCreate(
[
'platform' => $this->platform->value,
'platform_user_id' => data_get($selectedPage, 'id'),
2026-01-15 17:24:39 +00:00
],
[
'username' => data_get($selectedPage, 'username') ?? null,
'display_name' => data_get($selectedPage, 'name'),
'avatar_url' => $avatarPath,
'access_token' => data_get($selectedPage, 'access_token'),
'refresh_token' => null,
'token_expires_at' => null,
'scopes' => $this->scopes,
'status' => Status::Connected,
'error_message' => null,
'disconnected_at' => null,
'meta' => [
'page_id' => data_get($selectedPage, 'id'),
'user_id' => data_get($oauthData, 'user_id'),
'user_token' => data_get($oauthData, 'user_token'),
],
],
);
2026-01-15 17:24:39 +00:00
session()->forget(['facebook_oauth', 'social_reconnect_id']);
2026-01-15 17:24:39 +00:00
return $this->popupCallback(true, 'Facebook Page connected!', $this->platform->value);
2026-01-15 17:24:39 +00:00
} catch (\Exception $e) {
Log::error('Facebook page selection error', [
'error' => $e->getMessage(),
]);
return $this->popupCallback(false, 'Error connecting page. Please try again.', $this->platform->value);
2026-01-15 17:24:39 +00:00
}
}
private function fetchPages(string $userToken): array
{
try {
$response = Http::get('https://graph.facebook.com/v24.0/me/accounts', [
2026-01-15 17:24:39 +00:00
'access_token' => $userToken,
'fields' => 'id,name,username,picture{url},access_token',
]);
if ($response->failed()) {
Log::error('Facebook pages fetch failed', [
'status' => $response->status(),
'body' => $response->body(),
]);
return [];
}
$data = $response->json();
return collect(data_get($data, 'data', []))->map(fn ($page) => [
'id' => data_get($page, 'id'),
'name' => data_get($page, 'name'),
'username' => data_get($page, 'username', null),
'picture' => data_get($page, 'picture.data.url'),
'access_token' => data_get($page, 'access_token'),
2026-01-15 17:24:39 +00:00
])->toArray();
} catch (\Exception $e) {
Log::error('Facebook pages fetch error', [
'error' => $e->getMessage(),
]);
return [];
}
}
}