hi,
Hello all, i am explaining the simple login code…and then use of RBAC .
very first you need to create a table user
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(5) NOT NULL AUTO_INCREMENT,
`user_organization_email_id` varchar(60) NOT NULL,
`user_password` varchar(150) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`user_type` varchar(15) NOT NULL,
`user_created_by` int(3) NOT NULL,
`user_creation_date` datetime NOT NULL,
PRIMARY KEY (`user_id`)
) ;
.
Now create Model & CRUD.
Now open User.php
this is user.php file model file for login…
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
const ROLE_ADMIN = 20;
/**
* This is the model class for table "user".
*
* @property integer $user_id
* @property string $user_organization_email_id
* @property string $user_password
* @property string $user_type
* @property integer $user_created_by
* @property string $user_creation_date
*
* @property EmployeeTransaction[] $employeeTransactions
*/
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
public $current_pass,$new_pass,$retype_pass;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_organization_email_id', 'user_password', 'user_type', 'user_created_by', 'user_creation_date'], 'required'],
[['current_pass', 'new_pass', 'retype_pass'], 'required','on'=>'change','message'=>''],
[['user_created_by'], 'integer'],
[['user_creation_date'], 'safe'],
['current_pass','checkOldPassword','on'=>'change','message'=>''],
['retype_pass', 'compare','compareAttribute'=>'new_pass'],
[['user_organization_email_id'], 'string', 'max' => 60],
[['user_password'], 'string', 'max' => 150],
[['user_type'], 'string', 'max' => 15]
];
}
public function getRelUser()
{
return $this->hasOne(User::className(), ['user_id' => 'user_created_by']);
}
public function getRelAuthuser()
{
return $this->hasOne(AuthAssignment::className(), ['user_id' => 'user_id']);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'user_id' => 'User ID',
'user_organization_email_id' => 'Login ID',
'user_password' => 'Password',
'user_type' => 'User Type',
'user_created_by' => 'Created By',
'user_creation_date' => 'Creation Date',
'current_pass' => 'Current Password',
'new_pass' => 'New Password',
'retype_pass' => 'Retype Password',
];
}
/**
* @return \yii\db\ActiveQuery
*/
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
public function checkOldPassword($attribute,$params)
{
$record=User::find()->where(['user_password'=>md5($this->current_pass.$this->current_pass)])->one();
if($record===null){
$this->addError($attribute, 'Invalid password');
}
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
/*
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
*/
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['user_organization_email_id' => $username]);
/*
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
*/
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
$expire = \Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
if ($timestamp + $expire < time()) {
// token expired
return null;
}
return static::findOne([
'password_reset_token' => $token
]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->user_password === md5($password.$password);
// return Security::validatePassword($password, $this->password_hash);
}
// Generates "remember me" authentication key
public function generateAuthKey()
{
$this->auth_key = Security::generateRandomKey();
}
// Generates new password reset token
public function generatePasswordResetToken()
{
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
}
// Removes password reset token
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
/*********************************************************************/
USE Of RBAC
very first we need Yii 2 Extension to manage Role Base Access Control.
The preferred way to install this extension is through composer.
OR Open Terminal :
and go thru your web app path and then just type following :
/var/www/janvi-test$ composer require mdmsoft/yii2-admin "~1.0"
Now if you want to generate migration then also you can go thru terminal and
[b]
yii migrate --migrationPath=@mdm/admin/migrations[/b]
or create this four tables in your database.
CREATE TABLE IF NOT EXISTS `auth_assignment` (
`item_name` varchar(64) NOT NULL,
`user_id` varchar(64) NOT NULL,
`created_at` int(11) DEFAULT NULL,
PRIMARY KEY (`item_name`,`user_id`)
) ;
CREATE TABLE IF NOT EXISTS `auth_item` (
`name` varchar(64) NOT NULL,
`type` int(11) NOT NULL,
`description` text,
`rule_name` varchar(64) DEFAULT NULL,
`data` text,
`created_at` int(11) DEFAULT NULL,
`updated_at` int(11) DEFAULT NULL,
PRIMARY KEY (`name`),
KEY `rule_name` (`rule_name`),
KEY `type` (`type`)
) ;
CREATE TABLE IF NOT EXISTS `auth_item_child` (
`parent` varchar(64) NOT NULL,
`child` varchar(64) NOT NULL,
PRIMARY KEY (`parent`,`child`),
KEY `child` (`child`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `auth_rule` (
`name` varchar(64) NOT NULL,
`data` text,
`created_at` int(11) DEFAULT NULL,
`updated_at` int(11) DEFAULT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
now open Config/web.php file.
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'sdfskdfgkdsfhsdjfhdj',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'class' => 'yii\web\UrlManager',
'baseUrl' => '/janvi-test/web/',
'enablePrettyUrl' => true,
'showScriptName' => false,
//'enableStrictParsing' => true,
'rules' => [
''=>'site/index',
// '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
// '<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',
],
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'admin' => [
'class' => 'mdm\admin\Module',
'layout' => 'top-menu',
'controllerMap' => [
'assignment' => [
'class' => 'mdm\admin\controllers\AssignmentController',
'userClassName' => 'app\models\User',
'idField' => 'user_id', // id field of model User
],
],
]
],
'as access' => [
'class' => 'mdm\admin\components\AccessControl',
'allowActions' => [
'admin/*', // add or remove allowed actions to this list
'site/*'
]
],
now you can access your webapplication.http://janvi-test/web/admin
now you can create route,Roles & Permission…
Hope now this will help for all new users…