tourze/login-protect-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

tourze/login-protect-bundle

Composer 安装命令:

composer require tourze/login-protect-bundle

包简介

Symfony bundle providing login protection and brute force attack prevention

README 文档

README

PHP Version License Build Status Code Coverage

English | 中文

A Symfony bundle that provides comprehensive login protection features including failed login attempt tracking, automatic account locking, and login activity logging.

Features

  • Login Attempt Tracking: Records all login attempts (success/failure/logout) with IP addresses
  • Account Locking: Automatically locks accounts after multiple failed login attempts
  • Configurable Lock Duration: Environment variable control for lock timeout
  • IP Tracking: Tracks IP addresses for security auditing
  • Async Logging: Uses async database insertion for better performance
  • Data Cleanup: Automatic cleanup of old login logs via scheduled tasks

Installation

composer require tourze/login-protect-bundle

Configuration

1. Bundle Registration

Add the bundle to your config/bundles.php:

return [
    // ... other bundles
    Tourze\LoginProtectBundle\LoginProtectBundle::class => ['all' => true],
];

2. Environment Variables

Configure lock duration in your .env file:

# Lock duration in minutes after too many failed attempts (default: 30)
LOGIN_ATTEMPT_FAIL_LOCK_MINUTE=30

# How many days to keep login logs (default: 120)
LOGIN_LOG_PERSIST_DAY_NUM=120

3. Database Migration

Create the database table for login logs:

CREATE TABLE login_attempt (
    id BIGINT NOT NULL PRIMARY KEY,
    identifier VARCHAR(120) NOT NULL COMMENT '唯一标志',
    action VARCHAR(20) NOT NULL COMMENT '登录结果',
    unlock_time DATETIME DEFAULT NULL COMMENT '解锁时间',
    session_id VARCHAR(100) DEFAULT '' COMMENT '会话ID',
    created_from_ip VARCHAR(45) DEFAULT NULL COMMENT '创建时IP',
    create_time DATETIME NOT NULL COMMENT '创建时间',
    INDEX idx_identifier (identifier),
    INDEX idx_action (action),
    INDEX idx_session_id (session_id)
);

Usage

Basic Usage

The bundle automatically tracks login events through Symfony's security events. No additional code is required for basic functionality.

Manual Login Logging

If you need to manually log login events:

use Tourze\LoginProtectBundle\Service\LoginService;

class YourController
{
    public function __construct(
        private LoginService $loginService
    ) {}
    
    public function someAction()
    {
        // Log successful login
        $this->loginService->saveLoginLog($user, 'success', $sessionId);
        
        // Log failed login
        $this->loginService->saveLoginLog($userIdentifier, 'failure');
        
        // Log logout
        $this->loginService->saveLoginLog($user, 'logout');
    }
}

Advanced Usage

Custom Login Check

You can dispatch BeforeLoginEvent to trigger login protection checks:

use Tourze\LoginProtectBundle\Event\BeforeLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class YourAuthenticator
{
    public function authenticate(Request $request): ?Passport
    {
        // ... get user ...
        
        // Check if user is locked
        $event = new BeforeLoginEvent($user);
        $this->eventDispatcher->dispatch($event);
        
        // If user is locked, LockedAuthenticationException will be thrown
        
        return $passport;
    }
}

Security

This bundle provides several security features:

  • Brute Force Protection: Automatically locks accounts after multiple failed attempts
  • IP Tracking: Records IP addresses for security auditing and forensic analysis
  • Login Activity Monitoring: Comprehensive logging of all authentication events
  • Configurable Lock Policies: Customizable lock duration based on security requirements

Security Considerations

  • Ensure proper configuration of lock duration to balance security and usability
  • Monitor login logs regularly for suspicious activity
  • Consider implementing additional rate limiting at the network level
  • Use HTTPS to protect login credentials in transit

Events

The bundle listens to these Symfony security events:

  • LoginSuccessEvent: Records successful logins
  • LoginFailureEvent: Records failed attempts and may set unlock time
  • LogoutEvent: Records logout events

Exception Handling

The bundle throws LockedAuthenticationException when an account is locked. Handle it in your authentication flow:

try {
    // authentication logic
} catch (LockedAuthenticationException $e) {
    // Account is locked, show appropriate message
    return new Response('Account locked due to too many failed attempts');
}

Data Cleanup

Login logs are automatically cleaned up based on the scheduled task configuration. The default retention period is 120 days, configurable via LOGIN_LOG_PERSIST_DAY_NUM environment variable.

Testing

Run tests:

vendor/bin/phpunit packages/login-protect-bundle/tests

Dependencies

  • PHP 8.1+
  • Symfony 6.4+
  • Doctrine ORM 3.0+
  • tourze/doctrine-async-insert-bundle
  • tourze/doctrine-indexed-bundle
  • tourze/doctrine-ip-bundle
  • tourze/doctrine-snowflake-bundle
  • tourze/doctrine-timestamp-bundle

License

MIT License. See LICENSE for details.

tourze/login-protect-bundle 适用场景与选型建议

tourze/login-protect-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.37k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 04 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 tourze/login-protect-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 tourze/login-protect-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 tourze/login-protect-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.37k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 13
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-28