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.
141 lines
4.9 KiB
PHP
141 lines
4.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Auth;
|
|
|
|
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
|
use App\Enums\SocialAccount\Status;
|
|
use App\Models\Workspace;
|
|
use App\Services\Social\LinkedInTokenSynchronizer;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\View\View;
|
|
use Laravel\Socialite\Facades\Socialite;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class LinkedInController extends SocialController
|
|
{
|
|
protected string $driver = 'linkedin';
|
|
|
|
protected SocialPlatform $platform = SocialPlatform::LinkedIn;
|
|
|
|
protected array $scopes = [
|
|
'openid',
|
|
'profile',
|
|
'email',
|
|
'w_member_social',
|
|
];
|
|
|
|
public function connect(Request $request): Response|RedirectResponse
|
|
{
|
|
$this->ensurePlatformEnabled();
|
|
|
|
$workspace = $request->user()->currentWorkspace;
|
|
|
|
if (! $workspace) {
|
|
return redirect()->route('app.workspaces.create');
|
|
}
|
|
|
|
$this->authorize('manageAccounts', $workspace);
|
|
|
|
return $this->redirectToProvider($request, $this->driver, $this->resolveScopes());
|
|
}
|
|
|
|
/**
|
|
* Merge $this->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.
|
|
*/
|
|
protected function resolveScopes(): array
|
|
{
|
|
$extra = (string) config('services.linkedin.extra_scopes', '');
|
|
|
|
if ($extra === '') {
|
|
return $this->scopes;
|
|
}
|
|
|
|
$extraScopes = array_filter(array_map('trim', explode(',', $extra)));
|
|
|
|
return array_values(array_unique([...$this->scopes, ...$extraScopes]));
|
|
}
|
|
|
|
public function callback(Request $request): View
|
|
{
|
|
$workspaceId = session('social_connect_workspace');
|
|
|
|
if (! $workspaceId) {
|
|
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
|
|
}
|
|
|
|
$workspace = Workspace::find($workspaceId);
|
|
|
|
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
|
|
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
|
|
}
|
|
|
|
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,
|
|
],
|
|
);
|
|
|
|
// Sync tokens to LinkedIn Page if it exists
|
|
app(LinkedInTokenSynchronizer::class)->syncTokens($account);
|
|
|
|
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
|
|
} catch (\Exception $e) {
|
|
Log::error('LinkedIn OAuth Error', [
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
|
|
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
|
|
}
|
|
}
|
|
|
|
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', [
|
|
'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;
|
|
}
|
|
}
|