PHPackages                             yii2tech/authlog - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. yii2tech/authlog

AbandonedArchivedYii2-extension[Logging &amp; Monitoring](/categories/logging)

yii2tech/authlog
================

Provides support for Identity auth tracking and brute-force protection

1.0.1(8y ago)3596.7k—3.4%62BSD-3-ClausePHP

Since Feb 10Pushed 6y ago5 watchersCompare

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

READMEChangelogDependencies (1)Versions (4)Used By (2)

 [ ![](https://avatars2.githubusercontent.com/u/12951949) ](https://github.com/yii2tech)

Identity Authentication Tracking extension for Yii2
===================================================

[](#identity-authentication-tracking-extension-for-yii2)

This extension provides identity authentication logging and tracking mechanism, which can be used for 'brute-force' attack protection.

For license information check the [LICENSE](LICENSE.md)-file.

[![Latest Stable Version](https://camo.githubusercontent.com/83446f33e9eb4ac8b68005081b2485c7fd1cbd58c475eaf7c53d429e0d7c3a84/68747470733a2f2f706f7365722e707567782e6f72672f79696932746563682f617574686c6f672f762f737461626c652e706e67)](https://packagist.org/packages/yii2tech/authlog)[![Total Downloads](https://camo.githubusercontent.com/3cc042ec09699b322e56c35cc2b3445ddfd40e50555d03a2e20ad533cacb9132/68747470733a2f2f706f7365722e707567782e6f72672f79696932746563682f617574686c6f672f646f776e6c6f6164732e706e67)](https://packagist.org/packages/yii2tech/authlog)[![Build Status](https://camo.githubusercontent.com/1ff915375c2bc3786ddb2b38e758224cc0c6967383d264a1420622baa986e037/68747470733a2f2f7472617669732d63692e6f72672f79696932746563682f617574686c6f672e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/yii2tech/authlog)

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist yii2tech/authlog

```

or add

```
"yii2tech/authlog": "*"
```

to the require section of your composer.json.

Usage
-----

[](#usage)

This extension provides identity authentication logging and tracking mechanism, which can be used for 'brute-force' attack protection.

Extension works through the ActiveRecord entity for the authentication attempt log. The database migration for such entity creation can be following:

```
$this->createTable('UserAuthLog', [
    'id' => $this->primaryKey(),
    'userId' => $this->integer(),
    'date' => $this->integer(),
    'cookieBased' => $this->boolean(),
    'duration' => $this->integer(),
    'error' => $this->string(),
    'ip' => $this->string(),
    'host' => $this->string(),
    'url' => $this->string(),
    'userAgent' => $this->string(),
]);
```

ActiveRecord model, which implements \[\[\\yii\\web\\IdentityInterface\]\] should declare a 'has many' relation to this entity. The logging mechanism is provided via \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] behavior, which should be as well attached to the identity class. For example:

```
use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii2tech\authlog\AuthLogIdentityBehavior;

class User extends ActiveRecord implements IdentityInterface
{
    public function behaviors()
    {
        return [
            'authLog' => [
                'class' => AuthLogIdentityBehavior::className(),
                'authLogRelation' => 'authLogs',
                'defaultAuthLogData' => function ($model) {
                    return [
                        'ip' => Yii::$app->request->getUserIP(),
                        'host' => @gethostbyaddr(Yii::$app->request->getUserIP()),
                        'url' => Yii::$app->request->getAbsoluteUrl(),
                        'userAgent' => Yii::$app->request->getUserAgent(),
                    ];
                },
            ],
        ];
    }

    public function getAuthLogs()
    {
        return $this->hasMany(UserAuthLog::className(), ['userId' => 'id']);
    }

    // ...
}
```

> Note: because \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] works through ActiveRecord the auth log storage can be any one, which have ActiveRecord layer implemented, such as Redis, MongoDB etc.

Being attached \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] provides basic auth logging and statistic methods:

- `logAuth()` writes auth log entry
- `logAuthError()` writes auth log error entry
- `getLastSuccessfulAuthLog()` returns last successful auth log entry
- `getPreLastSuccessfulAuthLog()` returns pre-last successful auth log entry
- `getLastLoginDate()` returns last successful login date
- `getPreLastLoginDate()` returns pre-last successful login date
- `hasFailedLoginSequence()` checks if there is sequence of failed login attempts of request length starting from now

Refer to \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] for details about configuration and available methods.

Keep in mind that \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] does NOT log authentication attempts automatically. You'll have to invoke logging methods manually in a proper place to do so. However this extension provides other tools, which cover this task.

Automatic authentication logging
---------------------------------

[](#automatic-authentication-logging-)

Although \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] provides the basis for the auth logging, it does not log anything automatically. Automatic logging of the successful authentication attempts are provided via \[\[\\yii2tech\\authlog\\AuthLogWebUserBehavior\]\] behavior. \[\[\\yii2tech\\authlog\\AuthLogWebUserBehavior\]\] should be attached to the 'user' application component (instance of \[\[\\yii\\web\\User\]\]). This could be done at the application configuration:

```
return [
    'components' => [
        'user' => [
            'identityClass' => 'app\models\User',
            'loginUrl' => ['site/login'],
            'as authLog' => [
                'class' => 'yii2tech\authlog\AuthLogWebUserBehavior'
            ],
        ],
        // ...
    ],
    // ...
];
```

\[\[\\yii2tech\\authlog\\AuthLogWebUserBehavior\]\] relies identity class has a \[\[\\yii2tech\\authlog\\AuthLogIdentityBehavior\]\] attached and writes auth log on any successful login made through owner \[\[\\yii\\web\\User\]\] component, including the ones based on cookie. However, this behavior can not log any failed authentication attempt, which should be done elsewhere like login form.

Logging authentication failures
--------------------------------

[](#logging-authentication-failures-)

Logging authentication failures is specific to the authentication method used by application. Thus you are responsible of its performing by yourself.

Most common authentication method is usage of username/password pair, which is asked via login web form. In such workflow authentication failure should be written on invalid password entered. This extension provides \[\[\\yii2tech\\authlog\\AuthLogLoginFormBehavior\]\] behavior, which can be attached to the login form model, providing authentication failures logging feature. For example:

```
use app\models\User;
use yii2tech\authlog\AuthLogLoginFormBehavior;

class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    public function behaviors()
    {
        return [
            'authLog' => [
                'class' => AuthLogLoginFormBehavior::className(),
                'findIdentity' => 'findIdentity',
            ],
        ];
    }

    public function findIdentity()
    {
        return User::findByUsername($this->username);
    }

    // ...
}
```

\[\[\\yii2tech\\authlog\\AuthLogLoginFormBehavior\]\] automatically logs failure authentication attempt on owner validation in case identity is found and there is any error on \[\[\\yii2tech\\authlog\\AuthLogLoginFormBehavior::$verifyIdentityAttributes\]\].

"Brute force" protection
-------------------------

[](#brute-force-protection-)

In addition to simple logging \[\[\\yii2tech\\authlog\\AuthLogLoginFormBehavior\]\] provide built-in "brute force" attack protection mechanism, which have 2 levels:

- require robot verification (CAPTCHA) after \[\[\\yii2tech\\authlog\\AuthLogLoginFormBehavior::$verifyRobotFailedLoginSequence\]\] sequence login failures
- deactivation of the identity record after \[\[\\yii2tech\\authlog\\AuthLogLoginFormBehavior::$deactivateFailedLoginSequence\]\] sequence login failures

For example:

```
use app\models\User;
use yii2tech\authlog\AuthLogLoginFormBehavior;

class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    public $verifyCode;

    public function behaviors()
    {
        return [
            'authLog' => [
                'class' => AuthLogLoginFormBehavior::className(),
                'findIdentity' => 'findIdentity',
                'verifyRobotAttribute' => 'verifyCode',
                'deactivateIdentity' => function ($identity) {
                    return $this->updateAttributes(['statusId' => User::STATUS_SUSPENDED]);
                },
            ],
        ];
    }

    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            ['rememberMe', 'boolean'],
            ['password', 'validatePassword'],
            ['verifyCode', 'safe'],
        ];
    }

    public function findIdentity()
    {
        return User::findByUsername($this->username);
    }

    // ...
}
```

Robot verification requires extra processing at the view layer, which should render CAPTCHA only if it is necessary:

```
