提交 29d8fa9a 编写于 作者: T Terry

调整:admin user

上级 e194ade7
<?php
/**
* FecShop file.
*
* @link http://www.fecshop.com/
* @copyright Copyright (c) 2016 FecShop Software LLC
* @license http://www.fecshop.com/license/
*/
namespace fecshop\app\appadmin\modules\Fecadmin\block\account;
use fec\helpers\CUrl;
use fecshop\app\appadmin\interfaces\base\AppadminbaseBlockInterface;
use fecshop\app\appadmin\modules\AppadminbaseBlock;
use Yii;
/**
* block cms\article.
* @author Terry Zhao <2358269014@qq.com>
* @since 1.0
*/
class Manager extends AppadminbaseBlock implements AppadminbaseBlockInterface
{
public function init()
{
/*
* edit data url
*/
$this->_editUrl = CUrl::getUrl('fecadmin/account/manageredit');
/*
* delete data url
*/
$this->_deleteUrl = CUrl::getUrl('fecadmin/account/managerdelete');
/*
* service component, data provider
*/
$this->_service = Yii::$service->adminUser->adminUser;
parent::init();
}
public function getLastData(){
# 返回数据的函数
# 隐藏部分
$pagerForm = $this->getPagerForm();
# 搜索部分
$searchBar = $this->getSearchBar();
# 编辑 删除 按钮部分
$editBar = $this->getEditBar();
# 表头部分
$thead = $this->getTableThead();
# 表内容部分
$tbody = $this->getTableTbody();
# 分页部分
$toolBar = $this->getToolBar($this->_param['numCount'],$this->_param['pageNum'],$this->_param['numPerPage']);
return [
'pagerForm' => $pagerForm,
'searchBar' => $searchBar,
'editBar' => $editBar,
'thead' => $thead,
'tbody' => $tbody,
'toolBar' => $toolBar,
];
}
# 定义搜索部分字段格式
public function getSearchArr(){
$data = [
[ # selecit的Int 类型
'type'=>'select',
'title'=>'状态',
'name'=>'status',
'columns_type' =>'int', # int使用标准匹配, string使用模糊查询
'value'=> [ # select 类型的值
Yii::$service->adminUser->adminUser->getActiveStatus() => '激活',
Yii::$service->adminUser->adminUser->getDeleteStatus() => '关闭',
],
],
[ # 字符串类型
'type'=>'inputtext',
'title'=>'用户名',
'name'=>'username' ,
'columns_type' =>'string'
],
[ # 字符串类型
'type'=>'inputtext',
'title'=>'员工编号',
'name'=>'code' ,
'columns_type' =>'string'
],
[ # 字符串类型
'type'=>'inputtext',
'title'=>'邮箱',
'name'=>'email' ,
'columns_type' =>'string'
],
[ # 时间区间类型搜索
'type'=>'inputdatefilter',
'name'=> 'created_at_datetime',
'columns_type' =>'datetime',
'value'=>[
'gte'=>'用户创建时间开始',
'lt' =>'用户创建时间结束',
]
],
];
return $data;
}
# 定义表格显示部分的配置
public function getTableFieldArr(){
$table_th_bar = [
[
'orderField' => 'id',
'label' => 'ID',
'width' => '110',
'align' => 'center',
],
[
'orderField' => 'username',
'label' => '用户名称',
'width' => '110',
'align' => 'center',
],
[
'orderField' => 'person',
'label' => '姓名',
'width' => '110',
'align' => 'center',
],
[
'orderField' => 'code',
'label' => '员工编号',
'width' => '110',
'align' => 'center',
],
/*
[
'orderField' => 'role',
'width' => '110',
'align' => 'left',
'display' => AdminRole::getAdminRoleArr(),
],
*/
[
'orderField' => 'email',
'width' => '110',
'align' => 'center',
],
[
'orderField' => 'created_at_datetime',
//'label' => '用户名称',
'width' => '190',
'align' => 'center',
//'convert' => ['datetime' =>'date'],
],
[
'orderField' => 'updated_at_datetime',
//'label' => '用户名称',
'width' => '190',
'align' => 'center',
//'convert' => ['datetime' =>'date'], # int date datetime 显示的转换
],
[
'orderField' => 'status',
//'label' => '用户名称',
'width' => '60',
'align' => 'center',
'display' => [ # 显示转换 ,譬如 值为1显示为激活,值为10显示为关闭
'1' => '激活',
'10' => '关闭',
],
],
/*
[
'orderField' => 'allowance',
//'label' => '用户名称',
//'width' => '190',
'align' => 'center',
],
[
'orderField' => 'allowance_updated_at',
//'label' => '用户名称',
//'width' => '190',
'align' => 'center',
],
*/
];
return $table_th_bar ;
}
}
\ No newline at end of file
<?php
/**
* FecShop file.
*
* @link http://www.fecshop.com/
* @copyright Copyright (c) 2016 FecShop Software LLC
* @license http://www.fecshop.com/license/
*/
namespace fecshop\app\appadmin\modules\Fecadmin\block\account;
use fec\helpers\CRequest;
use fec\helpers\CUrl;
use fecshop\app\appadmin\interfaces\base\AppadminbaseBlockEditInterface;
use fecshop\app\appadmin\modules\AppadminbaseBlockEdit;
use Yii;
/**
* block cms\article.
* @author Terry Zhao <2358269014@qq.com>
* @since 1.0
*/
class Manageredit extends AppadminbaseBlockEdit implements AppadminbaseBlockEditInterface
{
public $_saveUrl;
public function init()
{
$this->_saveUrl = CUrl::getUrl('fecadmin/account/managereditsave');
parent::init();
}
public function setService()
{
$this->_service = Yii::$service->adminUser->adminUser;
}
# 传递给前端的数据 显示编辑form
public function getLastData(){
$role_ids = $this->getUserRoleIds();
return [
'editBar' => $this->getEditBar(),
'role_ids'=>$role_ids,
'saveUrl' => CUrl::getUrl('fecadmin/account/managereditsave'),
];
}
public function save()
{
$request_param = CRequest::param();
$this->_param = $request_param[$this->_editFormData];
$roles = $request_param['role'];
/*
* if attribute is date or date time , db storage format is int ,by frontend pass param is int ,
* you must convert string datetime to time , use strtotime function.
*/
$this->_service->saveUserAndRole($this->_param, $roles);
$errors = Yii::$service->helper->errors->get();
if (!$errors) {
echo json_encode([
'statusCode'=>'200',
'message'=>'save success',
]);
exit;
} else {
echo json_encode([
'statusCode'=>'300',
'message'=>$errors,
]);
exit;
}
}
// 批量删除
public function delete()
{
$ids = '';
if ($id = CRequest::param($this->_primaryKey)) {
$ids = $id;
} elseif ($ids = CRequest::param($this->_primaryKey.'s')) {
$ids = explode(',', $ids);
}
$this->_service->removeUserAndRole($ids);
$errors = Yii::$service->helper->errors->get();
if (!$errors) {
echo json_encode([
'statusCode'=>'200',
'message'=>'remove account success',
]);
exit;
} else {
echo json_encode([
'statusCode'=>'300',
'message'=>$errors,
]);
exit;
}
}
public function getEditArr(){
$activeStatus = Yii::$service->adminUser->adminUser->getActiveStatus();
$deleteStatus = Yii::$service->adminUser->adminUser->getDeleteStatus();
return [
[
'label'=>'用户名',
'name'=>'username',
'display'=>[
'type' => 'inputString',
],
'require' => 1,
],
[
'label'=>'密码',
'name'=>'password',
'display'=>[
'type' => 'inputPassword',
],
'require' => 0,
],
[
'label'=>'邮箱',
'name'=>'email',
'require' => 0,
'display'=>[
'type' => 'inputEmail',
],
],
[
'label'=>'姓名',
'name'=>'person',
'require' => 0,
'display'=>[
'type' => 'inputString',
],
],
[
'label'=>'员工编号',
'name'=>'code',
'require' => 1,
'display'=>[
'type' => 'inputString',
],
],
[
'label'=>'用户状态',
'name'=>'status',
'display'=>[
'type' => 'select',
'data' => [
$activeStatus => '激活',
$deleteStatus => '关闭',
]
],
'require' => 1,
'default' => $activeStatus,
],
//[
// 'label'=>'权限',
// 'name'=>'role',
// 'display'=>[
// 'type' => 'select',
// 'data' => AdminRole::getAdminRoleArr(),
// ],
//],
[
'label'=>'出生日期',
'name'=>'birth_date',
'display'=>[
'type' => 'inputDate',
],
],
[
'name'=>'auth_key',
'display'=>[
'type' => 'inputString',
],
],
[
'name'=>'access_token',
'display'=>[
'type' => 'inputString',
],
],
];
}
public function getUserRoleIds(){
$primaryKey = Yii::$service->adminUser->adminUser->getPrimaryKey();
$user_id = Yii::$app->request->get($primaryKey);
$filter = [
'where' => [
['user_id' => $user_id]
],
'asArray' => true,
'fetchAll' => true,
];
$data = Yii::$service->admin->userRole->coll($filter);
$role_ids = [];
if(is_array($data['coll']) && !empty($data['coll'])){
foreach($data['coll'] as $r){
$role_ids[] = $r['role_id'];
}
}
return $role_ids;
}
public function getEditBar($editArr = []){
if (empty($editArr)) {
$editArr = $this->getEditArr();
}
$str = '';
if($this->_param[$this->_primaryKey]){
$str = '<input type="hidden" value="'.$this->_param[$this->_primaryKey].'" size="30" name="editFormData['.$this->_primaryKey
.']" class="textInput ">';
}
foreach($editArr as $column){
$name = $column['name'];
$require = $column['require'] ? 'required' : '';
$label = $column['label'] ? $column['label'] : $this->_one->getAttributeLabel($name);
$display = isset($column['display']) ? $column['display'] : '';
if(empty($display)){
$display = ['type' => 'inputString'];
}
//var_dump($this->_one['id']);
$value = $this->_one[$name] ? $this->_one[$name] : $column['default'];
$display_type = isset($display['type']) ? $display['type'] : 'inputString';
if($display_type == 'inputString'){
$str .='<p>
<label>'.$label.':</label>
<input type="text" value="'.$value.'" size="30" name="editFormData['.$name.']" class="textInput '.$require.' ">
</p>';
}else if($display_type == 'inputDate'){
$str .='<p>
<label>'.$label.':</label>
<input type="text" value="'.($value ? date("Y-m-d",strtotime($value)) : '').'" size="30" name="editFormData['.$name.']" class="date textInput '.$require.' ">
</p>';
}else if($display_type == 'inputEmail'){
$str .='<p>
<label>'.$label.':</label>
<input type="text" value="'.$value.'" size="30" name="editFormData['.$name.']" class="email textInput '.$require.' ">
</p>';
}else if($display_type == 'inputPassword'){
$str .='<p>
<label>'.$label.':</label>
<input type="password" value="" size="30" name="editFormData['.$name.']" class=" textInput '.$require.' ">
</p>';
}else if($display_type == 'select'){
$data = isset($display['data']) ? $display['data'] : '';
//var_dump($data);
//echo $value;
$select_str = '';
if(is_array($data)){
$select_str .= '<select class="combox '.$require.'" name="editFormData['.$name.']" >';
$select_str .='<option value="">'.$label.'</option>';
foreach($data as $k => $v){
if($value == $k){
//echo $value."#".$k;
$select_str .='<option selected="selected" value="'.$k.'">'.$v.'</option>';
}else{
$select_str .='<option value="'.$k.'">'.$v.'</option>';
}
}
$select_str .= '</select>';
}
$str .='<p>
<label>'.$label.':</label>
'.$select_str.'
</p>';
}
}
return $str;
}
}
<?php
/**
* FecShop file.
*
* @link http://www.fecshop.com/
* @copyright Copyright (c) 2016 FecShop Software LLC
* @license http://www.fecshop.com/license/
*/
namespace fecshop\models\mysqldb\AdminUser;
use fecshop\models\mysqldb\AdminUser;
/**
* @author Terry Zhao <2358269014@qq.com>
* @since 1.0
*/
class AdminUserForm extends AdminUser {
private $_admin_user;
public function rules()
{
$parent_rules = parent::rules();
$current_rules = [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'validateUsername'],
['username', 'string', 'min' => 2, 'max' => 20],
['email', 'filter', 'filter' => 'trim'],
['code', 'required'],
['code', 'filter', 'filter' => 'trim'],
['code', 'validateCode'],
['person', 'filter', 'filter' => 'trim'],
['password', 'validatePasswordFormat'],
];
return array_merge($parent_rules,$current_rules) ;
}
public function validateUsername($attribute, $params){
if($this->id){
$one = AdminUser::find()->where(" id != ".$this->id." AND username = '".$this->username."' ")
->one();
if($one['id']){
$this->addError($attribute,"this username is exist!");
}
}else{
$one = AdminUser::find()->where(" username = '".$this->username."' ")
->one();
if($one['id']){
$this->addError($attribute,"this username is exist!");
}
}
}
public function validateCode($attribute, $params){
if($this->id){
$one = AdminUser::find()->where(" id != ".$this->id." AND code = '".$this->code."' ")
->one();
if($one['id']){
$this->addError($attribute,"this code is exist!");
}
}else{
$one = AdminUser::find()->where(" code = '".$this->code."' ")
->one();
if($one['id']){
$this->addError($attribute,"this code is exist!");
}
}
}
public function validateEmail($attribute, $params){
if($this->id){
$one = AdminUser::find()->where(" id != ".$this->id." AND email = '".$this->email."' ")
->one();
if($one['id']){
$this->addError($attribute,"this email is exist!");
}
}else{
$one = AdminUser::find()->where(" email = '".$this->email."' ")
->one();
if($one['id']){
$this->addError($attribute,"this email is exist!");
}
}
}
public function validatePasswordFormat($attribute, $params){
if($this->id){
if($this->password && strlen($this->password) <= 6){
$this->addError($attribute,"password must >=6");
}
}else{
if($this->password && strlen($this->password) >= 6){
}else{
$this->addError($attribute,"password must >=6");
}
}
}
public function setPassword($password)
{
if($this->password){
$this->password_hash = \Yii::$app->security->generatePasswordHash($password);
$this->password = '';
}
}
# 重写保存方法
public function save($runValidation = true, $attributeNames = NULL){
if($this->id){
$this->updated_at_datetime = date("Y-m-d H:i:s");
}else{
$this->created_at_datetime = date("Y-m-d H:i:s");
$this->updated_at_datetime = date("Y-m-d H:i:s");
}
# 如果auth_key为空,则重置
if(!$this->auth_key){
$this->generateAuthKey();
}
# 如果access_token为空,则重置
if(!$this->access_token){
$this->generateAccessToken();
}
# 设置password
$this->setPassword($this->password);
parent::save($runValidation,$attributeNames);
}
}
<?php
/*
* FecShop file.
*
* @link http://www.fecshop.com/
* @copyright Copyright (c) 2016 FecShop Software LLC
* @license http://www.fecshop.com/license/
*/
namespace fecshop\services\adminUser;
use Yii;
use fecshop\services\Service;
/**
* AdminUser services. 用来给后台的用户提供数据。
* @author Terry Zhao <2358269014@qq.com>
* @since 1.0
*/
class AdminUser extends Service
{
public $numPerPage = 20;
/**
* language attribute.
*/
protected $_lang_attr = [];
protected $_modelName = '\fecshop\models\mysqldb\AdminUser';
protected $_model;
protected $_userFormModelName = '\fecshop\models\mysqldb\adminUser\AdminUserForm';
protected $_userFormModel;
public function init()
{
parent::init();
list($this->_modelName, $this->_model) = \Yii::mapGet($this->_modelName);
list($this->_userFormModelName, $this->_userFormModel) = \Yii::mapGet($this->_userFormModelName);
}
public function getPrimaryKey()
{
return 'id';
}
public function getActiveStatus(){
$model = $this->_model;
return $model::STATUS_ACTIVE;
}
public function getDeleteStatus(){
$model = $this->_model;
return $model::STATUS_DELETED;
}
public function getByPrimaryKey($primaryKey)
{
if ($primaryKey) {
$one = $this->_model->findOne($primaryKey);
foreach ($this->_lang_attr as $attrName) {
if (isset($one[$attrName])) {
$one[$attrName] = unserialize($one[$attrName]);
}
}
return $one;
} else {
return new $this->_modelName();
}
}
/*
* example filter:
* [
* 'numPerPage' => 20,
* 'pageNum' => 1,
* 'orderBy' => ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
'where' => [
['>','price',1],
['<=','price',10]
* ['sku' => 'uk10001'],
* ],
* 'asArray' => true,
* ]
*/
public function coll($filter = '')
{
$query = $this->_model->find();
$query = Yii::$service->helper->ar->getCollByFilter($query, $filter);
$coll = $query->all();
if (!empty($coll)) {
foreach ($coll as $k => $one) {
foreach ($this->_lang_attr as $attr) {
$one[$attr] = $one[$attr] ? unserialize($one[$attr]) : '';
}
$coll[$k] = $one;
}
}
//var_dump($one);
return [
'coll' => $coll,
'count'=> $query->limit(null)->offset(null)->count(),
];
}
/**
* @param $data array, user form data
* @param $roles array, role id array
* @return boolean
* 保存用户的信息,以及用户的role信息。
*/
public function saveUserAndRole($data, $roles){
$user_id = $this->save($data);
if (!$user_id) {
return false;
}
if (Yii::$service->admin->userRole->saveUserRole($user_id, $roles)) {
return true;
}
return false;
}
/**
* @param $data array, user form data
* @return mix ,return save user id | null
* 保存用户的信息。
*/
public function save($data) {
$primaryKey = $this->getPrimaryKey();
$user_id = 0;
if ($data[$primaryKey]) {
$this->_userFormModel = $this->_userFormModel->findOne($data[$primaryKey]);
}
$this->_userFormModel->attributes = $data;
if (!$data['access_token']) {
$this->_userFormModel->access_token = '';
}
if (!$data['auth_key']) {
$this->_userFormModel->auth_key = '';
}
if ($this->_userFormModel[$primaryKey]) {
if ($this->_userFormModel->validate()) {
$this->_userFormModel->save();
$user_id = $this->_userFormModel[$primaryKey];
} else {
$errors = $this->_userFormModel->errors;
Yii::$service->helper->errors->addByModelErrors($errors);
return null;
}
} else {
if ($this->_userFormModel->validate()) {
$this->_userFormModel->save();
$user_id = Yii::$app->db->getLastInsertID();
} else {
$errors = $this->_userFormModel->errors;
Yii::$service->helper->errors->addByModelErrors($errors);
return null;
}
}
return $user_id;
}
public function removeUserAndRole($ids) {
$removeIds = $this->remove($ids);
if (is_array($removeIds) && !empty($removeIds)) {
Yii::$service->admin->userRole->deleteByUserIds($removeIds);
return true;
} else {
return false;
}
}
public function remove($ids){
if (!$ids) {
Yii::$service->helper->errors->add('remove id is empty');
return null;
}
$removeIds = [];
if (is_array($ids) && !empty($ids)) {
foreach ($ids as $id) {
$model = $this->_model->findOne($id);
if ($model->username !== 'admin') {
$model->delete();
$removeIds[] = $id;
} else {
Yii::$service->helper->errors->add('you can not delete admin user');
}
}
} else {
$id = $ids;
$model = $this->_model->findOne($id);
if ($model->username !== 'admin') {
$model->delete();
$removeIds[] = $id;
} else {
Yii::$service->helper->errors->add('you can not delete admin user');
}
}
return $removeIds;
}
/**
* @property $ids | Int Array
* @return 得到相应用户的数组。
*/
public function getIdAndNameArrByIds($ids)
{
$user_coll = $this->_model->find()
->asArray()
->select(['id', 'username'])
->where([
'in', 'id', $ids,
])->all();
$users = [];
foreach ($user_coll as $one) {
$users[$one['id']] = $one['username'];
}
return $users;
}
}
<?php
/*
* FecShop file.
*
* @link http://www.fecshop.com/
* @copyright Copyright (c) 2016 FecShop Software LLC
* @license http://www.fecshop.com/license/
*/
namespace fecshop\services\adminUser;
use Yii;
use fecshop\services\Service;
/**
* AdminUser services. 用来给后台的用户提供数据。
* @author Terry Zhao <2358269014@qq.com>
* @since 1.0
*/
class UserLogin extends Service
{
protected $_adminUserLoginModelName = '\fecshop\models\mysqldb\adminUser\AdminUserLogin';
protected $_adminUserLoginModel;
public function init()
{
parent::init();
list($this->_adminUserLoginModelName, $this->_adminUserLoginModel) = \Yii::mapGet($this->_adminUserLoginModelName);
}
/**
* @property $data|array
* 数组格式:['username'=>'xxx@xxx.com','password'=>'xxxx']
*/
public function actionLogin($data)
{
$model = new $this->_adminUserLoginModelName();
$model->username = $data['username'];
$model->password = $data['password'];
$loginStatus = $model->login();
$errors = $model->errors;
if (!empty($errors)) {
Yii::$service->helper->errors->addByModelErrors($errors);
}
return $loginStatus;
}
/** Appapi 部分使用的函数
* @param $username | String
* @param $password | String
* Appapi 和 第三方进行数据对接部分的用户登陆验证
*/
public function loginAndGetAccessToken($username, $password)
{
$header = Yii::$app->request->getHeaders();
if (isset($header['access-token']) && $header['access-token']) {
$accessToken = $header['access-token'];
}
// 如果request header中有access-token,则查看这个 access-token 是否有效
if ($accessToken) {
$identity = Yii::$app->user->loginByAccessToken($accessToken);
if ($identity !== null) {
$access_token_created_at = $identity->access_token_created_at;
$timeout = Yii::$service->session->timeout;
if ($access_token_created_at + $timeout > time()) {
return $accessToken;
}
}
}
// 如果上面access-token不存在
$data = [
'username' => $username,
'password' => $password,
];
if ($this->login($data)) {
$identity = Yii::$app->user->identity;
$identity->generateAccessToken();
$identity->access_token_created_at = time();
$identity->save();
$this->setHeaderAccessToken($identity->access_token);
return $identity->access_token;
}
return null;
}
public function setHeaderAccessToken($accessToken)
{
if ($accessToken) {
Yii::$app->response->getHeaders()->set('access-token', $accessToken);
return true;
}
return false;
}
/** AppServer 部分使用的函数
* @property $type | null or Object
* 从request headers中获取access-token,然后执行登录
* 如果登录成功,然后验证时间是否过期
* 如果不过期,则返回identity
* ** 该方法为appserver用户通过access-token验证需要执行的函数。
*/
public function loginByAccessToken($type = null)
{
$header = Yii::$app->request->getHeaders();
if (isset($header['access-token']) && $header['access-token']) {
$accessToken = $header['access-token'];
}
if ($accessToken) {
$identity = Yii::$app->user->loginByAccessToken($accessToken, $type);
if ($identity !== null) {
$access_token_created_at = $identity->access_token_created_at;
$timeout = Yii::$service->session->timeout;
// 如果时间没有过期,则返回identity
if ($access_token_created_at + $timeout > time()) {
//如果时间没有过期,但是快要过期了,在过$updateTimeLimit段时间就要过期,那么更新access_token_created_at。
$updateTimeLimit = Yii::$service->session->updateTimeLimit;
if ($access_token_created_at + $timeout <= (time() + $updateTimeLimit)) {
$identity->access_token_created_at = time();
$identity->save();
}
return $identity;
} else {
$this->logoutByAccessToken();
return false;
}
}
}
}
/**
* 通过accessToek的方式,进行登出从操作。
*/
public function logoutByAccessToken()
{
$userComponent = Yii::$app->user;
$identity = $userComponent->identity;
if ($identity !== null) {
if (!Yii::$app->user->isGuest) {
$identity->access_token = null;
$identity->access_token_created_at = null;
$identity->save();
}
$userComponent->switchIdentity(null);
}
return $userComponent->getIsGuest();
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册