Yii2 user module.
Use composer
composer require "yiisolutions/yii2-user-module: @dev"
or add to composer.json
{
"require": {
"yiisolutions/yii2-user-module": "@dev"
}
}
For enable user module edit your configuration
<?php
return [
// ...
'modules' => [
// ...
'user' => [
'class' => 'yiisolutions\user\Module',
],
// ...
],
// ...
];
This module provider console commands for manager users
user/commands/create
- create new useruser/commands/truncate
- clear user table
This module provide web controller actions:
yiisolutions\user\actions\LoginAction
- for user loginyiisolutions\user\actions\LogoutAction
- for logoutyiisolutions\user\actions\SignUpAction
- for sign up new user
For enable these actions use controller actions()
method
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\IdentityInterface;
use yiisolutions\user\actions\LoginAction;
use yiisolutions\user\actions\LogoutAction;
use yiisolutions\user\actions\SignUpAction;
use yiisolutions\user\events\LoginEvent;
use yiisolutions\user\models\LoginFormInterface;
class AccountController extends Controller
{
public function actions()
{
return [
'login' => [
'class' => LoginAction::className(),
'view' => 'login', // use @app/views/account/login.php view file
'on loginSuccess' => [$this, 'onLoginSuccess'], // alternative success callback (default redirect to back)
'on loginFailed' => [$this, 'onLoginFailed'], // do something when login failed (for example, logging)
],
'logout' => [
'class' => LogoutAction::className(),
],
'sign-up' => [
'class' => SignUpAction::className(),
],
];
}
/**
* Run when login success.
*/
public function onLoginSuccess(LoginEvent $event, LoginFormInterface $model)
{
// do something ...
$username = $model->getUserIdentity()->username;
Yii::info("User '{$username}' logged in");
// override default action return value
$event->return = $this->redirect('/profile');
}
/**
* Run when login error.
*/
public function onLoginFailed(LoginEvent $event, LoginFormInterface $model)
{
// do something ...
$user = $model->getUserIdentity();
if ($user instanceof IdentityInterface) {
// do something, when exists user fail login ...
} else {
// do something, else ...
}
$user = $model->getUserIdentity();
if ($user) {
// send email notification, increment attempt counter etc ...
}
}
}