RBAC and social controller

This commit is contained in:
2026-01-29 17:54:12 +01:00
parent 98a0e33939
commit e003257c84
48 changed files with 4510 additions and 73 deletions

388
README.md
View File

@@ -16,6 +16,24 @@ A modern, actively maintained user management module for Yii2. Built as a spirit
composer require cgsmith/yii2-user
```
### Optional Dependencies
For additional features, install these packages:
```bash
# 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
Add to your `composer.json`:
@@ -108,19 +126,24 @@ return [
| Last Login Tracking | ✅ | ✅ | ✅ |
| Email Change Strategies | ✅ | ✅ | ✅ |
| CSRF Protection | ✅ | ✅ | ✅ |
| Two-Factor Auth (TOTP) | ❌ | ❌ | ✅ |
| Session History | ❌ | ❌ | ✅ |
| CAPTCHA Support | ❌ | ❌ | ✅ |
### Advanced Features
| Feature | dektrium | usuario | cgsmith |
|-------------------------|:--------:|:-------:|:-------:|
| Social Authentication | ✅ | ✅ | 🔄 v2 |
| Two-Factor Auth (2FA) | ❌ | | 🔄 v2 |
| GDPR Compliance | ❌ | ✅ | 🔄 v2 |
| Data Export | ❌ | ✅ | 🔄 v2 |
| Account Deletion | ❌ | ✅ | 🔄 v2 |
| Social Authentication | ✅ | ✅ | |
| GDPR Compliance | ❌ | | |
| GDPR Consent Management | ❌ | ❌ | ✅ |
| Data Export | ❌ | ✅ | |
| Account Deletion | ❌ | ✅ | |
| User Impersonation | ✅ | ✅ | ✅ |
| Gravatar Support | ✅ | ✅ | ✅ |
| Avatar Upload | ❌ | ❌ | ✅ |
| RBAC Management UI | ❌ | ❌ | ✅ |
| Session Separation | ❌ | ❌ | ✅ |
| Migration from dektrium | N/A | ✅ | ✅ |
| Migration from usuario | N/A | N/A | ✅ |
@@ -136,17 +159,19 @@ return [
## Configuration Options
### Core Options
| Option | Type | Default | Description |
|---------------------------|--------|-----------------------------------------|-------------------------------------|
| `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 |
| `enableGdpr` | bool | `false` | Enable GDPR features (v2) |
| `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) |
@@ -163,6 +188,298 @@ return [
| `maxAvatarSize` | int | `2097152` | Max avatar file size (bytes) |
| `avatarExtensions` | array | `['jpg', 'jpeg', 'png', 'gif', 'webp']` | Allowed avatar extensions |
### GDPR Options
| Option | Type | Default | Description |
|--------------------------------------|--------|---------|------------------------------------------|
| `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
| Option | Type | Default | Description |
|-------------------------|--------|-------------------|--------------------------------------|
| `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
| Option | Type | Default | Description |
|-----------------------------|--------|---------|----------------------------------------|
| `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
| Option | Type | Default | Description |
|--------------------------|------|---------|-------------------------------------|
| `enableSocialAuth` | bool | `false` | Enable social login |
| `enableSocialRegistration` | bool | `true` | Allow registration via social |
| `enableSocialConnect` | bool | `true` | Allow linking social accounts |
### CAPTCHA Options
| Option | Type | Default | Description |
|-----------------------|--------|--------------|------------------------------------------|
| `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
| Option | Type | Default | Description |
|--------------------------|--------|---------|---------------------------------------|
| `enableRbacManagement` | bool | `false` | Enable RBAC management UI |
| `rbacManagementPermission` | string | `null` | Permission required to manage RBAC |
## Feature Documentation
### Two-Factor Authentication (TOTP)
Enable TOTP-based two-factor authentication with Google Authenticator, Authy, or any TOTP-compatible app.
```php
'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
Enable login and registration via OAuth2 providers using yii2-authclient.
```php
'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/<provider>` - OAuth callback
- `user/settings/networks` - Manage connected accounts
### Session History
Track and manage active user sessions across devices.
```php
'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
Protect forms with CAPTCHA verification. Supports Yii's built-in CAPTCHA, Google reCAPTCHA (v2 and v3), and hCaptcha.
```php
// 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
Track and enforce GDPR consent with version management.
```php
'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
Web-based interface for managing roles, permissions, and user assignments.
```php
'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/<id>` - User role assignments
### Frontend/Backend Session Separation
Use separate session cookies for frontend and backend applications.
```php
// 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
```bash
@@ -224,6 +541,14 @@ Available events:
- `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
@@ -241,17 +566,6 @@ Override views by setting up theme path mapping:
],
```
## GDPR Features (Coming in v2)
GDPR compliance features are planned for v2. When complete, users will be able to:
- Export all their personal data as JSON
- Request account deletion with soft-delete support
- View what data is stored about them
- Manage consent preferences
See the [v2 Roadmap](#v2-roadmap) for more details.
## Migration from dektrium/yii2-user
1. Install cgsmith/yii2-user
@@ -322,45 +636,18 @@ class User extends \cgsmith\user\models\User
}
```
## v2 Roadmap
## Future Roadmap
The following features are planned for version 2.0:
The following features are planned for future releases:
### Authentication & Security
- [ ] **Two-Factor Authentication (2FA)**
- TOTP (Google Authenticator, Authy)
- SMS verification
- Backup codes
- Per-user 2FA enforcement
- [ ] **Passwordless Authentication**
- Magic link login
- WebAuthn/FIDO2 support
- [ ] **Enhanced Session Management**
- View active sessions
- Remote session termination
- Device fingerprinting
### Social Authentication
- [ ] **OAuth2 Provider Integration**
- Google
- GitHub
- Facebook
- Apple
- Microsoft
- Custom providers via configuration
- [ ] **Account Linking**
- Link multiple social accounts
- Unlink social accounts
- Primary account selection
### Security Hardening
- [ ] **Brute Force Protection**
- [ ] **Enhanced Brute Force Protection**
- Rate limiting per IP/user
- Progressive delays
- CAPTCHA integration (reCAPTCHA v3, hCaptcha)
- [ ] **Password Policies**
- Password strength meter
- Common password blocklist
@@ -423,7 +710,7 @@ The following features are planned for version 2.0:
- Automatic migration script generation for custom fields
- Support for foreign key relationship preservation
- Rollback support with data integrity checks
- [ ] **Smart Migration from 2amigos/yii2-usuario**
- Auto-detect custom columns added to user table
- Interactive migration wizard for custom fields
@@ -434,11 +721,6 @@ The following features are planned for version 2.0:
### Compliance
- [ ] **Enhanced GDPR**
- Right to be forgotten workflow
- Data retention policies
- Consent management
- Cookie consent integration
- [ ] **Accessibility**
- WCAG 2.1 AA compliance
- Screen reader support