PHPackages                             tourze/login-protect-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tourze/login-protect-bundle

ActiveSymfony-bundle[Authentication &amp; Authorization](/categories/authentication)

tourze/login-protect-bundle
===========================

Symfony bundle providing login protection and brute force attack prevention

1.0.1(6mo ago)01.3k1MITPHPCI passing

Since Apr 28Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/login-protect-bundle)[ Packagist](https://packagist.org/packages/tourze/login-protect-bundle)[ RSS](/packages/tourze-login-protect-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (40)Versions (12)Used By (1)

login-protect-bundle
====================

[](#login-protect-bundle)

[![PHP Version](https://camo.githubusercontent.com/ef363a5a30025ffef1857918c40fa01e97f03929e5f87d12a14bf334a7de9220/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d3838393242462e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](../../LICENSE)[![Build Status](https://camo.githubusercontent.com/c27a457659b89ee4f1f80f7995c559dd37f2051bde7167ad25791e5c5c92cc8e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d627269676874677265656e2e737667)](#)[![Code Coverage](https://camo.githubusercontent.com/b3545ae1bcdb4ea486f71f87b43001e82dd21933bc8035d44601706c851265da/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e2e737667)](#)

[English](README.md) | [中文](README.zh-CN.md)

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

Features
--------

[](#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
------------

[](#installation)

```
composer require tourze/login-protect-bundle
```

Configuration
-------------

[](#configuration)

### 1. Bundle Registration

[](#1-bundle-registration)

Add the bundle to your `config/bundles.php`:

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

### 2. Environment Variables

[](#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

[](#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
-----

[](#usage)

### Basic 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

[](#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
--------------

[](#advanced-usage)

### Custom Login Check

[](#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
--------

[](#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

[](#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
------

[](#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
------------------

[](#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
------------

[](#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
-------

[](#testing)

Run tests:

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

Dependencies
------------

[](#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
-------

[](#license)

MIT License. See [LICENSE](../../LICENSE) for details.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance72

Regular maintenance activity

Popularity14

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Recently: every ~46 days

Total

11

Last Release

182d ago

Major Versions

0.1.4 → 1.0.02025-11-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-login-protect-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-login-protect-bundle/health.svg)](https://phpackages.com/packages/tourze-login-protect-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
