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

142 lines
5 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\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
2026-01-15 01:13:44 +00:00
use App\Models\Workspace;
use App\Services\Social\LinkedInTokenSynchronizer;
2026-01-15 01:13:44 +00:00
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
2026-01-15 01:13:44 +00:00
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpFoundation\Response;
class LinkedInController extends SocialController
{
protected string $driver = 'linkedin';
protected SocialPlatform $platform = SocialPlatform::LinkedIn;
public function connect(Request $request): Response|RedirectResponse
2026-01-15 01:13:44 +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);
2026-01-15 01:13:44 +00:00
fix(linkedin): drop deprecated r_basicprofile from default scopes Make r_basicprofile opt-in via LINKEDIN_EXTRA_SCOPES so self-hosted users unblock by default and ops with legacy/enterprise products keep working. Why --- LinkedIn rejects OAuth authorize requests with a generic "Bummer, something went wrong" page when an app asks for a scope it can't grant. `r_basicprofile` is a legacy scope deprecated in 2018; new LinkedIn dev apps don't have it, so every self-hosted user hits the rejection immediately on `/connect/linkedin`. The two products LinkedIn actually grants to standard apps today are: - Sign In with LinkedIn using OpenID Connect → `openid profile email` - Share on LinkedIn → `w_member_social` That set is enough for the connect flow. The only piece of data `r_basicprofile` was buying us is `/v2/me`'s `vanityName` (pretty `linkedin.com/in/<slug>`). `fetchVanityName()` already handles HTTP failure gracefully (returns null), and the only downstream consumer — `LinkedInPagePublisher`'s post-URL builder — already falls back to a numeric `linkedin.com/feed/update/<id>` URL when `$account->username` is null. Backward compatibility ---------------------- Ops with legacy or enterprise LinkedIn products approved on their dev app (so they DO have `r_basicprofile`) can opt back in via env: LINKEDIN_EXTRA_SCOPES=r_basicprofile `LinkedInController::resolveScopes()` merges this comma-separated list into the default scope array. The connect flow's `Socialite::scopes()` call then includes the legacy scope, preserving the pre-PR behaviour end-to-end (including `vanityName` lookup). Net effect for users without `r_basicprofile`: - Connect flow works (was previously rejected by LinkedIn). - Posts publish exactly the same way. - Generated post URLs use the numeric form instead of the vanity slug. Tests ----- - `linkedin connect requests the default scope set when LINKEDIN_EXTRA_SCOPES is unset` - `linkedin connect appends LINKEDIN_EXTRA_SCOPES to the default scope set` - Existing `splits comma-separated approvedScopes` fixture updated to match the new default set.
2026-05-28 03:54:26 +00:00
return $this->redirectToProvider($request, $this->driver, $this->resolveScopes());
}
/**
* Merge the default LinkedIn scopes with any extra scopes the operator
* configured via `LINKEDIN_EXTRA_SCOPES` comma-separated, e.g.
* `r_basicprofile`. Useful when the connected LinkedIn dev app has legacy
* or enterprise products not covered by the default Sign-In +
* Share-on-LinkedIn pair. Both live under
* `config/trypost.php` `platforms.linkedin`.
*
* @return array<int, string>
fix(linkedin): drop deprecated r_basicprofile from default scopes Make r_basicprofile opt-in via LINKEDIN_EXTRA_SCOPES so self-hosted users unblock by default and ops with legacy/enterprise products keep working. Why --- LinkedIn rejects OAuth authorize requests with a generic "Bummer, something went wrong" page when an app asks for a scope it can't grant. `r_basicprofile` is a legacy scope deprecated in 2018; new LinkedIn dev apps don't have it, so every self-hosted user hits the rejection immediately on `/connect/linkedin`. The two products LinkedIn actually grants to standard apps today are: - Sign In with LinkedIn using OpenID Connect → `openid profile email` - Share on LinkedIn → `w_member_social` That set is enough for the connect flow. The only piece of data `r_basicprofile` was buying us is `/v2/me`'s `vanityName` (pretty `linkedin.com/in/<slug>`). `fetchVanityName()` already handles HTTP failure gracefully (returns null), and the only downstream consumer — `LinkedInPagePublisher`'s post-URL builder — already falls back to a numeric `linkedin.com/feed/update/<id>` URL when `$account->username` is null. Backward compatibility ---------------------- Ops with legacy or enterprise LinkedIn products approved on their dev app (so they DO have `r_basicprofile`) can opt back in via env: LINKEDIN_EXTRA_SCOPES=r_basicprofile `LinkedInController::resolveScopes()` merges this comma-separated list into the default scope array. The connect flow's `Socialite::scopes()` call then includes the legacy scope, preserving the pre-PR behaviour end-to-end (including `vanityName` lookup). Net effect for users without `r_basicprofile`: - Connect flow works (was previously rejected by LinkedIn). - Posts publish exactly the same way. - Generated post URLs use the numeric form instead of the vanity slug. Tests ----- - `linkedin connect requests the default scope set when LINKEDIN_EXTRA_SCOPES is unset` - `linkedin connect appends LINKEDIN_EXTRA_SCOPES to the default scope set` - Existing `splits comma-separated approvedScopes` fixture updated to match the new default set.
2026-05-28 03:54:26 +00:00
*/
protected function resolveScopes(): array
{
/** @var array<int, string> $scopes */
$scopes = config('trypost.platforms.linkedin.scopes', []);
$extra = (string) config('trypost.platforms.linkedin.extra_scopes', '');
fix(linkedin): drop deprecated r_basicprofile from default scopes Make r_basicprofile opt-in via LINKEDIN_EXTRA_SCOPES so self-hosted users unblock by default and ops with legacy/enterprise products keep working. Why --- LinkedIn rejects OAuth authorize requests with a generic "Bummer, something went wrong" page when an app asks for a scope it can't grant. `r_basicprofile` is a legacy scope deprecated in 2018; new LinkedIn dev apps don't have it, so every self-hosted user hits the rejection immediately on `/connect/linkedin`. The two products LinkedIn actually grants to standard apps today are: - Sign In with LinkedIn using OpenID Connect → `openid profile email` - Share on LinkedIn → `w_member_social` That set is enough for the connect flow. The only piece of data `r_basicprofile` was buying us is `/v2/me`'s `vanityName` (pretty `linkedin.com/in/<slug>`). `fetchVanityName()` already handles HTTP failure gracefully (returns null), and the only downstream consumer — `LinkedInPagePublisher`'s post-URL builder — already falls back to a numeric `linkedin.com/feed/update/<id>` URL when `$account->username` is null. Backward compatibility ---------------------- Ops with legacy or enterprise LinkedIn products approved on their dev app (so they DO have `r_basicprofile`) can opt back in via env: LINKEDIN_EXTRA_SCOPES=r_basicprofile `LinkedInController::resolveScopes()` merges this comma-separated list into the default scope array. The connect flow's `Socialite::scopes()` call then includes the legacy scope, preserving the pre-PR behaviour end-to-end (including `vanityName` lookup). Net effect for users without `r_basicprofile`: - Connect flow works (was previously rejected by LinkedIn). - Posts publish exactly the same way. - Generated post URLs use the numeric form instead of the vanity slug. Tests ----- - `linkedin connect requests the default scope set when LINKEDIN_EXTRA_SCOPES is unset` - `linkedin connect appends LINKEDIN_EXTRA_SCOPES to the default scope set` - Existing `splits comma-separated approvedScopes` fixture updated to match the new default set.
2026-05-28 03:54:26 +00:00
if ($extra === '') {
return $scopes;
fix(linkedin): drop deprecated r_basicprofile from default scopes Make r_basicprofile opt-in via LINKEDIN_EXTRA_SCOPES so self-hosted users unblock by default and ops with legacy/enterprise products keep working. Why --- LinkedIn rejects OAuth authorize requests with a generic "Bummer, something went wrong" page when an app asks for a scope it can't grant. `r_basicprofile` is a legacy scope deprecated in 2018; new LinkedIn dev apps don't have it, so every self-hosted user hits the rejection immediately on `/connect/linkedin`. The two products LinkedIn actually grants to standard apps today are: - Sign In with LinkedIn using OpenID Connect → `openid profile email` - Share on LinkedIn → `w_member_social` That set is enough for the connect flow. The only piece of data `r_basicprofile` was buying us is `/v2/me`'s `vanityName` (pretty `linkedin.com/in/<slug>`). `fetchVanityName()` already handles HTTP failure gracefully (returns null), and the only downstream consumer — `LinkedInPagePublisher`'s post-URL builder — already falls back to a numeric `linkedin.com/feed/update/<id>` URL when `$account->username` is null. Backward compatibility ---------------------- Ops with legacy or enterprise LinkedIn products approved on their dev app (so they DO have `r_basicprofile`) can opt back in via env: LINKEDIN_EXTRA_SCOPES=r_basicprofile `LinkedInController::resolveScopes()` merges this comma-separated list into the default scope array. The connect flow's `Socialite::scopes()` call then includes the legacy scope, preserving the pre-PR behaviour end-to-end (including `vanityName` lookup). Net effect for users without `r_basicprofile`: - Connect flow works (was previously rejected by LinkedIn). - Posts publish exactly the same way. - Generated post URLs use the numeric form instead of the vanity slug. Tests ----- - `linkedin connect requests the default scope set when LINKEDIN_EXTRA_SCOPES is unset` - `linkedin connect appends LINKEDIN_EXTRA_SCOPES to the default scope set` - Existing `splits comma-separated approvedScopes` fixture updated to match the new default set.
2026-05-28 03:54:26 +00:00
}
$extraScopes = array_filter(array_map('trim', explode(',', $extra)));
return array_values(array_unique([...$scopes, ...$extraScopes]));
2026-01-15 01:13:44 +00:00
}
public function callback(Request $request): View
2026-01-15 01:13:44 +00:00
{
$workspaceId = session('social_connect_workspace');
if (! $workspaceId) {
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->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, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
2026-01-15 01:13:44 +00:00
}
try {
$socialUser = Socialite::driver($this->driver)->user();
// Fetch vanityName from LinkedIn API (not available via OpenID)
$username = $this->fetchVanityName($socialUser->token);
$avatarPath = uploadFromUrl($socialUser->getAvatar());
$account = $workspace->socialAccounts()->updateOrCreate(
[
'platform' => $this->platform->value,
'platform_user_id' => $socialUser->getId(),
],
[
'username' => $username,
'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,
// LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here.
'scopes' => explode(',', implode(',', $socialUser->approvedScopes)),
'status' => Status::Connected,
'error_message' => null,
'disconnected_at' => null,
],
);
2026-01-15 01:13:44 +00:00
// Sync tokens to LinkedIn Page if it exists
app(LinkedInTokenSynchronizer::class)->syncTokens($account);
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
2026-01-15 01:13:44 +00:00
} catch (\Exception $e) {
Log::error('LinkedIn OAuth Error', [
'error' => $e->getMessage(),
]);
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
2026-01-15 01:13:44 +00:00
}
}
private function fetchVanityName(string $accessToken): ?string
{
try {
$response = Http::withToken($accessToken)
->withHeaders(['X-RestLi-Protocol-Version' => '2.0.0'])
->get(config('trypost.platforms.linkedin.api').'/v2/me', [
2026-01-15 01:13:44 +00:00
'projection' => '(id,vanityName,localizedFirstName,localizedLastName)',
]);
if ($response->successful()) {
return $response->json('vanityName');
}
} catch (\Exception $e) {
Log::warning('Failed to fetch LinkedIn vanityName', [
'error' => $e->getMessage(),
]);
}
return null;
}
}