{"id":15169742,"url":"https://github.com/yii2tech/authlog","last_synced_at":"2025-10-01T02:31:44.927Z","repository":{"id":57087032,"uuid":"48946992","full_name":"yii2tech/authlog","owner":"yii2tech","description":"Identity auth tracking","archived":true,"fork":false,"pushed_at":"2019-07-03T12:59:07.000Z","size":31,"stargazers_count":35,"open_issues_count":0,"forks_count":6,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-09-18T22:32:58.898Z","etag":null,"topics":["auth","brute-force","log","logging","yii","yii2","yii2-extension"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yii2tech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-01-03T13:40:25.000Z","updated_at":"2024-02-09T17:08:57.000Z","dependencies_parsed_at":"2022-08-20T15:31:11.482Z","dependency_job_id":null,"html_url":"https://github.com/yii2tech/authlog","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fauthlog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fauthlog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fauthlog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fauthlog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yii2tech","download_url":"https://codeload.github.com/yii2tech/authlog/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219866483,"owners_count":16554235,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","brute-force","log","logging","yii","yii2","yii2-extension"],"created_at":"2024-09-27T07:21:56.772Z","updated_at":"2025-10-01T02:31:39.644Z","avatar_url":"https://github.com/yii2tech.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yii2tech\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://avatars2.githubusercontent.com/u/12951949\" height=\"100px\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eIdentity Authentication Tracking extension for Yii2\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\nThis extension provides identity authentication logging and tracking mechanism, which can be used\nfor 'brute-force' attack protection.\n\nFor license information check the [LICENSE](LICENSE.md)-file.\n\n[![Latest Stable Version](https://poser.pugx.org/yii2tech/authlog/v/stable.png)](https://packagist.org/packages/yii2tech/authlog)\n[![Total Downloads](https://poser.pugx.org/yii2tech/authlog/downloads.png)](https://packagist.org/packages/yii2tech/authlog)\n[![Build Status](https://travis-ci.org/yii2tech/authlog.svg?branch=master)](https://travis-ci.org/yii2tech/authlog)\n\n\nInstallation\n------------\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist yii2tech/authlog\n```\n\nor add\n\n```json\n\"yii2tech/authlog\": \"*\"\n```\n\nto the require section of your composer.json.\n\n\nUsage\n-----\n\nThis extension provides identity authentication logging and tracking mechanism, which can be used\nfor 'brute-force' attack protection.\n\nExtension works through the ActiveRecord entity for the authentication attempt log.\nThe database migration for such entity creation can be following:\n\n```php\n$this-\u003ecreateTable('UserAuthLog', [\n    'id' =\u003e $this-\u003eprimaryKey(),\n    'userId' =\u003e $this-\u003einteger(),\n    'date' =\u003e $this-\u003einteger(),\n    'cookieBased' =\u003e $this-\u003eboolean(),\n    'duration' =\u003e $this-\u003einteger(),\n    'error' =\u003e $this-\u003estring(),\n    'ip' =\u003e $this-\u003estring(),\n    'host' =\u003e $this-\u003estring(),\n    'url' =\u003e $this-\u003estring(),\n    'userAgent' =\u003e $this-\u003estring(),\n]);\n```\n\nActiveRecord model, which implements [[\\yii\\web\\IdentityInterface]] should declare a 'has many' relation to this entity.\nThe logging mechanism is provided via [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] behavior, which should be as well\nattached to the identity class. For example:\n\n```php\nuse Yii;\nuse yii\\db\\ActiveRecord;\nuse yii\\web\\IdentityInterface;\nuse yii2tech\\authlog\\AuthLogIdentityBehavior;\n\nclass User extends ActiveRecord implements IdentityInterface\n{\n    public function behaviors()\n    {\n        return [\n            'authLog' =\u003e [\n                'class' =\u003e AuthLogIdentityBehavior::className(),\n                'authLogRelation' =\u003e 'authLogs',\n                'defaultAuthLogData' =\u003e function ($model) {\n                    return [\n                        'ip' =\u003e Yii::$app-\u003erequest-\u003egetUserIP(),\n                        'host' =\u003e @gethostbyaddr(Yii::$app-\u003erequest-\u003egetUserIP()),\n                        'url' =\u003e Yii::$app-\u003erequest-\u003egetAbsoluteUrl(),\n                        'userAgent' =\u003e Yii::$app-\u003erequest-\u003egetUserAgent(),\n                    ];\n                },\n            ],\n        ];\n    }\n\n    public function getAuthLogs()\n    {\n        return $this-\u003ehasMany(UserAuthLog::className(), ['userId' =\u003e 'id']);\n    }\n\n    // ...\n}\n```\n\n\u003e Note: because [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] works through ActiveRecord the auth log storage can be\n  any one, which have ActiveRecord layer implemented, such as Redis, MongoDB etc.\n\nBeing attached [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] provides basic auth logging and statistic methods:\n\n - `logAuth()` writes auth log entry\n - `logAuthError()` writes auth log error entry\n - `getLastSuccessfulAuthLog()` returns last successful auth log entry\n - `getPreLastSuccessfulAuthLog()` returns pre-last successful auth log entry\n - `getLastLoginDate()` returns last successful login date\n - `getPreLastLoginDate()` returns pre-last successful login date\n - `hasFailedLoginSequence()` checks if there is sequence of failed login attempts of request length starting from now\n\nRefer to [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] for details about configuration and available methods.\n\nKeep in mind that [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] does NOT log authentication attempts automatically.\nYou'll have to invoke logging methods manually in a proper place to do so. However this extension provides other\ntools, which cover this task.\n\n\n## Automatic authentication logging \u003cspan id=\"automatic-authentication-logging\"\u003e\u003c/span\u003e\n\nAlthough [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] provides the basis for the auth logging, it does not\nlog anything automatically. Automatic logging of the successful authentication attempts are provided\nvia [[\\yii2tech\\authlog\\AuthLogWebUserBehavior]] behavior.\n[[\\yii2tech\\authlog\\AuthLogWebUserBehavior]] should be attached to the 'user' application component (instance\nof [[\\yii\\web\\User]]). This could be done at the application configuration:\n\n```php\nreturn [\n    'components' =\u003e [\n        'user' =\u003e [\n            'identityClass' =\u003e 'app\\models\\User',\n            'loginUrl' =\u003e ['site/login'],\n            'as authLog' =\u003e [\n                'class' =\u003e 'yii2tech\\authlog\\AuthLogWebUserBehavior'\n            ],\n        ],\n        // ...\n    ],\n    // ...\n];\n```\n\n[[\\yii2tech\\authlog\\AuthLogWebUserBehavior]] relies identity class has a [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] attached\nand writes auth log on any successful login made through owner [[\\yii\\web\\User]] component, including the ones\nbased on cookie. However, this behavior can not log any failed authentication attempt, which should be done\nelsewhere like login form.\n\n\n## Logging authentication failures \u003cspan id=\"logging-authentication-failures\"\u003e\u003c/span\u003e\n\nLogging authentication failures is specific to the authentication method used by application. Thus you are\nresponsible of its performing by yourself.\n\nMost common authentication method is usage of username/password pair, which is asked via login web form.\nIn such workflow authentication failure should be written on invalid password entered.\nThis extension provides [[\\yii2tech\\authlog\\AuthLogLoginFormBehavior]] behavior, which can be attached to the\nlogin form model, providing authentication failures logging feature. For example:\n\n```php\nuse app\\models\\User;\nuse yii2tech\\authlog\\AuthLogLoginFormBehavior;\n\nclass LoginForm extends Model\n{\n    public $username;\n    public $password;\n    public $rememberMe = true;\n\n    public function behaviors()\n    {\n        return [\n            'authLog' =\u003e [\n                'class' =\u003e AuthLogLoginFormBehavior::className(),\n                'findIdentity' =\u003e 'findIdentity',\n            ],\n        ];\n    }\n\n    public function findIdentity()\n    {\n        return User::findByUsername($this-\u003eusername);\n    }\n\n    // ...\n}\n```\n\n[[\\yii2tech\\authlog\\AuthLogLoginFormBehavior]] automatically logs failure authentication attempt on owner\nvalidation in case identity is found and there is any error on [[\\yii2tech\\authlog\\AuthLogLoginFormBehavior::$verifyIdentityAttributes]].\n\n\n## \"Brute force\" protection \u003cspan id=\"brute-force-protection\"\u003e\u003c/span\u003e\n\nIn addition to simple logging [[\\yii2tech\\authlog\\AuthLogLoginFormBehavior]] provide built-in \"brute force\" attack\nprotection mechanism, which have 2 levels:\n\n - require robot verification (CAPTCHA) after [[\\yii2tech\\authlog\\AuthLogLoginFormBehavior::$verifyRobotFailedLoginSequence]] sequence login failures\n - deactivation of the identity record after [[\\yii2tech\\authlog\\AuthLogLoginFormBehavior::$deactivateFailedLoginSequence]] sequence login failures\n\nFor example:\n\n```php\nuse app\\models\\User;\nuse yii2tech\\authlog\\AuthLogLoginFormBehavior;\n\nclass LoginForm extends Model\n{\n    public $username;\n    public $password;\n    public $rememberMe = true;\n    public $verifyCode;\n\n    public function behaviors()\n    {\n        return [\n            'authLog' =\u003e [\n                'class' =\u003e AuthLogLoginFormBehavior::className(),\n                'findIdentity' =\u003e 'findIdentity',\n                'verifyRobotAttribute' =\u003e 'verifyCode',\n                'deactivateIdentity' =\u003e function ($identity) {\n                    return $this-\u003eupdateAttributes(['statusId' =\u003e User::STATUS_SUSPENDED]);\n                },\n            ],\n        ];\n    }\n\n    public function rules()\n    {\n        return [\n            [['username', 'password'], 'required'],\n            ['rememberMe', 'boolean'],\n            ['password', 'validatePassword'],\n            ['verifyCode', 'safe'],\n        ];\n    }\n\n    public function findIdentity()\n    {\n        return User::findByUsername($this-\u003eusername);\n    }\n\n    // ...\n}\n```\n\nRobot verification requires extra processing at the view layer, which should render CAPTCHA only if it is necessary:\n\n```php\n\u003c?php $form = ActiveForm::begin(['id' =\u003e 'login-form']); ?\u003e\n\n\u003c?= $form-\u003efield($model, 'username') ?\u003e\n\u003c?= $form-\u003efield($model, 'password')-\u003epasswordInput() ?\u003e\n\n\u003c?php if (Yii::$app-\u003euser-\u003eenableAutoLogin) : ?\u003e\n    \u003c?= $form-\u003efield($model, 'rememberMe')-\u003echeckbox() ?\u003e\n\u003c?php endif; ?\u003e\n\n\u003c?php if ($model-\u003eisVerifyRobotRequired) : ?\u003e\n    \u003c?= $form-\u003efield($model, 'verifyCode')-\u003ewidget(Captcha::className(), [\n        'template' =\u003e '{image}{input}',\n    ]) ?\u003e\n\u003c?php endif; ?\u003e\n\n\u003cdiv class=\"form-group\"\u003e\n    \u003c?= Html::submitButton('Login', ['class' =\u003e 'btn btn-primary', 'name' =\u003e 'login-button']) ?\u003e\n\u003c/div\u003e\n\n\u003c?php ActiveForm::end(); ?\u003e\n```\n\n**Heads up!** Although [[\\yii2tech\\authlog\\AuthLogLoginFormBehavior]] is supposed to cover most common web login\nform workflow, do not limit yourself with it. Be ready to create your own implementation of the feature.\n\n\n## Garbage Collection \u003cspan id=\"garbage-collection\"\u003e\u003c/span\u003e\n\nLogging every authentication attempt for every user in the system may cause log storage (database) consuming\ntoo much space without much purpose. Usually there is no need to store all auth attempts for the single user\nstarting from his registration. Thus a built-in garbage collection mechanism provided.\n\nUsing [[\\yii2tech\\authlog\\AuthLogIdentityBehavior]] triggers garbage collection automatically on log writing.\nYou may setup `gcProbability` and `gcLimit` to control the process or invoke `gcAuthLogs()` directly.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Fauthlog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyii2tech%2Fauthlog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Fauthlog/lists"}