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

Dark Portal Bundle Laravel Package

chrisyue/dark-portal-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chrisyue/dark-portal-bundle:dev-master
    

    Add the bundle to your AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3.x+):

    new Chrisyue\DarkPortalBundle\ChrisyueDarkPortalBundle(),
    
  2. Configure Security Update config/packages/security.yaml (or app/config/security.yml for Symfony 2.x):

    providers:
        oauth:
            id: chrisyue_dark_portal.security.user.provider
    
    firewalls:
        secured_area:
            pattern: ^/
            oauth_code:
                appid: "%env(OAUTH_APP_ID)%"
                secret: "%env(OAUTH_SECRET)%"
                scope: "snsapi_login"
                code_endpoint: "http://oauth-code.xxx.com/get-code.php"
            provider: oauth
    
  3. Deploy the Code Endpoint Download get-code.php and place it on your dedicated oauth-code.xxx.com server. Configure allowed hosts in the script:

    $hosts = [
        'wechat.xxx.com',
        'weixin.xxx.com',
    ];
    
  4. First Use Case Redirect users to the OAuth provider (e.g., WeChat) via:

    return $this->get('security.token_storage')->getToken()->getUser()->getAuthenticator()->getLoginUrl();
    

    The bundle handles the code exchange transparently, allowing multi-host redirects.


Implementation Patterns

Workflow Integration

  1. Multi-Host OAuth Flow

    • Use oauth-code.xxx.com as a single entry point for all OAuth code requests.
    • Configure allowed hosts in get-code.php to validate redirects.
    • After obtaining the code, the bundle exchanges it for an access_token without host restrictions.
  2. Symfony Security Integration

    • Leverage Symfony’s UserProvider to fetch user data after token acquisition.
    • Example provider implementation:
      // src/Security/OAuthUserProvider.php
      use Chrisyue\DarkPortalBundle\Security\User\OAuthUserProvider as BaseProvider;
      
      class OAuthUserProvider extends BaseProvider {
          public function loadUserByOAuthToken($token) {
              // Custom logic to fetch user from OAuth API
          }
      }
      
  3. Dynamic Endpoint Configuration

    • Use environment variables for code_endpoint in security.yaml:
      oauth_code:
          code_endpoint: "%env(OAUTH_CODE_ENDPOINT)%"
      
    • Deploy get-code.php to a subdomain or separate server for isolation.
  4. CSRF Protection

    • The get-code.php script includes CSRF checks. Ensure your frontend includes a hidden CSRF token in the OAuth redirect.
  5. State Parameter Handling

    • Pass a state parameter (e.g., ?state=wechat) to distinguish between multiple OAuth providers or flows.

Gotchas and Tips

Pitfalls

  1. Host Validation Strictness

    • The get-code.php script strictly checks the Referer header against $hosts. If a request comes from an unallowed domain, it fails silently (no error message by default).
    • Fix: Add logging or a redirect to a fallback page in get-code.php:
      if (!in_array($_SERVER['HTTP_REFERER'], $hosts)) {
          error_log("Invalid referer: " . $_SERVER['HTTP_REFERER']);
          header("Location: /error");
          exit;
      }
      
  2. Token Exchange Failures

    • If the code expires before exchange, the OAuth provider may return an error. Ensure get-code.php is highly available and the code is exchanged promptly.
    • Tip: Use a queue (e.g., Symfony Messenger) to process code exchange asynchronously if latency is a concern.
  3. CORS Issues

    • If your frontend and oauth-code.xxx.com are on different domains, ensure CORS headers are set in get-code.php:
      header("Access-Control-Allow-Origin: https://wechat.xxx.com");
      
  4. State Parameter Mismatch

    • Always include and validate the state parameter to prevent CSRF attacks. The bundle does not handle this by default.
    • Example:
      // In get-code.php
      if ($_GET['state'] !== $_SESSION['expected_state']) {
          die("Invalid state");
      }
      
  5. Environment-Specific Config

    • Avoid hardcoding code_endpoint in security.yaml. Use %kernel.environment% or environment variables:
      code_endpoint: "%env(OAUTH_CODE_ENDPOINT_%kernel.environment%)%"
      

Debugging Tips

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

    handlers:
        oauth:
            type: stream
            path: "%kernel.logs_dir%/oauth.log"
            level: debug
            channels: ["oauth"]
    

    Then log critical steps in OAuthUserProvider.

  2. Test with Postman/cURL Manually trigger the OAuth flow to debug:

    curl -v "https://oauth-code.xxx.com/get-code.php?code=AUTH_CODE&state=test"
    
  3. Check get-code.php Permissions Ensure the script has:

    • Write permissions to log errors.
    • Access to session.save_path if using PHP sessions.

Extension Points

  1. Custom User Provider Extend BaseOAuthUserProvider to add logic like:

    • User role mapping from OAuth data.
    • Custom token validation.
  2. Multi-Provider Support Modify get-code.php to accept a provider parameter (e.g., ?provider=wechat) and route to different OAuth endpoints.

  3. Token Storage Override the default token storage to persist access_token and refresh_token in your database:

    // src/Security/OAuthTokenStorage.php
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class OAuthTokenStorage implements TokenStorageInterface {
        public function setToken(TokenInterface $token) {
            // Save token to DB
            parent::setToken($token);
        }
    }
    
  4. Webhook for Token Refresh Use the bundle’s refresh_token endpoint (if supported by the provider) to silently refresh tokens in the background.

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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours