PHPackages                             cgsmith/yii2-user - 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. cgsmith/yii2-user

ActiveYii2-extension[Authentication &amp; Authorization](/categories/authentication)

cgsmith/yii2-user
=================

Modern user management module for Yii2

7142PHP

Since Jan 31Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/cgsmith/yii2-user)[ Packagist](https://packagist.org/packages/cgsmith/yii2-user)[ RSS](/packages/cgsmith-yii2-user/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

cgsmith/yii2-user
=================

[](#cgsmithyii2-user)

A modern, actively maintained user management module for Yii2. Built as a spiritual successor to dektrium/yii2-user and 2amigos/yii2-usuario, designed for PHP 8.2+ with strict typing and modern practices.

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Yii2 2.0.45 or higher

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

[](#installation)

### Via Composer (when published)

[](#via-composer-when-published)

```
composer require cgsmith/yii2-user
```

### Optional Dependencies

[](#optional-dependencies)

For additional features, install these packages:

```
# Two-Factor Authentication (TOTP)
composer require pragmarx/google2fa bacon/bacon-qr-code

# Social Authentication
composer require yiisoft/yii2-authclient

# reCAPTCHA support
composer require google/recaptcha

# hCaptcha support
composer require skrtdev/hcaptcha
```

### Local Development

[](#local-development)

Add to your `composer.json`:

```
{
  "autoload": {
    "psr-4": {
      "cgsmith\\user\\": "common/modules/user/src/"
    }
  }
}
```

Then run:

```
composer dump-autoload
```

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

[](#configuration)

### Web Application

[](#web-application)

```
return [
    'bootstrap' => ['log', 'cgsmith\user\Bootstrap'],
    'modules' => [
        'user' => [
            'class' => 'cgsmith\user\Module',
            'enableRegistration' => true,
            'enableConfirmation' => true,
            'enablePasswordRecovery' => true,
            'admins' => ['admin@example.com'],
            'mailer' => [
                'sender' => ['noreply@example.com' => 'My Application'],
            ],
        ],
    ],
];
```

### Console Application

[](#console-application)

```
return [
    'bootstrap' => ['log', 'cgsmith\user\Bootstrap'],
    'modules' => [
        'user' => [
            'class' => 'cgsmith\user\Module',
        ],
    ],
];
```

Feature Comparison
------------------

[](#feature-comparison)

Featuredektrium/yii2-user2amigos/yii2-usuariocgsmith/yii2-user**Status**Abandoned (2018)Abandoned (2022)Active**PHP Version**5.6+7.1+8.2+**Strict Types**NoPartialYes**Yii2 Version**2.0.6+2.0.13+2.0.45+### Core Features

[](#core-features)

FeaturedektriumusuariocgsmithUser Registration✅✅✅Email Confirmation✅✅✅Password Recovery✅✅✅Account Settings✅✅✅Profile Management✅✅✅Admin Panel✅✅✅User Blocking✅✅✅RBAC Integration✅✅✅Model Overriding✅✅✅Controller Events✅✅✅i18n Support✅✅✅### Security Features

[](#security-features)

FeaturedektriumusuariocgsmithSecure Password Hashing✅✅✅Configurable bcrypt Cost✅✅✅Token-based Confirmation✅✅✅Token Expiration✅✅✅IP Logging✅✅✅Last Login Tracking✅✅✅Email Change Strategies✅✅✅CSRF Protection✅✅✅Two-Factor Auth (TOTP)❌❌✅Session History❌❌✅CAPTCHA Support❌❌✅### Advanced Features

[](#advanced-features)

FeaturedektriumusuariocgsmithSocial Authentication✅✅✅GDPR Compliance❌✅✅GDPR Consent Management❌❌✅Data Export❌✅✅Account Deletion❌✅✅User Impersonation✅✅✅Gravatar Support✅✅✅Avatar Upload❌❌✅RBAC Management UI❌❌✅Session Separation❌❌✅Migration from dektriumN/A✅✅Migration from usuarioN/AN/A✅### Architecture

[](#architecture)

FeaturedektriumusuariocgsmithService Layer❌Partial✅Dependency Injection❌Partial✅Interface Contracts❌❌✅Custom Query Classes❌❌✅Event-driven Design✅✅✅Configuration Options
---------------------

[](#configuration-options)

### Core Options

[](#core-options)

OptionTypeDefaultDescription`enableRegistration`bool`true`Enable/disable user registration`enableConfirmation`bool`true`Require email confirmation`enableUnconfirmedLogin`bool`false`Allow login without confirmation`enablePasswordRecovery`bool`true`Enable password recovery`enableImpersonation`bool`true`Enable admin impersonation`enableGeneratedPassword`bool`false`Auto-generate passwords`enableGravatar`bool`true`Enable Gravatar support`enableAvatarUpload`bool`true`Enable local avatar uploads`enableAccountDelete`bool`true`Allow users to delete accounts`emailChangeStrategy`int`1`Email change strategy (0-2)`rememberFor`int`1209600`Remember me duration (seconds)`confirmWithin`int`86400`Confirmation token expiry (seconds)`recoverWithin`int`21600`Recovery token expiry (seconds)`minPasswordLength`int`8`Minimum password length`maxPasswordLength`int`72`Maximum password length`cost`int`12`bcrypt cost parameter`admins`array`[]`Admin email addresses`adminPermission`string`null`RBAC permission for admin access`impersonatePermission`string`null`RBAC permission for impersonation`urlPrefix`string`'user'`URL prefix for module routes`avatarPath`string`'@webroot/uploads/avatars'`Avatar storage path`avatarUrl`string`'@web/uploads/avatars'`Avatar URL path`maxAvatarSize`int`2097152`Max avatar file size (bytes)`avatarExtensions`array`['jpg', 'jpeg', 'png', 'gif', 'webp']`Allowed avatar extensions### GDPR Options

[](#gdpr-options)

OptionTypeDefaultDescription`enableGdpr`bool`false`Enable GDPR features (export, delete)`enableGdprConsent`bool`false`Enable GDPR consent tracking`requireGdprConsentBeforeRegistration`bool`true`Require consent during registration`gdprConsentVersion`string`'1.0'`Current consent version`gdprConsentUrl`string`null`URL to privacy policy`gdprExemptRoutes`array`[]`Routes exempt from consent check### Session Options

[](#session-options)

OptionTypeDefaultDescription`enableSessionHistory`bool`false`Enable session tracking`sessionHistoryLimit`int`10`Max sessions to track per user`enableSessionSeparation`bool`false`Separate frontend/backend sessions`backendSessionName`string`'BACKENDSESSID'`Backend session cookie name`frontendSessionName`string`'PHPSESSID'`Frontend session cookie name### Two-Factor Authentication Options

[](#two-factor-authentication-options)

OptionTypeDefaultDescription`enableTwoFactor`bool`false`Enable 2FA support`twoFactorIssuer`string`''`Issuer name in authenticator app`twoFactorBackupCodesCount`int`10`Number of backup codes to generate`twoFactorRequireForAdmins`bool`false`Require 2FA for admin users### Social Authentication Options

[](#social-authentication-options)

OptionTypeDefaultDescription`enableSocialAuth`bool`false`Enable social login`enableSocialRegistration`bool`true`Allow registration via social`enableSocialConnect`bool`true`Allow linking social accounts### CAPTCHA Options

[](#captcha-options)

OptionTypeDefaultDescription`enableCaptcha`bool`false`Enable CAPTCHA on forms`captchaType`string`'yii'`Type: 'yii', 'recaptcha-v2', 'recaptcha-v3', 'hcaptcha'`reCaptchaSiteKey`string`null`reCAPTCHA site key`reCaptchaSecretKey`string`null`reCAPTCHA secret key`reCaptchaV3Threshold`float`0.5`reCAPTCHA v3 score threshold (0.0-1.0)`hCaptchaSiteKey`string`null`hCaptcha site key`hCaptchaSecretKey`string`null`hCaptcha secret key`captchaForms`array`['register']`Forms to show CAPTCHA: 'login', 'register', 'recovery'### RBAC Management Options

[](#rbac-management-options)

OptionTypeDefaultDescription`enableRbacManagement`bool`false`Enable RBAC management UI`rbacManagementPermission`string`null`Permission required to manage RBACFeature Documentation
---------------------

[](#feature-documentation)

### Two-Factor Authentication (TOTP)

[](#two-factor-authentication-totp)

Enable TOTP-based two-factor authentication with Google Authenticator, Authy, or any TOTP-compatible app.

```
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableTwoFactor' => true,
        'twoFactorIssuer' => 'My Application',
        'twoFactorBackupCodesCount' => 10,
        'twoFactorRequireForAdmins' => false,
    ],
],
```

**Features:**

- QR code setup with authenticator apps
- Manual secret key entry option
- Backup codes for account recovery
- Optional enforcement for admin users
- Secure login flow interruption

**Routes:**

- `user/settings/two-factor` - 2FA settings page
- `user/two-factor` - Verification during login

### Social Authentication

[](#social-authentication)

Enable login and registration via OAuth2 providers using yii2-authclient.

```
'components' => [
    'authClientCollection' => [
        'class' => 'yii\authclient\Collection',
        'clients' => [
            'google' => [
                'class' => 'yii\authclient\clients\Google',
                'clientId' => 'your-client-id',
                'clientSecret' => 'your-client-secret',
            ],
            'github' => [
                'class' => 'yii\authclient\clients\GitHub',
                'clientId' => 'your-client-id',
                'clientSecret' => 'your-client-secret',
            ],
        ],
    ],
],
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableSocialAuth' => true,
        'enableSocialRegistration' => true,
        'enableSocialConnect' => true,
    ],
],
```

**Features:**

- Login with social accounts
- Register new accounts via social providers
- Connect/disconnect social accounts in settings
- Link multiple social accounts to one user

**Routes:**

- `user/auth/` - OAuth callback
- `user/settings/networks` - Manage connected accounts

### Session History

[](#session-history)

Track and manage active user sessions across devices.

```
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableSessionHistory' => true,
        'sessionHistoryLimit' => 10,
    ],
],
```

**Features:**

- View all active sessions
- See device/browser information
- IP address and last activity tracking
- Terminate individual sessions
- Terminate all other sessions

**Routes:**

- `user/settings/sessions` - View active sessions

### CAPTCHA Support

[](#captcha-support)

Protect forms with CAPTCHA verification. Supports Yii's built-in CAPTCHA, Google reCAPTCHA (v2 and v3), and hCaptcha.

```
// Using Yii's built-in CAPTCHA
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableCaptcha' => true,
        'captchaType' => 'yii',
        'captchaForms' => ['register', 'login', 'recovery'],
    ],
],

// Using reCAPTCHA v2
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableCaptcha' => true,
        'captchaType' => 'recaptcha-v2',
        'reCaptchaSiteKey' => 'your-site-key',
        'reCaptchaSecretKey' => 'your-secret-key',
        'captchaForms' => ['register'],
    ],
],

// Using reCAPTCHA v3 (invisible)
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableCaptcha' => true,
        'captchaType' => 'recaptcha-v3',
        'reCaptchaSiteKey' => 'your-site-key',
        'reCaptchaSecretKey' => 'your-secret-key',
        'reCaptchaV3Threshold' => 0.5,
        'captchaForms' => ['register', 'login'],
    ],
],

// Using hCaptcha
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableCaptcha' => true,
        'captchaType' => 'hcaptcha',
        'hCaptchaSiteKey' => 'your-site-key',
        'hCaptchaSecretKey' => 'your-secret-key',
        'captchaForms' => ['register'],
    ],
],
```

### GDPR Consent Management

[](#gdpr-consent-management)

Track and enforce GDPR consent with version management.

```
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableGdprConsent' => true,
        'gdprConsentVersion' => '1.0',
        'gdprConsentUrl' => '/site/privacy',
        'requireGdprConsentBeforeRegistration' => true,
        'gdprExemptRoutes' => ['site/privacy', 'site/terms'],
    ],
],
```

**Features:**

- Consent checkbox during registration
- Optional marketing consent
- Consent version tracking
- Force re-consent when version changes
- Exempt routes from consent check

**Routes:**

- `user/gdpr/consent` - Consent page for existing users

### RBAC Management UI

[](#rbac-management-ui)

Web-based interface for managing roles, permissions, and user assignments.

```
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableRbacManagement' => true,
        'rbacManagementPermission' => 'manageRbac', // optional
    ],
],
```

**Features:**

- Create, edit, delete roles
- Create, edit, delete permissions
- Assign permissions to roles
- Role inheritance (child roles)
- Assign roles to users from admin panel

**Routes:**

- `user/rbac` - RBAC overview
- `user/rbac/roles` - Manage roles
- `user/rbac/permissions` - Manage permissions
- `user/admin/assignments/` - User role assignments

### Frontend/Backend Session Separation

[](#frontendbackend-session-separation)

Use separate session cookies for frontend and backend applications.

```
// Backend configuration
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableSessionSeparation' => true,
        'backendSessionName' => 'BACKENDSESSID',
    ],
],
'components' => [
    'session' => [
        'name' => 'BACKENDSESSID',
    ],
    'user' => [
        'class' => 'cgsmith\user\components\BackendUser',
    ],
],

// Frontend configuration (default)
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'enableSessionSeparation' => true,
        'frontendSessionName' => 'PHPSESSID',
    ],
],
```

Console Commands
----------------

[](#console-commands)

```
# Create a new user
php yii user/create admin@example.com password

# Confirm a user
php yii user/confirm admin@example.com

# Delete a user
php yii user/delete admin@example.com

# Migrate from dektrium/yii2-user
php yii migrate-from-dektrium/migrate
```

Model Overriding
----------------

[](#model-overriding)

```
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'modelMap' => [
            'User' => 'app\models\User',
            'Profile' => 'app\models\Profile',
            'RegistrationForm' => 'app\models\RegistrationForm',
        ],
    ],
],
```

Event Handling
--------------

[](#event-handling)

```
'modules' => [
    'user' => [
        'class' => 'cgsmith\user\Module',
        'controllerMap' => [
            'registration' => [
                'class' => 'cgsmith\user\controllers\RegistrationController',
                'on afterRegister' => ['app\handlers\UserHandler', 'onRegister'],
            ],
        ],
    ],
],
```

Available events:

- `RegistrationController::EVENT_BEFORE_REGISTER`
- `RegistrationController::EVENT_AFTER_REGISTER`
- `RegistrationController::EVENT_BEFORE_CONFIRM`
- `RegistrationController::EVENT_AFTER_CONFIRM`
- `SecurityController::EVENT_BEFORE_LOGIN`
- `SecurityController::EVENT_AFTER_LOGIN`
- `SecurityController::EVENT_BEFORE_LOGOUT`
- `SecurityController::EVENT_AFTER_LOGOUT`
- `RecoveryController::EVENT_BEFORE_REQUEST`
- `RecoveryController::EVENT_AFTER_REQUEST`
- `RecoveryController::EVENT_BEFORE_RESET`
- `RecoveryController::EVENT_AFTER_RESET`
- `TwoFactorController::EVENT_BEFORE_ENABLE`
- `TwoFactorController::EVENT_AFTER_ENABLE`
- `TwoFactorController::EVENT_BEFORE_DISABLE`
- `TwoFactorController::EVENT_AFTER_DISABLE`
- `SocialController::EVENT_BEFORE_CONNECT`
- `SocialController::EVENT_AFTER_CONNECT`
- `SocialController::EVENT_BEFORE_DISCONNECT`
- `SocialController::EVENT_AFTER_DISCONNECT`

View Customization
------------------

[](#view-customization)

Override views by setting up theme path mapping:

```
'components' => [
    'view' => [
        'theme' => [
            'pathMap' => [
                '@cgsmith/user/views' => '@app/views/user',
            ],
        ],
    ],
],
```

Migration from dektrium/yii2-user
---------------------------------

[](#migration-from-dektriumyii2-user)

1. Install cgsmith/yii2-user
2. Update your configuration to use the new module
3. Run the migration command:

```
php yii migrate-from-dektrium/migrate
```

This will:

- Migrate existing user data
- Convert token formats
- Preserve all user relationships
- Backup original tables as `user_dektrium_backup`, `profile_dektrium_backup`, `token_dektrium_backup`

### Custom Field Migration

[](#custom-field-migration)

**Important:** If you added custom columns to the original dektrium user table (e.g., `developer_id`, `company_id`, `department`, etc.), these fields will **not** be automatically migrated to the new user table. You must create a separate migration to:

1. Add the custom column(s) to the new `user` table
2. Copy the data from the backup table using email matching

Example migration for a custom `developer_id` field:

```
