Initial commit,修正
This commit is contained in:
+121
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models;
|
||||
|
||||
use Yii;
|
||||
use yii\base\BaseObject;
|
||||
use mdm\admin\components\Helper;
|
||||
|
||||
/**
|
||||
* Description of Assignment
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 2.5
|
||||
*/
|
||||
class Assignment extends BaseObject
|
||||
{
|
||||
/**
|
||||
* @var integer User id
|
||||
*/
|
||||
public $id;
|
||||
/**
|
||||
* @var \yii\web\IdentityInterface User
|
||||
*/
|
||||
public $user;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function __construct($id, $user = null, $config = array())
|
||||
{
|
||||
$this->id = $id;
|
||||
$this->user = $user;
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Grands a roles from a user.
|
||||
* @param array $items
|
||||
* @return integer number of successful grand
|
||||
*/
|
||||
public function assign($items)
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$success = 0;
|
||||
foreach ($items as $name) {
|
||||
try {
|
||||
$item = $manager->getRole($name);
|
||||
$item = $item ? : $manager->getPermission($name);
|
||||
$manager->assign($item, $this->id);
|
||||
$success++;
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
}
|
||||
Helper::invalidate();
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revokes a roles from a user.
|
||||
* @param array $items
|
||||
* @return integer number of successful revoke
|
||||
*/
|
||||
public function revoke($items)
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$success = 0;
|
||||
foreach ($items as $name) {
|
||||
try {
|
||||
$item = $manager->getRole($name);
|
||||
$item = $item ? : $manager->getPermission($name);
|
||||
$manager->revoke($item, $this->id);
|
||||
$success++;
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
}
|
||||
Helper::invalidate();
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all avaliable and assigned roles/permission
|
||||
* @return array
|
||||
*/
|
||||
public function getItems()
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$avaliable = [];
|
||||
foreach (array_keys($manager->getRoles()) as $name) {
|
||||
$avaliable[$name] = 'role';
|
||||
}
|
||||
|
||||
foreach (array_keys($manager->getPermissions()) as $name) {
|
||||
if ($name[0] != '/') {
|
||||
$avaliable[$name] = 'permission';
|
||||
}
|
||||
}
|
||||
|
||||
$assigned = [];
|
||||
foreach ($manager->getAssignments($this->id) as $item) {
|
||||
$assigned[$item->roleName] = $avaliable[$item->roleName];
|
||||
unset($avaliable[$item->roleName]);
|
||||
}
|
||||
|
||||
return[
|
||||
'avaliable' => $avaliable,
|
||||
'assigned' => $assigned
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
if ($this->user) {
|
||||
return $this->user->$name;
|
||||
}
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models;
|
||||
|
||||
use Yii;
|
||||
use yii\rbac\Item;
|
||||
use yii\helpers\Json;
|
||||
use yii\base\Model;
|
||||
use mdm\admin\components\Helper;
|
||||
|
||||
/**
|
||||
* This is the model class for table "tbl_auth_item".
|
||||
*
|
||||
* @property string $name
|
||||
* @property integer $type
|
||||
* @property string $description
|
||||
* @property string $ruleName
|
||||
* @property string $data
|
||||
*
|
||||
* @property Item $item
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class AuthItem extends Model
|
||||
{
|
||||
public $name;
|
||||
public $type;
|
||||
public $description;
|
||||
public $ruleName;
|
||||
public $data;
|
||||
/**
|
||||
* @var Item
|
||||
*/
|
||||
private $_item;
|
||||
|
||||
/**
|
||||
* Initialize object
|
||||
* @param Item $item
|
||||
* @param array $config
|
||||
*/
|
||||
public function __construct($item = null, $config = [])
|
||||
{
|
||||
$this->_item = $item;
|
||||
if ($item !== null) {
|
||||
$this->name = $item->name;
|
||||
$this->type = $item->type;
|
||||
$this->description = $item->description;
|
||||
$this->ruleName = $item->ruleName;
|
||||
$this->data = $item->data === null ? null : Json::encode($item->data);
|
||||
}
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['ruleName'], 'checkRule'],
|
||||
[['name', 'type'], 'required'],
|
||||
[['name'], 'unique', 'when' => function() {
|
||||
return $this->isNewRecord || ($this->_item->name != $this->name);
|
||||
}],
|
||||
[['type'], 'integer'],
|
||||
[['description', 'data', 'ruleName'], 'default'],
|
||||
[['name'], 'string', 'max' => 64]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check role is unique
|
||||
*/
|
||||
public function unique()
|
||||
{
|
||||
$authManager = Yii::$app->authManager;
|
||||
$value = $this->name;
|
||||
if ($authManager->getRole($value) !== null || $authManager->getPermission($value) !== null) {
|
||||
$message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
|
||||
$params = [
|
||||
'attribute' => $this->getAttributeLabel('name'),
|
||||
'value' => $value,
|
||||
];
|
||||
$this->addError('name', Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for rule
|
||||
*/
|
||||
public function checkRule()
|
||||
{
|
||||
$name = $this->ruleName;
|
||||
if (!Yii::$app->getAuthManager()->getRule($name)) {
|
||||
try {
|
||||
$rule = Yii::createObject($name);
|
||||
if ($rule instanceof \yii\rbac\Rule) {
|
||||
$rule->name = $name;
|
||||
Yii::$app->getAuthManager()->add($rule);
|
||||
} else {
|
||||
$this->addError('ruleName', Yii::t('rbac-admin', 'Invalid rule "{value}"', ['value' => $name]));
|
||||
}
|
||||
} catch (\Exception $exc) {
|
||||
$this->addError('ruleName', Yii::t('rbac-admin', 'Rule "{value}" does not exists', ['value' => $name]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return [
|
||||
'name' => Yii::t('rbac-admin', 'Name'),
|
||||
'type' => Yii::t('rbac-admin', 'Type'),
|
||||
'description' => Yii::t('rbac-admin', 'Description'),
|
||||
'ruleName' => Yii::t('rbac-admin', 'Rule Name'),
|
||||
'data' => Yii::t('rbac-admin', 'Data'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if is new record.
|
||||
* @return boolean
|
||||
*/
|
||||
public function getIsNewRecord()
|
||||
{
|
||||
return $this->_item === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find role
|
||||
* @param string $id
|
||||
* @return null|\self
|
||||
*/
|
||||
public static function find($id)
|
||||
{
|
||||
$item = Yii::$app->authManager->getRole($id);
|
||||
if ($item !== null) {
|
||||
return new self($item);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save role to [[\yii\rbac\authManager]]
|
||||
* @return boolean
|
||||
*/
|
||||
public function save()
|
||||
{
|
||||
if ($this->validate()) {
|
||||
$manager = Yii::$app->authManager;
|
||||
if ($this->_item === null) {
|
||||
if ($this->type == Item::TYPE_ROLE) {
|
||||
$this->_item = $manager->createRole($this->name);
|
||||
} else {
|
||||
$this->_item = $manager->createPermission($this->name);
|
||||
}
|
||||
$isNew = true;
|
||||
} else {
|
||||
$isNew = false;
|
||||
$oldName = $this->_item->name;
|
||||
}
|
||||
$this->_item->name = $this->name;
|
||||
$this->_item->description = $this->description;
|
||||
$this->_item->ruleName = $this->ruleName;
|
||||
$this->_item->data = $this->data === null || $this->data === '' ? null : Json::decode($this->data);
|
||||
if ($isNew) {
|
||||
$manager->add($this->_item);
|
||||
} else {
|
||||
$manager->update($oldName, $this->_item);
|
||||
}
|
||||
Helper::invalidate();
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an item as a child of another item.
|
||||
* @param array $items
|
||||
* @return int
|
||||
*/
|
||||
public function addChildren($items)
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$success = 0;
|
||||
if ($this->_item) {
|
||||
foreach ($items as $name) {
|
||||
$child = $manager->getPermission($name);
|
||||
if ($this->type == Item::TYPE_ROLE && $child === null) {
|
||||
$child = $manager->getRole($name);
|
||||
}
|
||||
try {
|
||||
$manager->addChild($this->_item, $child);
|
||||
$success++;
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($success > 0) {
|
||||
Helper::invalidate();
|
||||
}
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an item as a child of another item.
|
||||
* @param array $items
|
||||
* @return int
|
||||
*/
|
||||
public function removeChildren($items)
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$success = 0;
|
||||
if ($this->_item !== null) {
|
||||
foreach ($items as $name) {
|
||||
$child = $manager->getPermission($name);
|
||||
if ($this->type == Item::TYPE_ROLE && $child === null) {
|
||||
$child = $manager->getRole($name);
|
||||
}
|
||||
try {
|
||||
$manager->removeChild($this->_item, $child);
|
||||
$success++;
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($success > 0) {
|
||||
Helper::invalidate();
|
||||
}
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get items
|
||||
* @return array
|
||||
*/
|
||||
public function getItems()
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$avaliable = [];
|
||||
if ($this->type == Item::TYPE_ROLE) {
|
||||
foreach (array_keys($manager->getRoles()) as $name) {
|
||||
$avaliable[$name] = 'role';
|
||||
}
|
||||
}
|
||||
foreach (array_keys($manager->getPermissions()) as $name) {
|
||||
$avaliable[$name] = $name[0] == '/' ? 'route' : 'permission';
|
||||
}
|
||||
|
||||
$assigned = [];
|
||||
foreach ($manager->getChildren($this->_item->name) as $item) {
|
||||
$assigned[$item->name] = $item->type == 1 ? 'role' : ($item->name[0] == '/' ? 'route' : 'permission');
|
||||
unset($avaliable[$item->name]);
|
||||
}
|
||||
unset($avaliable[$this->name]);
|
||||
return[
|
||||
'avaliable' => $avaliable,
|
||||
'assigned' => $assigned
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get item
|
||||
* @return Item
|
||||
*/
|
||||
public function getItem()
|
||||
{
|
||||
return $this->_item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get type name
|
||||
* @param mixed $type
|
||||
* @return string|array
|
||||
*/
|
||||
public static function getTypeName($type = null)
|
||||
{
|
||||
$result = [
|
||||
Item::TYPE_PERMISSION => 'Permission',
|
||||
Item::TYPE_ROLE => 'Role'
|
||||
];
|
||||
if ($type === null) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $result[$type];
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models;
|
||||
|
||||
use yii\rbac\Rule;
|
||||
use Yii;
|
||||
|
||||
/**
|
||||
* BizRule
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class BizRule extends \yii\base\Model
|
||||
{
|
||||
/**
|
||||
* @var string name of the rule
|
||||
*/
|
||||
public $name;
|
||||
|
||||
/**
|
||||
* @var integer UNIX timestamp representing the rule creation time
|
||||
*/
|
||||
public $createdAt;
|
||||
|
||||
/**
|
||||
* @var integer UNIX timestamp representing the rule updating time
|
||||
*/
|
||||
public $updatedAt;
|
||||
|
||||
/**
|
||||
* @var string Rule classname.
|
||||
*/
|
||||
public $className;
|
||||
|
||||
/**
|
||||
* @var Rule
|
||||
*/
|
||||
private $_item;
|
||||
|
||||
/**
|
||||
* Initilaize object
|
||||
* @param \yii\rbac\Rule $item
|
||||
* @param array $config
|
||||
*/
|
||||
public function __construct($item, $config = [])
|
||||
{
|
||||
$this->_item = $item;
|
||||
if ($item !== null) {
|
||||
$this->name = $item->name;
|
||||
$this->className = get_class($item);
|
||||
}
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['name', 'className'], 'required'],
|
||||
[['className'], 'string'],
|
||||
[['className'], 'classExists']
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate class exists
|
||||
*/
|
||||
public function classExists()
|
||||
{
|
||||
if (!class_exists($this->className)) {
|
||||
$message = Yii::t('rbac-admin', "Unknown class '{class}'", ['class' => $this->className]);
|
||||
$this->addError('className', $message);
|
||||
return;
|
||||
}
|
||||
if (!is_subclass_of($this->className, Rule::className())) {
|
||||
$message = Yii::t('rbac-admin', "'{class}' must extend from 'yii\rbac\Rule' or its child class", [
|
||||
'class' => $this->className]);
|
||||
$this->addError('className', $message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return [
|
||||
'name' => Yii::t('rbac-admin', 'Name'),
|
||||
'className' => Yii::t('rbac-admin', 'Class Name'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if new record.
|
||||
* @return boolean
|
||||
*/
|
||||
public function getIsNewRecord()
|
||||
{
|
||||
return $this->_item === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find model by id
|
||||
* @param type $id
|
||||
* @return null|static
|
||||
*/
|
||||
public static function find($id)
|
||||
{
|
||||
$item = Yii::$app->getAuthManager()->getRule($id);
|
||||
if ($item !== null) {
|
||||
return new static($item);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save model to authManager
|
||||
* @return boolean
|
||||
*/
|
||||
public function save()
|
||||
{
|
||||
if ($this->validate()) {
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$class = $this->className;
|
||||
if ($this->_item === null) {
|
||||
$this->_item = new $class();
|
||||
$isNew = true;
|
||||
} else {
|
||||
$isNew = false;
|
||||
$oldName = $this->_item->name;
|
||||
}
|
||||
$this->_item->name = $this->name;
|
||||
|
||||
if ($isNew) {
|
||||
$manager->add($this->_item);
|
||||
} else {
|
||||
$manager->update($oldName, $this->_item);
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get item
|
||||
* @return Item
|
||||
*/
|
||||
public function getItem()
|
||||
{
|
||||
return $this->_item;
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models;
|
||||
|
||||
use Yii;
|
||||
use mdm\admin\components\Configs;
|
||||
use yii\db\Query;
|
||||
|
||||
/**
|
||||
* This is the model class for table "menu".
|
||||
*
|
||||
* @property integer $id Menu id(autoincrement)
|
||||
* @property string $name Menu name
|
||||
* @property integer $parent Menu parent
|
||||
* @property string $route Route for this menu
|
||||
* @property integer $order Menu order
|
||||
* @property string $data Extra information for this menu
|
||||
*
|
||||
* @property Menu $menuParent Menu parent
|
||||
* @property Menu[] $menus Menu children
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class Menu extends \yii\db\ActiveRecord
|
||||
{
|
||||
public $parent_name;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function tableName()
|
||||
{
|
||||
return Configs::instance()->menuTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function getDb()
|
||||
{
|
||||
if (Configs::instance()->db !== null) {
|
||||
return Configs::instance()->db;
|
||||
} else {
|
||||
return parent::getDb();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['name'], 'required'],
|
||||
[['parent_name'], 'in',
|
||||
'range' => static::find()->select(['name'])->column(),
|
||||
'message' => 'Menu "{value}" not found.'],
|
||||
[['parent', 'route', 'data', 'order'], 'default'],
|
||||
[['parent'], 'filterParent', 'when' => function() {
|
||||
return !$this->isNewRecord;
|
||||
}],
|
||||
[['order'], 'integer'],
|
||||
[['route'], 'in',
|
||||
'range' => static::getSavedRoutes(),
|
||||
'message' => 'Route "{value}" not found.']
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Use to loop detected.
|
||||
*/
|
||||
public function filterParent()
|
||||
{
|
||||
$parent = $this->parent;
|
||||
$db = static::getDb();
|
||||
$query = (new Query)->select(['parent'])
|
||||
->from(static::tableName())
|
||||
->where('[[id]]=:id');
|
||||
while ($parent) {
|
||||
if ($this->id == $parent) {
|
||||
$this->addError('parent_name', 'Loop detected.');
|
||||
return;
|
||||
}
|
||||
$parent = $query->params([':id' => $parent])->scalar($db);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return [
|
||||
'id' => Yii::t('rbac-admin', 'ID'),
|
||||
'name' => Yii::t('rbac-admin', 'Name'),
|
||||
'parent' => Yii::t('rbac-admin', 'Parent'),
|
||||
'parent_name' => Yii::t('rbac-admin', 'Parent Name'),
|
||||
'route' => Yii::t('rbac-admin', 'Route'),
|
||||
'order' => Yii::t('rbac-admin', 'Order'),
|
||||
'data' => Yii::t('rbac-admin', 'Data'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get menu parent
|
||||
* @return \yii\db\ActiveQuery
|
||||
*/
|
||||
public function getMenuParent()
|
||||
{
|
||||
return $this->hasOne(Menu::className(), ['id' => 'parent']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get menu children
|
||||
* @return \yii\db\ActiveQuery
|
||||
*/
|
||||
public function getMenus()
|
||||
{
|
||||
return $this->hasMany(Menu::className(), ['parent' => 'id']);
|
||||
}
|
||||
private static $_routes;
|
||||
|
||||
/**
|
||||
* Get saved routes.
|
||||
* @return array
|
||||
*/
|
||||
public static function getSavedRoutes()
|
||||
{
|
||||
if (self::$_routes === null) {
|
||||
self::$_routes = [];
|
||||
foreach (Yii::$app->getAuthManager()->getPermissions() as $name => $value) {
|
||||
if ($name[0] === '/' && substr($name, -1) != '*') {
|
||||
self::$_routes[] = $name;
|
||||
}
|
||||
}
|
||||
}
|
||||
return self::$_routes;
|
||||
}
|
||||
|
||||
public static function getMenuSource()
|
||||
{
|
||||
$tableName = static::tableName();
|
||||
return (new \yii\db\Query())
|
||||
->select(['m.id', 'm.name', 'm.route', 'parent_name' => 'p.name'])
|
||||
->from(['m' => $tableName])
|
||||
->leftJoin(['p' => $tableName], '[[m.parent]]=[[p.id]]')
|
||||
->all(static::getDb());
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models;
|
||||
|
||||
use Yii;
|
||||
use mdm\admin\components\Helper;
|
||||
use yii\caching\TagDependency;
|
||||
use mdm\admin\components\RouteRule;
|
||||
use mdm\admin\components\Configs;
|
||||
use yii\helpers\VarDumper;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Description of Route
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
|
||||
class Route extends \yii\base\BaseObject
|
||||
{
|
||||
const CACHE_TAG = 'mdm.admin.route';
|
||||
|
||||
/**
|
||||
* Assign or remove items
|
||||
* @param array $routes
|
||||
* @return array
|
||||
*/
|
||||
public function addNew($routes)
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
foreach ($routes as $route) {
|
||||
try {
|
||||
$r = explode('&', $route);
|
||||
$item = $manager->createPermission('/' . trim($route, '/'));
|
||||
if (count($r) > 1) {
|
||||
$action = '/' . trim($r[0], '/');
|
||||
if (($itemAction = $manager->getPermission($action)) === null) {
|
||||
$itemAction = $manager->createPermission($action);
|
||||
$manager->add($itemAction);
|
||||
}
|
||||
unset($r[0]);
|
||||
foreach ($r as $part) {
|
||||
$part = explode('=', $part);
|
||||
$item->data['params'][$part[0]] = isset($part[1]) ? $part[1] : '';
|
||||
}
|
||||
$this->setDefaultRule();
|
||||
$item->ruleName = RouteRule::RULE_NAME;
|
||||
$manager->add($item);
|
||||
$manager->addChild($item, $itemAction);
|
||||
} else {
|
||||
$manager->add($item);
|
||||
}
|
||||
} catch (Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
}
|
||||
Helper::invalidate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign or remove items
|
||||
* @param array $routes
|
||||
* @return array
|
||||
*/
|
||||
public function remove($routes)
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
foreach ($routes as $route) {
|
||||
try {
|
||||
$item = $manager->createPermission('/' . trim($route, '/'));
|
||||
$manager->remove($item);
|
||||
} catch (Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
}
|
||||
Helper::invalidate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get avaliable and assigned routes
|
||||
* @return array
|
||||
*/
|
||||
public function getRoutes()
|
||||
{
|
||||
$manager = Yii::$app->getAuthManager();
|
||||
$routes = $this->getAppRoutes();
|
||||
$exists = [];
|
||||
foreach (array_keys($manager->getPermissions()) as $name) {
|
||||
if ($name[0] !== '/') {
|
||||
continue;
|
||||
}
|
||||
$exists[] = $name;
|
||||
unset($routes[$name]);
|
||||
}
|
||||
return[
|
||||
'avaliable' => array_keys($routes),
|
||||
'assigned' => $exists
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of application routes
|
||||
* @return array
|
||||
*/
|
||||
public function getAppRoutes($module = null)
|
||||
{
|
||||
if ($module === null) {
|
||||
$module = Yii::$app;
|
||||
} elseif (is_string($module)) {
|
||||
$module = Yii::$app->getModule($module);
|
||||
}
|
||||
$key = [__METHOD__, $module->getUniqueId()];
|
||||
$cache = Configs::instance()->cache;
|
||||
if ($cache === null || ($result = $cache->get($key)) === false) {
|
||||
$result = [];
|
||||
$this->getRouteRecrusive($module, $result);
|
||||
if ($cache !== null) {
|
||||
$cache->set($key, $result, Configs::instance()->cacheDuration, new TagDependency([
|
||||
'tags' => self::CACHE_TAG,
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get route(s) recrusive
|
||||
* @param \yii\base\Module $module
|
||||
* @param array $result
|
||||
*/
|
||||
protected function getRouteRecrusive($module, &$result)
|
||||
{
|
||||
$token = "Get Route of '" . get_class($module) . "' with id '" . $module->uniqueId . "'";
|
||||
Yii::beginProfile($token, __METHOD__);
|
||||
try {
|
||||
foreach ($module->getModules() as $id => $child) {
|
||||
if (($child = $module->getModule($id)) !== null) {
|
||||
$this->getRouteRecrusive($child, $result);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($module->controllerMap as $id => $type) {
|
||||
$this->getControllerActions($type, $id, $module, $result);
|
||||
}
|
||||
|
||||
$namespace = trim($module->controllerNamespace, '\\') . '\\';
|
||||
$this->getControllerFiles($module, $namespace, '', $result);
|
||||
$all = '/' . ltrim($module->uniqueId . '/*', '/');
|
||||
$result[$all] = $all;
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
Yii::endProfile($token, __METHOD__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list controller under module
|
||||
* @param \yii\base\Module $module
|
||||
* @param string $namespace
|
||||
* @param string $prefix
|
||||
* @param mixed $result
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getControllerFiles($module, $namespace, $prefix, &$result)
|
||||
{
|
||||
$path = Yii::getAlias('@' . str_replace('\\', '/', $namespace), false);
|
||||
$token = "Get controllers from '$path'";
|
||||
Yii::beginProfile($token, __METHOD__);
|
||||
try {
|
||||
if (!is_dir($path)) {
|
||||
return;
|
||||
}
|
||||
foreach (scandir($path) as $file) {
|
||||
if ($file == '.' || $file == '..') {
|
||||
continue;
|
||||
}
|
||||
if (is_dir($path . '/' . $file) && preg_match('%^[a-z0-9_/]+$%i', $file . '/')) {
|
||||
$this->getControllerFiles($module, $namespace . $file . '\\', $prefix . $file . '/', $result);
|
||||
} elseif (strcmp(substr($file, -14), 'Controller.php') === 0) {
|
||||
$baseName = substr(basename($file), 0, -14);
|
||||
$name = strtolower(preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $baseName));
|
||||
$id = ltrim(str_replace(' ', '-', $name), '-');
|
||||
$className = $namespace . $baseName . 'Controller';
|
||||
if (strpos($className, '-') === false && class_exists($className) && is_subclass_of($className, 'yii\base\Controller')) {
|
||||
$this->getControllerActions($className, $prefix . $id, $module, $result);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
Yii::endProfile($token, __METHOD__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list action of controller
|
||||
* @param mixed $type
|
||||
* @param string $id
|
||||
* @param \yii\base\Module $module
|
||||
* @param string $result
|
||||
*/
|
||||
protected function getControllerActions($type, $id, $module, &$result)
|
||||
{
|
||||
$token = "Create controller with cofig=" . VarDumper::dumpAsString($type) . " and id='$id'";
|
||||
Yii::beginProfile($token, __METHOD__);
|
||||
try {
|
||||
/* @var $controller \yii\base\Controller */
|
||||
$controller = Yii::createObject($type, [$id, $module]);
|
||||
$this->getActionRoutes($controller, $result);
|
||||
$all = "/{$controller->uniqueId}/*";
|
||||
$result[$all] = $all;
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
Yii::endProfile($token, __METHOD__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get route of action
|
||||
* @param \yii\base\Controller $controller
|
||||
* @param array $result all controller action.
|
||||
*/
|
||||
protected function getActionRoutes($controller, &$result)
|
||||
{
|
||||
$token = "Get actions of controller '" . $controller->uniqueId . "'";
|
||||
Yii::beginProfile($token, __METHOD__);
|
||||
try {
|
||||
$prefix = '/' . $controller->uniqueId . '/';
|
||||
foreach ($controller->actions() as $id => $value) {
|
||||
$result[$prefix . $id] = $prefix . $id;
|
||||
}
|
||||
$class = new \ReflectionClass($controller);
|
||||
foreach ($class->getMethods() as $method) {
|
||||
$name = $method->getName();
|
||||
if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0 && $name !== 'actions') {
|
||||
$name = strtolower(preg_replace('/(?<![A-Z])[A-Z]/', ' \0', substr($name, 6)));
|
||||
$id = $prefix . ltrim(str_replace(' ', '-', $name), '-');
|
||||
$result[$id] = $id;
|
||||
}
|
||||
}
|
||||
} catch (\Exception $exc) {
|
||||
Yii::error($exc->getMessage(), __METHOD__);
|
||||
}
|
||||
Yii::endProfile($token, __METHOD__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ivalidate cache
|
||||
*/
|
||||
public static function invalidate()
|
||||
{
|
||||
if (Configs::cache() !== null) {
|
||||
TagDependency::invalidate(Configs::cache(), self::CACHE_TAG);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set default rule of parameterize route.
|
||||
*/
|
||||
protected function setDefaultRule()
|
||||
{
|
||||
if (Yii::$app->getAuthManager()->getRule(RouteRule::RULE_NAME) === null) {
|
||||
Yii::$app->getAuthManager()->add(new RouteRule());
|
||||
}
|
||||
}
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models;
|
||||
|
||||
use Yii;
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\behaviors\TimestampBehavior;
|
||||
use yii\db\ActiveRecord;
|
||||
use yii\web\IdentityInterface;
|
||||
use mdm\admin\components\Configs;
|
||||
|
||||
/**
|
||||
* User model
|
||||
*
|
||||
* @property integer $id
|
||||
* @property string $username
|
||||
* @property string $password_hash
|
||||
* @property string $password_reset_token
|
||||
* @property string $email
|
||||
* @property string $auth_key
|
||||
* @property integer $status
|
||||
* @property integer $created_at
|
||||
* @property integer $updated_at
|
||||
* @property string $password write-only password
|
||||
*
|
||||
* @property UserProfile $profile
|
||||
*/
|
||||
class User extends ActiveRecord implements IdentityInterface
|
||||
{
|
||||
const STATUS_INACTIVE = 0;
|
||||
const STATUS_ACTIVE = 10;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function tableName()
|
||||
{
|
||||
return Configs::instance()->userTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function behaviors()
|
||||
{
|
||||
return [
|
||||
TimestampBehavior::className(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
['status', 'default', 'value' => self::STATUS_ACTIVE],
|
||||
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE]],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function findIdentity($id)
|
||||
{
|
||||
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public static function findIdentityByAccessToken($token, $type = null)
|
||||
{
|
||||
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds user by username
|
||||
*
|
||||
* @param string $username
|
||||
* @return static|null
|
||||
*/
|
||||
public static function findByUsername($username)
|
||||
{
|
||||
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds user by password reset token
|
||||
*
|
||||
* @param string $token password reset token
|
||||
* @return static|null
|
||||
*/
|
||||
public static function findByPasswordResetToken($token)
|
||||
{
|
||||
if (!static::isPasswordResetTokenValid($token)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return static::findOne([
|
||||
'password_reset_token' => $token,
|
||||
'status' => self::STATUS_ACTIVE,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds out if password reset token is valid
|
||||
*
|
||||
* @param string $token password reset token
|
||||
* @return boolean
|
||||
*/
|
||||
public static function isPasswordResetTokenValid($token)
|
||||
{
|
||||
if (empty($token)) {
|
||||
return false;
|
||||
}
|
||||
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
|
||||
$parts = explode('_', $token);
|
||||
$timestamp = (int) end($parts);
|
||||
return $timestamp + $expire >= time();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->getPrimaryKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getAuthKey()
|
||||
{
|
||||
return $this->auth_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function validateAuthKey($authKey)
|
||||
{
|
||||
return $this->getAuthKey() === $authKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates password
|
||||
*
|
||||
* @param string $password password to validate
|
||||
* @return boolean if password provided is valid for current user
|
||||
*/
|
||||
public function validatePassword($password)
|
||||
{
|
||||
return Yii::$app->security->validatePassword($password, $this->password_hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates password hash from password and sets it to the model
|
||||
*
|
||||
* @param string $password
|
||||
*/
|
||||
public function setPassword($password)
|
||||
{
|
||||
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates "remember me" authentication key
|
||||
*/
|
||||
public function generateAuthKey()
|
||||
{
|
||||
$this->auth_key = Yii::$app->security->generateRandomString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates new password reset token
|
||||
*/
|
||||
public function generatePasswordResetToken()
|
||||
{
|
||||
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes password reset token
|
||||
*/
|
||||
public function removePasswordResetToken()
|
||||
{
|
||||
$this->password_reset_token = null;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\form;
|
||||
|
||||
use Yii;
|
||||
use mdm\admin\models\User;
|
||||
use yii\base\Model;
|
||||
|
||||
/**
|
||||
* Description of ChangePassword
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class ChangePassword extends Model
|
||||
{
|
||||
public $oldPassword;
|
||||
public $newPassword;
|
||||
public $retypePassword;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['oldPassword', 'newPassword', 'retypePassword'], 'required'],
|
||||
[['oldPassword'], 'validatePassword'],
|
||||
[['newPassword'], 'string', 'min' => 6],
|
||||
[['retypePassword'], 'compare', 'compareAttribute' => 'newPassword'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the password.
|
||||
* This method serves as the inline validation for password.
|
||||
*/
|
||||
public function validatePassword()
|
||||
{
|
||||
/* @var $user User */
|
||||
$user = Yii::$app->user->identity;
|
||||
if (!$user || !$user->validatePassword($this->oldPassword)) {
|
||||
$this->addError('oldPassword', 'Incorrect old password.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change password.
|
||||
*
|
||||
* @return User|null the saved model or null if saving fails
|
||||
*/
|
||||
public function change()
|
||||
{
|
||||
if ($this->validate()) {
|
||||
/* @var $user User */
|
||||
$user = Yii::$app->user->identity;
|
||||
$user->setPassword($this->newPassword);
|
||||
$user->generateAuthKey();
|
||||
if ($user->save()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\form;
|
||||
|
||||
use Yii;
|
||||
use yii\base\Model;
|
||||
use mdm\admin\models\User;
|
||||
|
||||
/**
|
||||
* Login form
|
||||
*/
|
||||
class Login extends Model
|
||||
{
|
||||
public $username;
|
||||
public $password;
|
||||
public $rememberMe = true;
|
||||
|
||||
private $_user = false;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
// username and password are both required
|
||||
[['username', 'password'], 'required'],
|
||||
// rememberMe must be a boolean value
|
||||
['rememberMe', 'boolean'],
|
||||
// password is validated by validatePassword()
|
||||
['password', 'validatePassword'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the password.
|
||||
* This method serves as the inline validation for password.
|
||||
*
|
||||
* @param string $attribute the attribute currently being validated
|
||||
* @param array $params the additional name-value pairs given in the rule
|
||||
*/
|
||||
public function validatePassword($attribute, $params)
|
||||
{
|
||||
if (!$this->hasErrors()) {
|
||||
$user = $this->getUser();
|
||||
if (!$user || !$user->validatePassword($this->password)) {
|
||||
$this->addError($attribute, 'Incorrect username or password.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs in a user using the provided username and password.
|
||||
*
|
||||
* @return boolean whether the user is logged in successfully
|
||||
*/
|
||||
public function login()
|
||||
{
|
||||
if ($this->validate()) {
|
||||
return Yii::$app->getUser()->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds user by [[username]]
|
||||
*
|
||||
* @return User|null
|
||||
*/
|
||||
public function getUser()
|
||||
{
|
||||
if ($this->_user === false) {
|
||||
$this->_user = User::findByUsername($this->username);
|
||||
}
|
||||
|
||||
return $this->_user;
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
namespace mdm\admin\models\form;
|
||||
|
||||
use Yii;
|
||||
use mdm\admin\models\User;
|
||||
use yii\base\Model;
|
||||
|
||||
/**
|
||||
* Password reset request form
|
||||
*/
|
||||
class PasswordResetRequest extends Model
|
||||
{
|
||||
public $email;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
['email', 'filter', 'filter' => 'trim'],
|
||||
['email', 'required'],
|
||||
['email', 'email'],
|
||||
['email', 'exist',
|
||||
'targetClass' => 'mdm\admin\models\User',
|
||||
'filter' => ['status' => User::STATUS_ACTIVE],
|
||||
'message' => 'There is no user with such email.'
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an email with a link, for resetting the password.
|
||||
*
|
||||
* @return boolean whether the email was send
|
||||
*/
|
||||
public function sendEmail()
|
||||
{
|
||||
/* @var $user User */
|
||||
$user = User::findOne([
|
||||
'status' => User::STATUS_ACTIVE,
|
||||
'email' => $this->email,
|
||||
]);
|
||||
|
||||
if ($user) {
|
||||
if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
|
||||
$user->generatePasswordResetToken();
|
||||
}
|
||||
|
||||
if ($user->save()) {
|
||||
return Yii::$app->mailer->compose(['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'], ['user' => $user])
|
||||
->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
|
||||
->setTo($this->email)
|
||||
->setSubject('Password reset for ' . Yii::$app->name)
|
||||
->send();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\form;
|
||||
|
||||
use Yii;
|
||||
use mdm\admin\models\User;
|
||||
use yii\base\InvalidParamException;
|
||||
use yii\base\Model;
|
||||
|
||||
/**
|
||||
* Password reset form
|
||||
*/
|
||||
class ResetPassword extends Model
|
||||
{
|
||||
public $password;
|
||||
/**
|
||||
* @var User
|
||||
*/
|
||||
private $_user;
|
||||
|
||||
/**
|
||||
* Creates a form model given a token.
|
||||
*
|
||||
* @param string $token
|
||||
* @param array $config name-value pairs that will be used to initialize the object properties
|
||||
* @throws \yii\base\InvalidParamException if token is empty or not valid
|
||||
*/
|
||||
public function __construct($token, $config = [])
|
||||
{
|
||||
if (empty($token) || !is_string($token)) {
|
||||
throw new InvalidParamException('Password reset token cannot be blank.');
|
||||
}
|
||||
$this->_user = User::findByPasswordResetToken($token);
|
||||
if (!$this->_user) {
|
||||
throw new InvalidParamException('Wrong password reset token.');
|
||||
}
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
['password', 'required'],
|
||||
['password', 'string', 'min' => 6],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets password.
|
||||
*
|
||||
* @return boolean if password was reset.
|
||||
*/
|
||||
public function resetPassword()
|
||||
{
|
||||
$user = $this->_user;
|
||||
$user->setPassword($this->password);
|
||||
$user->removePasswordResetToken();
|
||||
|
||||
return $user->save(false);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
namespace mdm\admin\models\form;
|
||||
|
||||
use Yii;
|
||||
use mdm\admin\models\User;
|
||||
use yii\base\Model;
|
||||
|
||||
/**
|
||||
* Signup form
|
||||
*/
|
||||
class Signup extends Model
|
||||
{
|
||||
public $username;
|
||||
public $email;
|
||||
public $password;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
['username', 'filter', 'filter' => 'trim'],
|
||||
['username', 'required'],
|
||||
['username', 'unique', 'targetClass' => 'mdm\admin\models\User', 'message' => 'This username has already been taken.'],
|
||||
['username', 'string', 'min' => 2, 'max' => 255],
|
||||
|
||||
['email', 'filter', 'filter' => 'trim'],
|
||||
['email', 'required'],
|
||||
['email', 'email'],
|
||||
['email', 'unique', 'targetClass' => 'mdm\admin\models\User', 'message' => 'This email address has already been taken.'],
|
||||
|
||||
['password', 'required'],
|
||||
['password', 'string', 'min' => 6],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs user up.
|
||||
*
|
||||
* @return User|null the saved model or null if saving fails
|
||||
*/
|
||||
public function signup()
|
||||
{
|
||||
if ($this->validate()) {
|
||||
$user = new User();
|
||||
$user->username = $this->username;
|
||||
$user->email = $this->email;
|
||||
$user->setPassword($this->password);
|
||||
$user->generateAuthKey();
|
||||
if ($user->save()) {
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\searchs;
|
||||
|
||||
use Yii;
|
||||
use yii\base\Model;
|
||||
use yii\data\ActiveDataProvider;
|
||||
|
||||
/**
|
||||
* AssignmentSearch represents the model behind the search form about Assignment.
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class Assignment extends Model
|
||||
{
|
||||
public $id;
|
||||
public $username;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['id', 'username'], 'safe'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return [
|
||||
'id' => Yii::t('rbac-admin', 'ID'),
|
||||
'username' => Yii::t('rbac-admin', 'Username'),
|
||||
'name' => Yii::t('rbac-admin', 'Name'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create data provider for Assignment model.
|
||||
* @param array $params
|
||||
* @param \yii\db\ActiveRecord $class
|
||||
* @param string $usernameField
|
||||
* @return \yii\data\ActiveDataProvider
|
||||
*/
|
||||
public function search($params, $class, $usernameField)
|
||||
{
|
||||
$query = $class::find();
|
||||
$dataProvider = new ActiveDataProvider([
|
||||
'query' => $query,
|
||||
]);
|
||||
|
||||
if (!($this->load($params) && $this->validate())) {
|
||||
return $dataProvider;
|
||||
}
|
||||
|
||||
$query->andFilterWhere(['like', $usernameField, $this->username]);
|
||||
|
||||
return $dataProvider;
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\searchs;
|
||||
|
||||
use Yii;
|
||||
use yii\base\Model;
|
||||
use yii\data\ArrayDataProvider;
|
||||
use yii\rbac\Item;
|
||||
|
||||
/**
|
||||
* AuthItemSearch represents the model behind the search form about AuthItem.
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class AuthItem extends Model
|
||||
{
|
||||
const TYPE_ROUTE = 101;
|
||||
|
||||
public $name;
|
||||
public $type;
|
||||
public $description;
|
||||
public $ruleName;
|
||||
public $data;
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['name', 'ruleName', 'description'], 'safe'],
|
||||
[['type'], 'integer'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return [
|
||||
'name' => Yii::t('rbac-admin', 'Name'),
|
||||
'item_name' => Yii::t('rbac-admin', 'Name'),
|
||||
'type' => Yii::t('rbac-admin', 'Type'),
|
||||
'description' => Yii::t('rbac-admin', 'Description'),
|
||||
'ruleName' => Yii::t('rbac-admin', 'Rule Name'),
|
||||
'data' => Yii::t('rbac-admin', 'Data'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Search authitem
|
||||
* @param array $params
|
||||
* @return \yii\data\ActiveDataProvider|\yii\data\ArrayDataProvider
|
||||
*/
|
||||
public function search($params)
|
||||
{
|
||||
/* @var \yii\rbac\Manager $authManager */
|
||||
$authManager = Yii::$app->getAuthManager();
|
||||
if ($this->type == Item::TYPE_ROLE) {
|
||||
$items = $authManager->getRoles();
|
||||
} else {
|
||||
$items = array_filter($authManager->getPermissions(), function($item) {
|
||||
return $this->type == Item::TYPE_PERMISSION xor strncmp($item->name, '/', 1) === 0;
|
||||
});
|
||||
}
|
||||
$this->load($params);
|
||||
if ($this->validate()) {
|
||||
$search = empty($this->name) ? '' : strtolower(trim($this->name));
|
||||
$desc = empty($this->description) ? '' : strtolower(trim($this->description));
|
||||
$ruleName = $this->ruleName;
|
||||
foreach ($items as $name => $item) {
|
||||
$f = (empty($search) || strpos(strtolower($item->name), $search) !== false) &&
|
||||
(empty($desc) || strpos(strtolower($item->description), $desc) !== false) &&
|
||||
(empty($ruleName) || $item->ruleName == $ruleName);
|
||||
if (!$f) {
|
||||
unset($items[$name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayDataProvider([
|
||||
'allModels' => $items,
|
||||
]);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\searchs;
|
||||
|
||||
use Yii;
|
||||
use yii\base\Model;
|
||||
use yii\data\ArrayDataProvider;
|
||||
use mdm\admin\models\BizRule as MBizRule;
|
||||
use mdm\admin\components\RouteRule;
|
||||
|
||||
/**
|
||||
* Description of BizRule
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class BizRule extends Model
|
||||
{
|
||||
/**
|
||||
* @var string name of the rule
|
||||
*/
|
||||
public $name;
|
||||
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['name'], 'safe']
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function attributeLabels()
|
||||
{
|
||||
return [
|
||||
'name' => Yii::t('rbac-admin', 'Name'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Search BizRule
|
||||
* @param array $params
|
||||
* @return \yii\data\ActiveDataProvider|\yii\data\ArrayDataProvider
|
||||
*/
|
||||
public function search($params)
|
||||
{
|
||||
/* @var \yii\rbac\Manager $authManager */
|
||||
$authManager = Yii::$app->authManager;
|
||||
$models = [];
|
||||
$included = !($this->load($params) && $this->validate() && trim($this->name) !== '');
|
||||
foreach ($authManager->getRules() as $name => $item) {
|
||||
if ($name != RouteRule::RULE_NAME && ($included || stripos($item->name, $this->name) !== false)) {
|
||||
$models[$name] = new MBizRule($item);
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayDataProvider([
|
||||
'allModels' => $models,
|
||||
]);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\searchs;
|
||||
|
||||
use Yii;
|
||||
use yii\base\Model;
|
||||
use yii\data\ActiveDataProvider;
|
||||
use mdm\admin\models\Menu as MenuModel;
|
||||
|
||||
/**
|
||||
* Menu represents the model behind the search form about [[\mdm\admin\models\Menu]].
|
||||
*
|
||||
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
|
||||
* @since 1.0
|
||||
*/
|
||||
class Menu extends MenuModel
|
||||
{
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['id', 'parent', 'order'], 'integer'],
|
||||
[['name', 'route', 'parent_name'], 'safe'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function scenarios()
|
||||
{
|
||||
// bypass scenarios() implementation in the parent class
|
||||
return Model::scenarios();
|
||||
}
|
||||
|
||||
/**
|
||||
* Searching menu
|
||||
* @param array $params
|
||||
* @return \yii\data\ActiveDataProvider
|
||||
*/
|
||||
public function search($params)
|
||||
{
|
||||
$query = MenuModel::find()
|
||||
->from(MenuModel::tableName() . ' t')
|
||||
->joinWith(['menuParent' => function ($q) {
|
||||
$q->from(MenuModel::tableName() . ' parent');
|
||||
}]);
|
||||
|
||||
$dataProvider = new ActiveDataProvider([
|
||||
'query' => $query
|
||||
]);
|
||||
|
||||
$sort = $dataProvider->getSort();
|
||||
$sort->attributes['menuParent.name'] = [
|
||||
'asc' => ['parent.name' => SORT_ASC],
|
||||
'desc' => ['parent.name' => SORT_DESC],
|
||||
'label' => 'parent',
|
||||
];
|
||||
$sort->attributes['order'] = [
|
||||
'asc' => ['parent.order' => SORT_ASC, 't.order' => SORT_ASC],
|
||||
'desc' => ['parent.order' => SORT_DESC, 't.order' => SORT_DESC],
|
||||
'label' => 'order',
|
||||
];
|
||||
$sort->defaultOrder = ['menuParent.name' => SORT_ASC];
|
||||
|
||||
if (!($this->load($params) && $this->validate())) {
|
||||
return $dataProvider;
|
||||
}
|
||||
|
||||
$query->andFilterWhere([
|
||||
't.id' => $this->id,
|
||||
't.parent' => $this->parent,
|
||||
]);
|
||||
|
||||
$query->andFilterWhere(['like', 'lower(t.name)', strtolower($this->name)])
|
||||
->andFilterWhere(['like', 't.route', $this->route])
|
||||
->andFilterWhere(['like', 'lower(parent.name)', strtolower($this->parent_name)]);
|
||||
|
||||
return $dataProvider;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace mdm\admin\models\searchs;
|
||||
|
||||
use Yii;
|
||||
use yii\base\Model;
|
||||
use yii\data\ActiveDataProvider;
|
||||
use mdm\admin\models\User as UserModel;
|
||||
|
||||
/**
|
||||
* User represents the model behind the search form about `mdm\admin\models\User`.
|
||||
*/
|
||||
class User extends UserModel
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
[['id', 'status', 'created_at', 'updated_at'], 'integer'],
|
||||
[['username', 'auth_key', 'password_hash', 'password_reset_token', 'email'], 'safe'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function scenarios()
|
||||
{
|
||||
// bypass scenarios() implementation in the parent class
|
||||
return Model::scenarios();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates data provider instance with search query applied
|
||||
*
|
||||
* @param array $params
|
||||
*
|
||||
* @return ActiveDataProvider
|
||||
*/
|
||||
public function search($params)
|
||||
{
|
||||
$query = UserModel::find();
|
||||
|
||||
$dataProvider = new ActiveDataProvider([
|
||||
'query' => $query,
|
||||
]);
|
||||
|
||||
$this->load($params);
|
||||
if (!$this->validate()) {
|
||||
$query->where('1=0');
|
||||
return $dataProvider;
|
||||
}
|
||||
|
||||
$query->andFilterWhere([
|
||||
'id' => $this->id,
|
||||
'status' => $this->status,
|
||||
'created_at' => $this->created_at,
|
||||
'updated_at' => $this->updated_at,
|
||||
]);
|
||||
|
||||
$query->andFilterWhere(['like', 'username', $this->username])
|
||||
->andFilterWhere(['like', 'auth_key', $this->auth_key])
|
||||
->andFilterWhere(['like', 'password_hash', $this->password_hash])
|
||||
->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
|
||||
->andFilterWhere(['like', 'email', $this->email]);
|
||||
|
||||
return $dataProvider;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user