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

Auth Telegram Laravel Package

baks-dev/auth-telegram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baks-dev/auth-telegram
    php bin/console baks:assets:install
    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

    Verify the package is registered in config/packages/baks_auth_telegram.yaml.

  2. Configure Telegram Bot Add your bot token and allowed domains to .env:

    TELEGRAM_BOT_TOKEN=your_bot_token_here
    TELEGRAM_ALLOWED_DOMAINS=yourdomain.com,subdomain.yourdomain.com
    
  3. First Use Case: Login Button Add the login button to your Symfony template (e.g., base.html.twig):

    <a href="{{ path('baks_auth_telegram_login') }}" class="telegram-login-btn">
        Login with Telegram
    </a>
    

    The route baks_auth_telegram_login triggers the OAuth flow.


Implementation Patterns

Core Workflow

  1. OAuth Flow

    • User clicks the login button → redirected to Telegram’s OAuth URL.
    • Telegram redirects back to your app with a code parameter.
    • The package exchanges the code for a Telegram User object (via baks-dev/telegram-bot).
    • Creates/updates a user in your database (linked to the Telegram ID).
  2. User Model Integration Extend your User entity to include Telegram-specific fields:

    // src/Entity/User.php
    use Baks\AuthTelegram\Entity\TelegramUser;
    
    #[ORM\Embedded(class: TelegramUser::class)]
    private TelegramUser $telegram;
    

    The package provides a TelegramUser embeddable for storing:

    • telegramId (int)
    • username (string|null)
    • firstName (string)
    • lastName (string|null)
    • authDate (DateTimeImmutable)
  3. Guard Integration Configure the guard in config/packages/security.yaml:

    firewalls:
        main:
            telegram_authenticator: true  # Enables the TelegramAuthenticator
    
  4. Customizing User Resolution Override the default user resolver (e.g., to merge Telegram data with existing users):

    // config/packages/baks_auth_telegram.yaml
    baks_auth_telegram:
        user_resolver: App\Security\CustomTelegramUserResolver
    

    Implement Baks\AuthTelegram\Resolver\UserResolverInterface.


Integration Tips

  • CSRF Protection: The package handles CSRF for the OAuth callback. Ensure your form_login firewall is properly configured.
  • Multi-Bot Support: Use the telegram_bot service tag to register multiple bots:
    services:
        App\Telegram\CustomBot:
            tags: ['baks.telegram.bot']
    
  • Webhook Setup: If using Telegram webhooks (e.g., for updates), configure them separately via baks-dev/telegram-bot.
  • Testing: Run the package’s tests as a baseline:
    php bin/phpunit --group=auth-telegram
    

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatch

    • The package expects a telegram_user table or an embedded TelegramUser in your User entity.
    • Fix: Run migrations after installation or manually add the embeddable fields.
  2. CORS Issues

    • Telegram’s OAuth redirect may fail if your domain isn’t whitelisted in .env (TELEGRAM_ALLOWED_DOMAINS).
    • Fix: Add all domains (including localhost for development):
      TELEGRAM_ALLOWED_DOMAINS=localhost,127.0.0.1,yourdomain.com
      
  3. Bot Token Validation

    • The package silently fails if the bot token is invalid. Check logs for:
      Telegram API error: Bad Request: token invalid
      
    • Fix: Verify the token in @BotFather.
  4. User Merge Conflicts

    • If a user exists in your DB but lacks a telegramId, the package may create a duplicate.
    • Fix: Implement a custom UserResolver to merge users by email/username.
  5. PHP 8.4+ Requirements

    • The package requires PHP 8.4+. Downgrading may break type safety.
    • Fix: Use a compatible PHP version or fork the package.

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/dev/baks_auth_telegram.yaml:

    baks_auth_telegram:
        debug: true
    

    Logs OAuth flow details to var/log/dev.log.

  2. Inspect the Telegram User Object Dump the resolved user in a controller:

    use Baks\AuthTelegram\Resolver\UserResolverInterface;
    
    public function debugTelegramUser(UserResolverInterface $resolver): void
    {
        $user = $resolver->resolve(new TelegramUser($telegramId));
        dump($user);
    }
    
  3. Test Locally with ngrok If testing on localhost, expose your app via ngrok:

    ngrok http 8000
    

    Update TELEGRAM_ALLOWED_DOMAINS to include the ngrok URL (e.g., your-ngrok-url.ngrok.io).


Extension Points

  1. Custom User Attributes Extend the TelegramUser embeddable:

    #[ORM\Embeddable]
    class CustomTelegramUser extends TelegramUser
    {
        #[ORM\Column(nullable: true)]
        private ?string $languageCode = null;
    }
    
  2. Post-Auth Actions Listen to the telegram_auth_success event:

    // src/EventListener/TelegramAuthListener.php
    use Baks\AuthTelegram\Event\TelegramAuthSuccessEvent;
    use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
    
    #[AsEventListener(TelegramAuthSuccessEvent::class)]
    public function onTelegramAuth(TelegramAuthSuccessEvent $event): void
    {
        $user = $event->getUser();
        // Send welcome email, log activity, etc.
    }
    
  3. Rate Limiting Add rate limiting to the OAuth endpoint:

    # config/packages/security.yaml
    firewalls:
        main:
            telegram_authenticator: true
            pattern: ^/telegram/login
            limiter: { max: 5, interval: '1 minute' }
    
  4. Two-Factor Authentication (2FA) Combine with Symfony’s 2FA bundle:

    use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
    use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
    
    public function getPassport(): Passport
    {
        return new Passport(
            new UserBadge($this->telegramId, function () use ($telegramId) {
                return $this->userResolver->resolve($telegramId);
            }),
            new TotpBadge('telegram_2fa') // Add 2FA
        );
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky