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

Ajax Login Bundle Laravel Package

divi/ajax-login-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    • Add divi/ajax-login-bundle to composer.json under "require" with "dev-master" (or a stable version if available).
    • Run composer update divi/ajax-login-bundle.
    • Enable the bundle in AppKernel.php:
      new Divi\AjaxLoginBundle\DiviAjaxLoginBundle(),
      
  2. Configure Security: Replace form_login with ajax_form_login in security.yml:

    security:
        firewalls:
            main:
                pattern: ^/
                ajax_form_login:
                    login_path: /login
                    check_path: /login_check
                    always_use_default_target_path: true
                    # Optional: Customize failure path, username/email parameter, etc.
    
  3. First Use Case:

    • Replace your existing login form template with one of the provided examples in Resources/views/Login/ (e.g., ajax_login.html.twig).
    • Ensure jQuery is loaded (the bundle auto-loads it via Google if missing).
    • Submit the form via AJAX (e.g., using jQuery’s .ajax() or .submit() with event.preventDefault()).

Implementation Patterns

Core Workflows

  1. Form Integration:

    • Use the provided Twig templates (ajax_login.html.twig or fos_ajax_login.html.twig) as a starting point.
    • Bind form submission to an AJAX handler:
      $('#login-form').submit(function(e) {
          e.preventDefault();
          $.ajax({
              url: $(this).attr('action'),
              type: 'POST',
              data: $(this).serialize(),
              success: function(data) {
                  if (data.redirect) {
                      window.location.href = data.redirect;
                  } else {
                      // Handle errors (e.g., display messages)
                      $('#login-errors').html(data.errors);
                  }
              }
          });
      });
      
  2. CSRF Protection:

    • The bundle handles CSRF tokens automatically. Ensure your form includes the hidden _csrf_token field:
      {{ form_hidden(form._csrf_token) }}
      
  3. Authentication Handling:

    • After successful login, the bundle redirects to default_target_path (configured in security.yml). Override this in your controller if needed:
      ajax_form_login:
          default_target_path: /dashboard
      
  4. Integration with FOSUserBundle:

    • Use fos_ajax_login.html.twig if using FOSUserBundle. Extend the form type if custom fields are needed:
      // src/Acme/UserBundle/Form/Type/RegistrationFormType.php
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          parent::buildForm($builder, $options);
          $builder->add('custom_field', TextType::class);
      }
      
  5. Dynamic jQuery Loading:

    • The bundle auto-loads jQuery from Google’s CDN if not detected. Disable this in config.yml:
      divi_ajax_login:
          load_jquery: false
      

Gotchas and Tips

Pitfalls and Debugging

  1. CSRF Token Mismatch:

    • If AJAX requests fail with "CSRF token invalid," ensure:
      • The token is included in the form data.
      • The route generating the token matches the submission route (e.g., /login_check).
    • Regenerate tokens if testing locally with php bin/console cache:clear.
  2. jQuery Conflicts:

    • If jQuery is already loaded (e.g., via another bundle), disable auto-loading in config.yml to avoid conflicts:
      divi_ajax_login:
          load_jquery: false
      
  3. Symfony 2.1+ Requirement:

    • The bundle will not work on Symfony 2.0. Use the 2.0-2.1 branch explicitly if needed.
  4. FOSUserBundle Compatibility:

    • If using FOSUserBundle, ensure the User class is properly configured in security.yml:
      providers:
          fos_userbundle:
              id: fos_user.user_provider.username_email
      
    • Override the login template path if using custom FOS templates:
      ajax_form_login:
          login_path: /login
          check_path: /login_check
          always_use_default_target_path: true
          template: AcmeUserBundle:Security:ajax_login.html.twig
      
  5. Redirect Handling:

    • The bundle returns a JSON response with a redirect key on success. Always check for this in your AJAX success handler:
      success: function(data) {
          if (data.redirect) window.location.href = data.redirect;
          else console.error('Login failed:', data);
      }
      
  6. Custom Error Messages:

    • To customize error messages, override the bundle’s error handler in your controller or via Twig:
      {% if error %}
          <div class="alert alert-danger">
              {{ error.message|trans }}
          </div>
      {% endif %}
      
  7. Extension Points:

    • Event Listeners: Extend login logic via Symfony events (e.g., security.interactive_login).
    • Custom Responses: Override the bundle’s response logic by extending the AjaxLoginListener class and replacing the service:
      # app/config/services.yml
      services:
          acme.ajax_login.listener:
              class: Acme\AjaxLoginBundle\EventListener\CustomAjaxLoginListener
              tags:
                  - { name: kernel.event_listener, event: security.interactive_login, method: onLogin }
      
  8. Testing:

    • Mock AJAX requests in PHPUnit using HttpKernel:
      $client = static::createClient();
      $client->request('POST', '/login_check', [
          'username' => 'test',
          'password' => 'test',
          '_csrf_token' => $client->getContainer()->get('session')->get('_csrf')->getToken('authenticate')->getValue(),
      ]);
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle