Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Platform Sso Twitter Bundle Laravel Package

digitalstate/platform-sso-twitter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require digitalstate/platform-sso-twitter-bundle
    

    Ensure DigitalState\PlatformSsoTwitterBundle\DigitalStatePlatformSsoTwitterBundle is registered in config/bundles.php.

  2. Configure Twitter App Credentials Navigate to System → Configuration → Integrations → Twitter Settings in the Oro admin panel. Add your Twitter API credentials:

    • Consumer Key
    • Consumer Secret
    • Callback URL (e.g., https://your-app.com/connect/twitter/check)
  3. Enable Twitter SSO In the same configuration section, toggle Enable Twitter SSO to true.

  4. Test the Flow

    • Visit /connect/twitter (or your configured route).
    • Authenticate via Twitter and verify redirection to your app.

First Use Case: Quick Integration

For a developer needing to add Twitter SSO to an existing OroPlatform app:

  1. Extend the SSO Provider Override the default Twitter provider if custom logic is needed (see src/Resources/config/services.yml for service definitions). Example:

    # config/packages/digitalstate_platform_sso_twitter.yaml
    services:
        DigitalState\PlatformSsoTwitterBundle\Provider\TwitterProvider:
            arguments:
                $clientId: '%env(TWITTER_CONSUMER_KEY)%'
                $clientSecret: '%env(TWITTER_CONSUMER_SECRET)%'
                $callbackUrl: '%env(TWITTER_CALLBACK_URL)%'
    
  2. Customize User Mapping If Twitter user data needs to map to custom user fields, extend the UserMapper service:

    // src/DigitalState/PlatformSsoTwitterBundle/DependencyInjection/Compiler/UserMapperPass.php
    public function process(ContainerBuilder $container)
    {
        $definition = $container->findDefinition('digitalstate_platform_sso_twitter.user_mapper');
        $definition->addMethodCall('setCustomFieldMapper', [[$this->getCustomMapper()]]);
    }
    

Implementation Patterns

Workflow: OAuth Flow Integration

  1. Initiate Login Trigger the OAuth flow via the /connect/twitter route (handled by TwitterAuthController).

    // Example: Custom route for Twitter login
    $router->add('/custom-twitter-login', 'DigitalState\PlatformSsoTwitterBundle\Controller\TwitterAuthController::login');
    
  2. Handle Callback The bundle automatically processes the Twitter OAuth callback at /connect/twitter/check. Extend the TwitterProvider to add pre/post-auth logic:

    // src/Service/TwitterCustomProvider.php
    class TwitterCustomProvider extends TwitterProvider
    {
        public function getUserData(array $response)
        {
            $data = parent::getUserData($response);
            $data['custom_field'] = $this->fetchCustomData($response['id']);
            return $data;
        }
    }
    
  3. Post-Auth Actions Use Oro’s event system to react to successful logins:

    # config/services.yaml
    services:
        App\EventListener\TwitterLoginListener:
            tags:
                - { name: kernel.event_listener, event: digitalstate_platform_sso.login.success, method: onTwitterLogin }
    

Integration Tips

  • Environment Variables Store credentials in .env:

    TWITTER_CONSUMER_KEY=your_key
    TWITTER_CONSUMER_SECRET=your_secret
    TWITTER_CALLBACK_URL=https://your-app.com/connect/twitter/check
    
  • Route Customization Override the default routes in config/routes.yaml:

    digitalstate_platform_sso_twitter:
        resource: "@DigitalStatePlatformSsoTwitterBundle/Resources/config/routes.yml"
        prefix: /custom-prefix
    
  • User Entity Mapping Ensure your User entity extends Oro’s User and includes required fields (e.g., twitterId):

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $twitterId;
    

Gotchas and Tips

Pitfalls

  1. Callback URL Mismatch

    • Issue: Twitter OAuth fails with redirect_uri_mismatch.
    • Fix: Ensure the callback URL in Twitter’s developer portal matches exactly (including http/https and trailing slashes).
  2. Missing User Fields

    • Issue: Twitter user data isn’t saved to the local user entity.
    • Fix: Extend the UserMapper to include all required fields:
      $mapper->mapUserField('twitterId', 'id');
      $mapper->mapUserField('twitterScreenName', 'screen_name');
      
  3. CORS Issues

    • Issue: OAuth redirect fails due to CORS.
    • Fix: Configure your server to allow requests from Twitter’s domains:
      location /connect/twitter {
          if_is_args ~* (code=.*):
                  add_header 'Access-Control-Allow-Origin' 'https://api.twitter.com';
      }
      

Debugging

  • Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        twitter_sso:
            type: stream
            path: "%kernel.logs_dir%/twitter_sso.log"
            level: debug
            channels: ["digitalstate_platform_sso"]
    
  • Check OAuth Tokens Inspect the digitalstate_platform_sso_twitter channel in logs for token errors:

    [2023-01-01 12:00:00] digitalstate_platform_sso.TRACE: OAuth token request failed: {"error":"invalid_request"} []
    

Extension Points

  1. Custom Provider Logic Override TwitterProvider to add logic before/after token exchange:

    class CustomTwitterProvider extends TwitterProvider
    {
        public function authenticate(array $credentials)
        {
            // Add custom validation
            if (!$this->isValidTwitterUser($credentials)) {
                throw new AuthenticationException('Invalid Twitter user.');
            }
            return parent::authenticate($credentials);
        }
    }
    
  2. Event Subscribers Listen for SSO events to trigger actions:

    // src/EventListener/TwitterSSOListener.php
    class TwitterSSOListener
    {
        public function onLoginSuccess(LoginSuccessEvent $event)
        {
            if ($event->getProviderName() === 'twitter') {
                $this->logTwitterLogin($event->getUser());
            }
        }
    }
    
  3. Configuration Overrides Dynamically adjust settings via dependency injection:

    # config/packages/digitalstate_platform_sso_twitter.yaml
    digitalstate_platform_sso_twitter:
        enabled: '%env(bool:TWITTER_SSO_ENABLED)%'
        scope: ['user.read', 'tweet.read'] # Custom OAuth scopes
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle