# Required OAuth integration

The app settings screen stores credentials; OAuth handlers must read them. In `OAuthController.php`:

1. Add `use App\Services\OrganizationOAuthConfig;`.
2. Change `redirect(Request $r, string $platform)` to inject `OrganizationOAuthConfig $oauthConfig`, then replace:

   `$c = config("social.$platform");`

   with:

   `$orgId = (int) app('currentOrg')->id;`
   `$c = $oauthConfig->forOrganization($orgId, $platform);`

   The existing session state should keep this `$orgId` as `org`.

3. In `callback(...)`, inject the same service and replace the global config lookup with:

   `$c = $oauthConfig->forOrganization((int) $saved['org'], $platform);`

4. Ensure callback processing checks that the authenticated user still belongs to `$saved['org']` before storing accounts. Keep the callback URL generated by the app (`url('/connect/...')`), and verify the provider redirect URI exactly matches the one registered in the business's developer console.

5. Meta Socialite needs extra wiring because its driver configuration is commonly loaded from `config/services.php`. Configure a request-scoped provider instance from the selected organization's client ID/secret or use the provider's direct OAuth client; do not mutate global config in a long-running worker. Save Meta app credentials per organization too.

6. Update publisher/token refresh clients to use the organization's platform app only where needed. Account access/refresh tokens are separate from client secrets and must be encrypted in the SocialAccount model.

Never let the client submit an organization ID and trust it as authorization. Resolve the current organization from authenticated membership and validate the stored OAuth `state` value on callback.
