User.php 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Description: 用户
  4. // +----------------------------------------------------------------------
  5. // | Author: Michael_xu | gengxiaoxu@5kcrm.com
  6. // +----------------------------------------------------------------------
  7. namespace app\admin\model;
  8. use think\Db;
  9. use app\admin\model\Common;
  10. use com\verify\HonrayVerify;
  11. use think\Cache;
  12. use think\Request;
  13. class User extends Common
  14. {
  15. /**
  16. * 为了数据库的整洁,同时又不影响Model和Controller的名称
  17. * 我们约定每个模块的数据表都加上相同的前缀,比如CRM模块用crm作为数据表前缀
  18. */
  19. protected $name = 'admin_user';
  20. protected $createTime = 'create_time';
  21. protected $updateTime = false;
  22. protected $autoWriteTimestamp = true;
  23. protected $insert = [
  24. 'status' => 2,
  25. ];
  26. protected $statusArr = ['禁用','启用','未激活'];
  27. protected $dateFormat = 'Y-m-d';
  28. protected $type = [
  29. 'create_time' => 'timestamp',
  30. 'update_time' => 'timestamp',
  31. ];
  32. /**
  33. * 导入字段
  34. *
  35. * @var array
  36. * @author Ymob
  37. * @datetime 2019-10-25 15:35:25
  38. */
  39. public static $import_field_list = [
  40. [
  41. 'field' => 'username',
  42. 'name' => '手机号(登录名)',
  43. 'form_type' => 'mobile',
  44. 'is_null' => 1,
  45. 'is_unique' => 1
  46. ],
  47. [
  48. 'field' => 'password',
  49. 'name' => '密码',
  50. 'form_type' => 'text',
  51. 'is_null' => 1,
  52. ],
  53. [
  54. 'field' => 'realname',
  55. 'name' => '姓名',
  56. 'form_type' => 'text',
  57. 'is_null' => 1,
  58. ],
  59. [
  60. 'field' => 'sex',
  61. 'name' => '性别',
  62. 'form_type' => 'select',
  63. 'setting' => ['男', '女'],
  64. 'is_null' => 0,
  65. ],
  66. [
  67. 'field' => 'email',
  68. 'name' => '邮箱',
  69. 'form_type' => 'email',
  70. 'is_null' => 0,
  71. ],
  72. [
  73. 'field' => 'post',
  74. 'name' => '岗位',
  75. 'form_type' => 'text',
  76. 'is_null' => 0,
  77. ]
  78. ];
  79. /**
  80. * 获取用户所属所有用户组
  81. * @param array $param [description]
  82. */
  83. public function groups()
  84. {
  85. return $this->belongsToMany('group', 'admin_access', 'group_id', 'user_id');
  86. }
  87. public function structureList($structure_id,$str)
  88. {
  89. $str_ids = structureList($structure_id,$str);
  90. return $str_ids;
  91. }
  92. /**
  93. * [getDataList 列表]
  94. * @AuthorHTL
  95. * @param [string] $map [查询条件]
  96. * @param [number] $page [当前页数]
  97. * @param [number] $limit [每页数量]
  98. * @return [description]
  99. */
  100. public function getDataList($request)
  101. {
  102. $request = $this->fmtRequest( $request );
  103. $fieldarray = ['search','group_id','structure_id','status','type','page','limit','pageType'];
  104. $map = $request['map'] ? : [];
  105. if (isset($map['search']) && $map['search']) {
  106. $map['user.username|user.realname'] = ['like', '%'.$map['search'].'%'];
  107. }
  108. unset($map['search']);
  109. //角色员工
  110. if ($map['group_id']) {
  111. $group_user_ids = db('admin_access')->where(['group_id' => $map['group_id']])->column('user_id');
  112. if ($map['group_id'] == 1 && !$group_user_ids) {
  113. $group_user_ids = ['1'];
  114. }
  115. $map['user.id'] = array('in',$group_user_ids);
  116. }
  117. $exp = new \think\db\Expression('field(user.status,1,2,0)');
  118. // 默认除去超级管理员
  119. // $map['user.id'] = array('neq', 1);
  120. if($map['structure_id']){
  121. //获取部门下员工列表
  122. $str_ids = structureList($map['structure_id'],'');
  123. $new_str_ids = rtrim($str_ids,',');
  124. $map['user.structure_id'] = ['in',$new_str_ids]; //$map['structure_id'];
  125. }
  126. unset($map['structure_id']);
  127. if ($map['status'] || $map['group_id']) {
  128. if ($map['status'] != 3) {
  129. $map['user.status'] = ($map['status'] !== 'all') ? ($map['status'] ? : ['gt',0]) : ['egt',0];
  130. } else {
  131. $map['user.create_time'] = ['gt', time() - 86400 * 7];
  132. }
  133. } else {
  134. $map['user.status'] = 0;
  135. }
  136. unset($map['status']);
  137. $map['user.type'] = 1;
  138. if(isset($map['type'])) $map['user.type'] == ($map['type'] == '0') ? 0 : 1;
  139. //过滤字段
  140. foreach($fieldarray as $value){
  141. unset($map[$value]);
  142. }
  143. //获取列表
  144. $dataCount = db('admin_user')
  145. ->alias('user')
  146. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  147. // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
  148. ->where($map)
  149. ->count();
  150. $list = db('admin_user')
  151. ->alias('user')
  152. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  153. // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
  154. ->limit(($request['page']-1)*$request['limit'], $request['limit'])
  155. ->where($map)
  156. ->field('user.id,user.username,user.img,user.thumb_img,user.realname,user.num,user.email,user.mobile,user.sex,user.structure_id,user.post,user.status,user.parent_id,user.type,user.create_time,structure.name as s_name')
  157. ->order($exp)
  158. ->order('user.id asc')
  159. ->select();
  160. foreach ($list as $k=>$v) {
  161. //直属上级
  162. $list[$k]['status_name'] = $v['status']=='1'?'启用':'禁用';
  163. $parentInfo = [];
  164. $parentInfo = $this->getUserById($v['parent_id']);
  165. $list[$k]['parent_name'] = $v['parent_id'] ? $parentInfo['realname'] : '';
  166. $list[$k]['status_name'] = $v['status'] ? $this->statusArr[$v['status']] : '停用';
  167. //角色
  168. $groupsArr = $this->get($v['id'])->groups;
  169. $groups = [];
  170. $groupids = [];
  171. foreach ($groupsArr as $key=>$val) {
  172. $groups[] = $val['title'];
  173. $groupids[] = $val['id'];
  174. }
  175. $list[$k]['groups'] = $groups ? implode(',',$groups) : '';
  176. $list[$k]['groupids'] = $groupids ? implode(',',$groupids) : '';
  177. $list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : '';
  178. $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
  179. $list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
  180. }
  181. $data = [];
  182. $data['list'] = $list;
  183. $data['dataCount'] = $dataCount;
  184. return $data;
  185. }
  186. /*
  187. *根据字符串展示参与人 use by work
  188. */
  189. public function getDataByStr($idstr)
  190. {
  191. $idArr = stringToArray($idstr);
  192. if (!$idArr) {
  193. return [];
  194. }
  195. $list = $this->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select();
  196. foreach($list as $key=>$value){
  197. $list[$key]['thumb_img'] = $value['thumb_img']?getFullPath($value['thumb_img']):'';
  198. }
  199. return $list;
  200. }
  201. /**
  202. * [getDataById 根据主键获取详情]
  203. * @param string $id [主键]
  204. * @return
  205. */
  206. public function getDataById($id = '')
  207. {
  208. $data = Db::name('AdminUser')->find($id);
  209. if (!$data) {
  210. $this->error = '暂无此数据';
  211. return false;
  212. }
  213. unset($data['password']);
  214. unset($data['authkey']);
  215. if($data['structure_id']) {
  216. $structureDet = Db::name('AdminStructure')->field('id,name')->where('id = '.$data['structure_id'].'')->find();
  217. $data['structure_name'] = $structureDet['name'];
  218. } else {
  219. $data['structure_name'] = '暂无';
  220. }
  221. if($data['parent_id']) {
  222. $parentDet = Db::name('AdminUser')->field('id,realname')->where('id = '.$data['parent_id'].'')->find();
  223. $data['parent_name'] = $parentDet['realname'];
  224. } else {
  225. $data['parent_name'] = '暂无';
  226. }
  227. $data['thumb_img'] = getFullPath($data['thumb_img']);
  228. $data['img'] = getFullPath($data['img']);
  229. //$data['groups'] = $this->get($id)->groups();
  230. return $data;
  231. }
  232. /**
  233. * 创建用户
  234. * @param array $param [description]
  235. */
  236. public function createData($param)
  237. {
  238. // 非导入数据
  239. if (request()->action() == 'import') {
  240. $temp = [];
  241. foreach (self::$import_field_list as $key => $val) {
  242. $temp[$val['field']] = $param[$val['field']];
  243. }
  244. $param = $temp;
  245. $param['structure_id'] = 0;
  246. } else {
  247. if (empty($param['group_id']) || !is_array($param['group_id'])) {
  248. $this->error = '请至少勾选一个用户组';
  249. return false;
  250. }
  251. }
  252. // 验证
  253. $validate = validate($this->name);
  254. if (!$validate->check($param)) {
  255. $this->error = $validate->getError();
  256. return false;
  257. }
  258. $syncModel = new \app\admin\model\Sync();
  259. $this->startTrans();
  260. try {
  261. $salt = substr(md5(time()),0,4);
  262. $param['salt'] = $salt;
  263. if (!$param['password']) {
  264. $password = $param['username'];
  265. } else {
  266. $password = $param['password'];
  267. }
  268. $param['password'] = user_md5($password, $salt, $param['username']);
  269. $param['type'] = 1;
  270. $param['mobile'] = $param['username'];
  271. $this->data($param)->allowField(true)->isUpdate(false)->save();
  272. $user_id = (int) $this->getLastInsId();
  273. //员工档案
  274. $data['user_id'] = $param['user_id'];
  275. unset($param['user_id']);
  276. $data['user_id'] = $user_id;
  277. $data['mobile'] = $param['username'];
  278. $data['email'] = $param['email'] ? : '';
  279. $data['sex'] = $param['sex'] ? : '';
  280. $data['create_time'] = time();
  281. Db::name('HrmUserDet')->insert($data);
  282. $userGroups = [];
  283. foreach ($param['group_id'] as $k => $v) {
  284. $userGroup['user_id'] = $user_id;
  285. $userGroup['group_id'] = $v;
  286. $userGroups[] = $userGroup;
  287. }
  288. if ($userGroups) {
  289. Db::name('admin_access')->insertAll($userGroups);
  290. }
  291. $this->commit();
  292. $param['user_id'] = $data['user_id'];
  293. $resSync = $syncModel->syncData($param);
  294. return true;
  295. } catch(\Exception $e) {
  296. $this->rollback();
  297. $this->error = '添加失败';
  298. return false;
  299. }
  300. }
  301. //导入成为正式用户
  302. public function beusers($request)
  303. {
  304. if ($request['userlist']&&is_array($request['userlist'])) {
  305. $flag = true;
  306. foreach ($request['userlist'] as $value) {
  307. $userInfo = Db::name('AdminUser')->where('id = '.$value.'')->find();
  308. $userDet = Db::name('HrmUserDet')->where('user_id = '.$value.'')->find();
  309. $temp['status'] = 1;
  310. $temp['type'] = 1;
  311. $temp['username'] = $userDet['mobile'];
  312. $salt = substr(md5(time()),0,4);
  313. $temp['salt'] = $salt;
  314. $password = $userDet['mobile'];
  315. $temp['password'] = user_md5($password, $salt, $temp['username']);
  316. $flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
  317. }
  318. if ($flag) {
  319. return true;
  320. } else {
  321. $this->error = '操作失败';
  322. return false;
  323. }
  324. } else {
  325. $this->error = '参数错误';
  326. return false;
  327. }
  328. }
  329. /**
  330. * 通过id修改用户
  331. * @param array
  332. */
  333. public function updateDataById($param, $id)
  334. {
  335. if ($param['user_id']) {
  336. //修改个人信息
  337. $data['email'] = $param['email'];
  338. $data['sex'] = $param['sex'];
  339. // $data['mobile'] = $param['username'];
  340. if (db('admin_user')->where(['username' => $param['username'],'id' => ['neq',$param['user_id']]])->find()) {
  341. $this->error = '手机号已存在';
  342. return false;
  343. }
  344. Db::name('HrmUserDet')->where(['user_id' => $param['user_id']])->update($data);
  345. $data['realname'] = $param['realname'];
  346. $data['post'] = $param['post'];
  347. $flag = $this->where(['id' => $param['user_id']])->update($data);
  348. if ($flag==0 || $flag==1) {
  349. return true;
  350. } else {
  351. $this->error = '保存失败';
  352. return false;
  353. }
  354. } else {
  355. // 不能操作超级管理员
  356. // if ($id == 1) {
  357. // $this->error = '非法操作';
  358. // return false;
  359. // }
  360. $checkData = $this->get($id);
  361. $userInfo = $checkData->data;
  362. if (!$checkData) {
  363. $this->error = '暂无此数据';
  364. return false;
  365. }
  366. if (request()->action() != 'import') {
  367. if (empty($param['group_id'])) {
  368. $this->error = '请至少勾选一个用户组';
  369. return false;
  370. }
  371. }
  372. $subUserId = getSubUserId(true, 0, $id);
  373. if ((int)$param['parent_id'] == (int)$id) {
  374. $this->error = '直属上级不能是自己';
  375. return false;
  376. }
  377. if ((int)$param['parent_id'] !== 1 && in_array($param['parent_id'],$subUserId)) {
  378. $this->error = '直属上级不能是自己或下属';
  379. return false;
  380. }
  381. if (db('admin_user')->where(['id' => ['neq',$id],'username' => $param['username']])->find()) {
  382. $this->error = '手机号已存在';
  383. return false;
  384. }
  385. $this->startTrans();
  386. try {
  387. $accessModel = model('Access');
  388. if ($param['group_id']) {
  389. //角色员工关系处理
  390. $accessModel->userGroup($id, $param['group_id'], 'update');
  391. }
  392. if (!empty($param['password'])) {
  393. $salt = $userInfo['salt'];
  394. $param['password'] = user_md5($param['password'], $salt, $param['username']);
  395. }
  396. $this->allowField(true)->save($param, ['id' => $id]);
  397. $this->commit();
  398. Cache::rm('user_info' . $id);
  399. // $data['mobile'] = $param['username'];
  400. $data['email'] = $param['email'];
  401. $data['sex'] = $param['sex'];
  402. $data['update_time'] = time();
  403. $flagg = Db::name('HrmUserDet')->where('user_id = '.$id)->update($data);
  404. return true;
  405. } catch(\Exception $e) {
  406. $this->rollback();
  407. $this->error = '编辑失败';
  408. return false;
  409. }
  410. }
  411. }
  412. /**
  413. * [login 登录]
  414. * @AuthorHTL
  415. * @DateTime
  416. * @param [string] $u_username [账号]
  417. * @param [string] $u_pwd [密码]
  418. * @param [string] $verifyCode [验证码]
  419. * @param Boolean $isRemember [是否记住密码]
  420. * @param Boolean $type [是否重复登录]
  421. * @param array $paramArr
  422. * @return [type] [description]
  423. */
  424. public function login($username, $password, $verifyCode = '', $isRemember = false, $type = false, $authKey = '', $paramArr = [])
  425. {
  426. if ($paramArr['dingCode']) {
  427. $dingtalkModel = new \app\admin\model\Dingtalk();
  428. $username = $dingtalkModel->sign($paramArr['dingCode']);
  429. if (!$username) {
  430. $this->error = $dingtalkModel->getError();;
  431. return false;
  432. }
  433. } else {
  434. if (!$password){
  435. $this->error = '密码不能为空';
  436. return false;
  437. }
  438. }
  439. if (config('IDENTIFYING_CODE') && !$type) {
  440. if (!$verifyCode) {
  441. $this->error = '验证码不能为空';
  442. return false;
  443. }
  444. $captcha = new HonrayVerify(config('captcha'));
  445. if (!$captcha->check($verifyCode)) {
  446. $this->error = '验证码错误';
  447. return false;
  448. }
  449. }
  450. $map['username'] = $username;
  451. $map['type'] = 1;
  452. $userInfo = $this->where($map)->find();
  453. if (!$userInfo) {
  454. $this->error = '帐号不存在';
  455. return false;
  456. }
  457. // 登录记录
  458. $login_record = new LoginRecord();
  459. $login_record->user_id = $userInfo['id'];
  460. // 三次出错,十五分钟禁止登录
  461. if (!$login_record->verify()) {
  462. $this->error = $login_record->error;
  463. return false;
  464. }
  465. $userInfo['thumb_img'] = $userInfo['thumb_img'] ? getFullPath($userInfo['thumb_img']) : '';
  466. if (user_md5($password, $userInfo['salt'], $userInfo['username']) !== $userInfo['password'] && !$paramArr['dingCode']) {
  467. $this->error = '账号或密码错误!';
  468. $login_record->createRecord(LoginRecord::TYPE_PWD_ERROR);
  469. return false;
  470. }
  471. if ($userInfo['status'] === 0) {
  472. $this->error = '帐号已被禁用';
  473. $login_record->createRecord(LoginRecord::TYPE_USER_BANNED);
  474. return false;
  475. }
  476. $login_record->createRecord(LoginRecord::TYPE_SUCCESS);
  477. // 获取菜单和权限
  478. $dataList = $this->getMenuAndRule($userInfo['id']);
  479. if ($isRemember || $type) {
  480. $secret['username'] = $username;
  481. $secret['password'] = $password;
  482. $data['rememberKey'] = encrypt($secret);
  483. }
  484. //登录有效时间
  485. $cacheConfig = config('cache');
  486. $loginExpire = $cacheConfig['expire'] ? : 86400*3;
  487. // 保存缓存
  488. session_start();
  489. $info['userInfo'] = $userInfo;
  490. $info['sessionId'] = session_id();
  491. $authKey = user_md5($userInfo['username'].$userInfo['password'].$info['sessionId'], $userInfo['salt']);
  492. // $info['_AUTH_LIST_'] = $dataList['rulesList'];
  493. $info['authKey'] = $authKey;
  494. $platform = $paramArr['platform'] ? '_'.$paramArr['platform'] : ''; //请求平台(mobile,ding)
  495. //删除旧缓存
  496. if (cache('Auth_'.$userInfo['authkey'].$platform)) {
  497. cache('Auth_'.$userInfo['authkey'].$platform, NULL);
  498. }
  499. cache('Auth_'.$authKey.$platform, $info, $loginExpire, 'UserToken');
  500. unset($userInfo['authkey']);
  501. // 返回信息
  502. $data['authKey'] = $authKey;
  503. $data['sessionId'] = $info['sessionId'];
  504. $data['userInfo'] = $userInfo;
  505. $data['authList'] = $dataList['authList'];
  506. $data['menusList'] = $dataList['menusList'];
  507. $data['loginExpire'] = $loginExpire;
  508. //保存authKey信息
  509. $userData = [];
  510. $userData['authkey'] = $authKey;
  511. $userData['authkey_time'] = time()+$loginExpire;
  512. //把状态未激活至为启用
  513. if ($userInfo['status'] == 2) {
  514. $userData['status'] = 1;
  515. }
  516. $this->where(['id' => $userInfo['id']])->update($userData);
  517. return $data;
  518. }
  519. /**
  520. * 修改密码
  521. * @param array $param [description]
  522. */
  523. public function updatePaw($userInfo, $old_pwd, $new_pwd)
  524. {
  525. if (!$old_pwd) {
  526. $this->error = '请输入旧密码';
  527. return false;
  528. }
  529. if (!$new_pwd) {
  530. $this->error = '请输入新密码';
  531. return false;
  532. }
  533. if ($new_pwd == $old_pwd) {
  534. $this->error = '新旧密码不能一致';
  535. return false;
  536. }
  537. //登录有效时间
  538. $cacheConfig = config('cache');
  539. $loginExpire = $cacheConfig['expire'] ? : '86400*3';
  540. $password = $this->where('id', $userInfo['id'])->value('password');
  541. if (user_md5($old_pwd, $userInfo['salt'], $userInfo['username']) != $password) {
  542. $this->error = '原密码错误';
  543. return false;
  544. }
  545. if (user_md5($new_pwd, $userInfo['salt'], $userInfo['username']) == $password) {
  546. $this->error = '密码没改变';
  547. return false;
  548. }
  549. if ($this->where('id', $userInfo['id'])->setField('password', user_md5($new_pwd, $userInfo['salt'], $userInfo['username']))) {
  550. $syncData = [];
  551. $syncModel = new \app\admin\model\Sync();
  552. $syncData['user_id'] = $userInfo['id'];
  553. $syncData['salt'] = $userInfo['salt'];
  554. $syncData['password'] = user_md5($new_pwd, $userInfo['salt'], $userInfo['username']);
  555. $resSync = $syncModel->syncData($syncData);
  556. $userInfo = $this->where('id', $userInfo['id'])->find();
  557. // 重新设置缓存
  558. session_start();
  559. $cache['userInfo'] = $userInfo;
  560. $cache['authKey'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
  561. cache('Auth_'.$auth_key, null);
  562. cache('Auth_'.$cache['authKey'], $cache, $loginExpire);
  563. return $cache['authKey'];//把auth_key传回给前端
  564. }
  565. $this->error = '修改失败';
  566. return false;
  567. }
  568. //根据IDs批量设置密码
  569. public function updatePwdById($param)
  570. {
  571. $syncModel = new \app\admin\model\Sync();
  572. $flag = true;
  573. foreach ($param['id'] as $value) {
  574. $password = '';
  575. $userInfo = db('admin_user')->where(['id' => $value])->find();;
  576. $salt = substr(md5(time()),0,4);
  577. $temp['salt'] = $salt;
  578. $temp['password']= $password = user_md5($param['password'], $salt, $userInfo['username']);
  579. $flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
  580. $syncData = [];
  581. $syncData['user_id'] = $value;
  582. $syncData['salt'] = $salt;
  583. $syncData['password'] = $password;
  584. $resSync = $syncModel->syncData($syncData);
  585. }
  586. if ($flag) {
  587. return $flag;
  588. } else {
  589. $this->error ='修改失败,请稍后重试';
  590. return false;
  591. }
  592. }
  593. /**
  594. * 获取菜单和权限 protected
  595. *
  596. * @param $u_id
  597. * @return array
  598. * @throws \think\db\exception\DataNotFoundException
  599. * @throws \think\db\exception\ModelNotFoundException
  600. * @throws \think\exception\DbException
  601. */
  602. public function getMenuAndRule($u_id)
  603. {
  604. $menusList = [];
  605. $ruleMap = [];
  606. $adminTypes = adminGroupTypes($u_id);
  607. if (in_array(1,$adminTypes)) {
  608. $map['status'] = 1;
  609. $menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select();
  610. } else {
  611. $groups = $this->get($u_id)->groups;
  612. $ruleIds = [];
  613. foreach ($groups as $k => $v) {
  614. if (stringToArray($v['rules'])) {
  615. $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
  616. }
  617. }
  618. $ruleIds = array_unique($ruleIds);
  619. $ruleMap['id'] = array('in', $ruleIds);
  620. $ruleMap['status'] = 1;
  621. }
  622. $newRuleIds = [];
  623. // 重新设置ruleIds,除去部分已删除或禁用的权限。
  624. $rules = Db::name('admin_rule')->where($ruleMap)->select();
  625. // $ruless = Db::name('admin_rule')->where($ruleMap)->where(['level'=>2,'pid'=>0])->column('name');
  626. foreach ($rules as $k => $v) {
  627. $newRuleIds[] = $v['id'];
  628. $rules[$k]['name'] = strtolower($v['name']);
  629. }
  630. //菜单管理(弃用)
  631. // $menuMap['status'] = 1;
  632. // $menuMap['rule_id'] = array('in',$newRuleIds);
  633. // $menusList = Db::name('admin_menu')->where($menuMap)->order('sort asc')->select();
  634. $ret = [];
  635. //处理菜单成树状
  636. $tree = new \com\Tree();
  637. //处理规则成树状
  638. $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
  639. //权限数组
  640. $authList = rulesListToArray($rulesList, $newRuleIds);
  641. //应用控制
  642. $adminConfig = db('admin_config')->where(['pid' => 0,'status' => 1])->column('module');
  643. $adminConfig = $adminConfig ? array_merge($adminConfig,['bi','admin']) : ['bi','admin'];
  644. # 通讯录
  645. if (in_array('book', $adminConfig) && !empty($authList['oa']['addresslist']['index'])) {
  646. $authList['oa']['book']['index'] = true;
  647. }
  648. # 商业智能权限细化
  649. if ($authList['bi']) {
  650. if (!in_array('taskExamine',$adminConfig) && !in_array('crm',$adminConfig)) {
  651. unset($authList['bi']);
  652. } else {
  653. foreach ($authList['bi'] as $key=>$val) {
  654. if (!in_array('taskExamine',$adminConfig)) {
  655. unset($authList['bi']['oa']);
  656. }
  657. if (!in_array('crm',$adminConfig)) {
  658. unset($authList['bi']['customer']);
  659. unset($authList['bi']['business']);
  660. unset($authList['bi']['product']);
  661. unset($authList['bi']['achievement']);
  662. unset($authList['bi']['contract']);
  663. unset($authList['bi']['portrait']);
  664. unset($authList['bi']['ranking']);
  665. }
  666. }
  667. }
  668. } else {
  669. unset($authList['bi']);
  670. }
  671. # 任务审批
  672. if (in_array('taskExamine', $adminConfig) && !$authList['oa']) {
  673. $oaAuth = ['announcement' => ['read' => true]];
  674. $authList['oa'] = $oaAuth;
  675. $authList['oa']['taskExamine'] = (Object)[];
  676. } else {
  677. $authList['oa'] = $authList['oa'];
  678. $authList['oa']['taskExamine'] = (Object)[];
  679. }
  680. # 项目
  681. if (in_array('work', $adminConfig) && !$authList['work']) {
  682. $oaAuth = ['work' => 'read'];
  683. $authList['work'] = $oaAuth;
  684. } else {
  685. $authList['work'] = $authList['work'];
  686. }
  687. # 日志
  688. if (in_array('log', $adminConfig)) {
  689. $authList['oa']['log'] = (Object)[];
  690. }
  691. # 日历
  692. if (in_array('calendar', $adminConfig)) {
  693. $authList['oa']['calendar'] = (Object)[];
  694. }
  695. $ret['authList'] = $this->resetAuthorityFiled($authList);
  696. $res['manage']=$rules;
  697. return $ret;
  698. }
  699. /**
  700. * todo 应前端要求修改部分权限字段,与java的权限字段保持一致。
  701. *
  702. * @param $authList
  703. * @return mixed
  704. */
  705. private function resetAuthorityFiled($authList)
  706. {
  707. # 客户
  708. if (isset($authList['crm']['customer']['deal_status'])) {
  709. $authList['crm']['customer']['dealStatus'] = $authList['crm']['customer']['deal_status'];
  710. unset($authList['crm']['customer']['deal_status']);
  711. }
  712. if (isset($authList['crm']['customer']['nearby'])) {
  713. $authList['crm']['customer']['nearbyCustomer'] = $authList['crm']['customer']['nearby'];
  714. unset($authList['crm']['customer']['nearby']);
  715. }
  716. # 跟进记录
  717. $authList['crm']['followRecord'] = $authList['crm']['activity'];
  718. # 公海
  719. if (isset($authList['crm']['customer']['pool'])) {
  720. $authList['crm']['pool']['index'] = $authList['crm']['customer']['pool'] ? true : false;
  721. }
  722. if (isset($authList['crm']['customer']['distribute'])) {
  723. $authList['crm']['pool']['distribute'] = $authList['crm']['customer']['distribute'] ? true : false;
  724. }
  725. if (isset($authList['crm']['customer']['receive'])) {
  726. $authList['crm']['pool']['receive'] = $authList['crm']['customer']['receive'] ? true : false;
  727. }
  728. if (isset($authList['crm']['customer']['poolexcelexport'])) {
  729. $authList['crm']['pool']['excelexport'] = $authList['crm']['customer']['poolexcelexport'] ? true : false;
  730. }
  731. if (isset($authList['crm']['customer']['pooldelete'])) {
  732. $authList['crm']['pool']['delete'] = $authList['crm']['customer']['pooldelete'] ? true : false;
  733. }
  734. # 合同
  735. if (isset($authList['crm']['contract']['discard'])) {
  736. $authList['crm']['contract']['discard'] = false;
  737. }
  738. # 发票
  739. if (isset($authList['crm']['invoice']['setinvoice'])) {
  740. $authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice'];
  741. }
  742. # 发票抬头权限
  743. if (!empty($authList['crm']['invoice']['index'])) {
  744. $authList['crm']['invoiceTitle']['index'] = true;
  745. }
  746. // else {
  747. // $authList['crm']['invoice']['updateInvoiceStatus'] = false;
  748. // }
  749. # project
  750. if (!empty($authList['work']['work']['update']) || !empty($authList['work']['work']['save'])) {
  751. $authList['project']['projectLabelManage']['projectLabelAdd'] = true;
  752. $authList['project']['projectLabelManage']['projectLabelDelete'] = true;
  753. $authList['project']['projectLabelManage']['projectLabelUpdate'] = true;
  754. $authList['project']['projectManage']['save'] = true;
  755. }
  756. // else {
  757. // $authList['project']['projectLabelManage']['projectLabelAdd'] = false;
  758. // $authList['project']['projectLabelManage']['projectLabelDelete'] = false;
  759. // $authList['project']['projectLabelManage']['projectLabelUpdate'] = false;
  760. // $authList['project']['projectManage']['save'] = false;
  761. // }
  762. # 项目
  763. $projectRules = Db::name('admin_rule')->where(['types' => 3, 'level' => 4, 'status' => 0])->column('name');
  764. if (!empty($authList['project']['projectManage']['save'])) {
  765. foreach ($projectRules AS $key => $value) $authList['work']['project'][$value] = true;
  766. } else {
  767. $authList['work'] = [];
  768. }
  769. unset($authList['work']['work']);
  770. unset($authList['work']['task']);
  771. unset($authList['work']['taskclass']);
  772. # 跟进记录
  773. if (!empty($authList['crm']['record']['index'])) {
  774. $authList['crm']['followRecord']['delete'] = true;
  775. $authList['crm']['followRecord']['read'] = true;
  776. $authList['crm']['followRecord']['save'] = true;
  777. $authList['crm']['followRecord']['update'] = true;
  778. }
  779. unset($authList['crm']['record']);
  780. # admin:system
  781. if (!empty($authList['admin']['system']['index'])) {
  782. $authList['admin']['system']['read'] = $authList['admin']['system']['index'];
  783. unset($authList['admin']['system']['index']);
  784. }
  785. if (!empty($authList['admin']['system']['save'])) {
  786. $authList['admin']['system']['update'] = $authList['admin']['system']['save'];
  787. }
  788. # admin:configSet
  789. if (!empty($authList['admin']['configset']['index'])) {
  790. $authList['admin']['configSet']['read'] = $authList['admin']['configset']['index'];
  791. }
  792. if (!empty($authList['admin']['configset']['update'])) {
  793. $authList['admin']['configSet']['update'] = $authList['admin']['configset']['update'];
  794. }
  795. unset($authList['admin']['configset']);
  796. # admin:users
  797. if (!empty($authList['admin']['users']['index'])) {
  798. $authList['admin']['users']['read'] = $authList['admin']['users']['index'];
  799. unset($authList['admin']['users']['index']);
  800. }
  801. if (!empty($authList['admin']['users']['enables'])) {
  802. $authList['admin']['users']['userEnables'] = $authList['admin']['users']['enables'];
  803. unset($authList['admin']['users']['enables']);
  804. }
  805. if (!empty($authList['admin']['users']['save'])) {
  806. $authList['admin']['users']['userSave'] = $authList['admin']['users']['save'];
  807. unset($authList['admin']['users']['save']);
  808. }
  809. if (!empty($authList['admin']['users']['update'])) {
  810. $authList['admin']['users']['userUpdate'] = $authList['admin']['users']['update'];
  811. unset($authList['admin']['users']['update']);
  812. }
  813. if (!empty($authList['admin']['users']['structures_save'])) {
  814. $authList['admin']['users']['deptSave'] = $authList['admin']['users']['structures_save'];
  815. unset($authList['admin']['users']['structures_save']);
  816. }
  817. if (!empty($authList['admin']['users']['structures_update'])) {
  818. $authList['admin']['users']['deptUpdate'] = $authList['admin']['users']['structures_update'];
  819. unset($authList['admin']['users']['structures_update']);
  820. }
  821. if (!empty($authList['admin']['users']['structures_delete'])) {
  822. $authList['admin']['users']['deptDelete'] = $authList['admin']['users']['structures_delete'];
  823. unset($authList['admin']['users']['structures_delete']);
  824. }
  825. # admin:group 角色权限管理
  826. if (!empty($authList['admin']['groups'])) {
  827. $authList['admin']['permission'] = $authList['admin']['groups'];
  828. unset($authList['admin']['groups']);
  829. }
  830. # admin:examine_flow
  831. if (!empty($authList['admin']['examine_flow'])) {
  832. $authList['admin']['examineFlow'] = $authList['admin']['examine_flow'];
  833. unset($authList['admin']['examine_flow']);
  834. }
  835. # admin:printing
  836. if (!empty($authList['admin']['printing'])) {
  837. $authList['admin']['print'] = $authList['admin']['printing'];
  838. unset($authList['admin']['printing']);
  839. }
  840. # admin:work
  841. if (!empty($authList['admin']['work']['work'])) {
  842. $authList['admin']['work']['update'] = $authList['admin']['work']['work'];
  843. unset($authList['admin']['work']['work']);
  844. }
  845. # admin:log
  846. unset($authList['admin']['loginrecord']);
  847. unset($authList['admin']['log']);
  848. # admin:initialize
  849. if (!empty($authList['admin']['initialize'])) {
  850. $authList['admin']['init']['initData'] = $authList['admin']['initialize']['update'];
  851. $authList['admin']['init']['index'] = $authList['admin']['initialize']['index'];
  852. unset($authList['admin']['initialize']);
  853. }
  854. # admin
  855. if (!empty($authList['admin'])) {
  856. $authList['manage'] = $authList['admin'];
  857. $adminAuth = [
  858. 'configSet.read', 'crm.achievement', 'crm.field', 'crm.pool', 'crm.setting',
  859. 'examineFlow.index', 'init.initData', 'oa.examine', 'system.read', 'users.read',
  860. 'work.update','permission.update'
  861. ];
  862. foreach ($authList['manage'] AS $key1 => $value1) {
  863. foreach ($value1 AS $key2 => $value2) {
  864. if (in_array($key1.'.'.$key2, $adminAuth)) {
  865. $authList['manage']['other_rule'] = [
  866. 'setwelcome' => true,
  867. 'setworklogrule' => true,
  868. 'welcome' => true,
  869. 'worklogrule' => true
  870. ];
  871. }
  872. }
  873. }
  874. }
  875. if (empty($authList['manage']['other_rule'])) unset($authList['manage']);
  876. unset($authList['admin']);
  877. # 通讯录
  878. $authList['email'] = (Object)[];
  879. $authList['hrm'] = (Object)[];
  880. $authList['jxc'] = (Object)[];
  881. $authList['knowledge'] = (Object)[];
  882. $authList['crm']['receivables']['excelexport'] = false;
  883. return $authList;
  884. }
  885. /**
  886. * 获取权限结构数组
  887. * @param
  888. */
  889. public function getRulesList($uid)
  890. {
  891. $ruleMap = [];
  892. $adminTypes = adminGroupTypes($uid);
  893. if (in_array(1,$adminTypes)) {
  894. $map['status'] = 1;
  895. } else {
  896. $groups = $this->get($uid)->groups;
  897. $ruleIds = [];
  898. foreach($groups as $k => $v) {
  899. if (stringToArray($v['rules'])) {
  900. $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
  901. }
  902. }
  903. $ruleIds = array_unique($ruleIds);
  904. $ruleMap['id'] = array('in', $ruleIds);
  905. $ruleMap['status'] = 1;
  906. }
  907. $newRuleIds = [];
  908. // 重新设置ruleIds,除去部分已删除或禁用的权限。
  909. $rules = Db::name('admin_rule')->where($ruleMap)->select();
  910. foreach ($rules as $k => $v) {
  911. $newRuleIds[] = $v['id'];
  912. $rules[$k]['name'] = strtolower($v['name']);
  913. }
  914. //处理规则成树状
  915. $tree = new \com\Tree();
  916. $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
  917. $rulesList = rulesDeal($rulesList);
  918. return $rulesList ? : [];
  919. }
  920. /**
  921. * 获取用户所属角色(用户组)
  922. * @param
  923. */
  924. public function getGroupTypeByAction($uid, $m, $c, $a)
  925. {
  926. //根据$m,$c,$a 获取对应的$a 的rule_id
  927. $rulesList = $this->getRulesList($uid);
  928. if (!in_array($m.'-'.$c.'-'.$a, $rulesList)) {
  929. return false;
  930. }
  931. $mRuleId = db('admin_rule')->where(['name'=>$m,'level'=>1])->value('id');
  932. $cRuleId = db('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id');
  933. $aRuleId = db('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id');
  934. //获取用户组
  935. $groups = $this->get($uid)->groups;
  936. if (!$groups) {
  937. return false;
  938. }
  939. $groupTypes = [];
  940. foreach ($groups as $g) {
  941. if (in_array($aRuleId, explode(',', trim($g['rules'], ',')))) {
  942. $groupTypes[] = $g['type'];
  943. }
  944. }
  945. return $groupTypes ? : [];
  946. }
  947. /**
  948. * 获取有此权限的角色
  949. * @param
  950. */
  951. public function getAllUserByAction($m, $c, $a)
  952. {
  953. $mRuleId = db('admin_rule')->where(['name'=>$m,'level'=>1])->value('id');
  954. $cRuleId = db('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id');
  955. $aRuleId = db('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id');
  956. $groups = db('admin_group')->where(['rules' => ['in',$aRuleId]])->column('id');
  957. $userIds = db('admin_access')->where(['group_id' => ['in',$groups]])->column('user_id');
  958. if (!$userIds) {
  959. //查询管理员
  960. $userIds = db('admin_user')->where(['id' => 1])->column('id');
  961. }
  962. return $userIds;
  963. }
  964. /**
  965. * 根据部门获取部门的userId
  966. * @param $strId 部门ID
  967. * @param $type 2时包含所有下属部门
  968. */
  969. public function getSubUserByStr($structure_id, $type = 1)
  970. {
  971. $allStrIds = (array) $structure_id;
  972. if ($type == 2) {
  973. $structureModel = new \app\admin\model\Structure();
  974. foreach ($allStrIds as $v) {
  975. $allSubStrIds = [];
  976. $allSubStrIds = $structureModel->getAllChild($v);
  977. if ($allSubStrIds) {
  978. $allStrIds = array_merge($allStrIds, $allSubStrIds); //全部关联部门(包含下属部门)
  979. }
  980. }
  981. }
  982. $userIds = db('admin_user')->where(['structure_id' => ['in',$allStrIds]])->column('id');
  983. return $userIds ? : [];
  984. }
  985. /**
  986. * [getUserById 根据主键获取详情]
  987. * @param
  988. * @return
  989. */
  990. public function getUserById($id = '')
  991. {
  992. $data = Db::name('AdminUser')
  993. ->alias('user')
  994. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  995. ->where(['user.id' => $id])
  996. ->field([
  997. 'user.id',
  998. 'username',
  999. 'img',
  1000. 'thumb_img',
  1001. 'realname',
  1002. 'parent_id',
  1003. 'structure.name' => 'structure_name',
  1004. 'structure.id' => 'structure_id'
  1005. ])
  1006. ->cache('user_info' . $id, null, 'user_info')
  1007. ->find();
  1008. $data['img'] = $data['img'] ? getFullPath($data['img']) : '';
  1009. $data['thumb_img'] = $data['thumb_img'] ? getFullPath($data['thumb_img']) : '';
  1010. return $data ? : [];
  1011. }
  1012. /**
  1013. * [getUserNameById 根据主键获取详情]
  1014. * @param
  1015. * @return
  1016. */
  1017. public function getUserNameById($id = '')
  1018. {
  1019. $data = $this->where(['id' => $id])->value('realname');
  1020. return $data ? : '查看详情';
  1021. }
  1022. /**
  1023. * [getUserNameByArr 根据主键获取详情]
  1024. * @param
  1025. * @return
  1026. */
  1027. public function getUserNameByArr($ids = [])
  1028. {
  1029. if (!is_array($ids)) {
  1030. $idArr[] = $ids;
  1031. } else {
  1032. $idArr = $ids;
  1033. }
  1034. $data = $this->where(['id' => array('in', $idArr)])->column('realname');
  1035. return $data ? : [];
  1036. }
  1037. /**
  1038. * [getAdminId 获取管理员ID]
  1039. * @param
  1040. * @return
  1041. */
  1042. public function getAdminId()
  1043. {
  1044. $adminGroupUser = db('admin_access')->where(['group_id' => 1])->column('user_id');
  1045. $userIDs = $adminGroupUser ? array_merge($adminGroupUser, [1]) : [1];
  1046. return $userIDs ? : [1];
  1047. }
  1048. /**
  1049. * [getUserByIdArr 根据ID数组获取列表]
  1050. * @param
  1051. * @return
  1052. */
  1053. public function getUserByIdArr($ids = [])
  1054. {
  1055. $list = $this
  1056. ->alias('user')
  1057. ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
  1058. ->where(['user.id' => ['in', $id]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select();
  1059. return $list ? : [];
  1060. }
  1061. /**
  1062. * [getUserByPer 获取权限范围的user_id]
  1063. * @param
  1064. * @return
  1065. */
  1066. public function getUserByPer($m = '', $c = '', $a = ''){
  1067. $request = Request::instance();
  1068. $header = $request->header();
  1069. $authKey = $header['authkey'];
  1070. $m = $m ? strtolower($m) : strtolower($request->module());
  1071. $c = $c ? strtolower($c) : strtolower($request->controller());
  1072. $a = $a ? strtolower($a) : strtolower($request->action());
  1073. $cache = cache('Auth_'.$authKey);
  1074. if (!$cache) {
  1075. return false;
  1076. }
  1077. $userInfo = $cache['userInfo'];
  1078. //用户所属用户组类别(数组)
  1079. $groupTypes = $this->getGroupTypeByAction($userInfo['id'], $m, $c, $a);
  1080. //数组去重
  1081. $groupTypes = $groupTypes ? array_unique($groupTypes) : [];
  1082. //用户组类别(1本人,2本人及下属,3本部门,4本部门及下属部门,5全部)
  1083. $adminIds = $this->getAdminId();
  1084. $userIds = [];
  1085. if (in_array($userInfo['id'],$adminIds)) {
  1086. $userIds = getSubUserId(true, 1);
  1087. } else {
  1088. if (!$groupTypes) {
  1089. return [];
  1090. }
  1091. if (in_array(5, $groupTypes)) {
  1092. $userIds = getSubUserId(true, 1);
  1093. } else {
  1094. foreach ($groupTypes as $v) {
  1095. if ($v == 1) {
  1096. $userIds = [$userInfo['id']];
  1097. } elseif ($v == 2) {
  1098. $userIds = getSubUserId();
  1099. } elseif ($v == 3) {
  1100. $userIds = $this->getSubUserByStr($userInfo['structure_id']);
  1101. } elseif ($v == 4) {
  1102. $userIds = $this->getSubUserByStr($userInfo['structure_id'], 2);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. return $userIds ? : [];
  1108. }
  1109. /*
  1110. *根据部门ID获取员工列表
  1111. *
  1112. */
  1113. public function getUserListByStructureId($structure_id='')
  1114. {
  1115. $map =array();
  1116. if($structure_id){
  1117. $map['structure_id'] = $structure_id;
  1118. }
  1119. $list = Db::name('AdminUser')->field('id as user_id,realname,post,structure_id')->where($map)->select();
  1120. return $list ? : [];
  1121. }
  1122. /*
  1123. *根据字符串返回数组
  1124. *
  1125. */
  1126. public function getListByStr($str)
  1127. {
  1128. $idArr = stringToArray($str);
  1129. $list = db('admin_user')->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select();
  1130. return $list;
  1131. }
  1132. /*
  1133. *读写权限
  1134. *
  1135. */
  1136. public function rwPre($user_id, $ro_user_id, $rw_user_id, $action = 'read')
  1137. {
  1138. if ($action == 'update') {
  1139. if (!in_array($user_id, stringToArray($rw_user_id))) {
  1140. return false;
  1141. }
  1142. } else {
  1143. if (!in_array($user_id, stringToArray($ro_user_id))) {
  1144. return false;
  1145. }
  1146. }
  1147. return true;
  1148. }
  1149. /**
  1150. * [getUserThree 员工第三方扩展信息]
  1151. * @param key 分类
  1152. * @author Michael_xu
  1153. * @return [array]
  1154. */
  1155. public function getUserThree($key, $user_id)
  1156. {
  1157. $resValue = db('admin_user_threeparty')->where(['key' => $key,'user_id' => $user_id])->value('value');
  1158. return $resValue ? : '';
  1159. }
  1160. /**
  1161. * 获取当前登录用户信息
  1162. *
  1163. * @param string $key 默认返回所有信息
  1164. * @return mixed
  1165. * @author Ymob
  1166. * @datetime 2019-10-22 14:38:07
  1167. */
  1168. public static function userInfo($key = '')
  1169. {
  1170. $request = Request::instance();
  1171. $header = $request->header();
  1172. $authKey = $header['authkey'];
  1173. $sessionId = $header['sessionid'];
  1174. $paramArr = $request->param();
  1175. $platform = $paramArr['platform'] ? '_' . $paramArr['platform'] : ''; //请求平台(mobile,ding)
  1176. $cache = cache('Auth_' . $authKey . $platform);
  1177. if ($cache) {
  1178. if ($key) {
  1179. return $cache['userInfo'][$key];
  1180. } else {
  1181. return $cache['userInfo'];
  1182. }
  1183. } else {
  1184. return false;
  1185. }
  1186. }
  1187. /**
  1188. * 判断用户是否拥有 某(些) 角色
  1189. *
  1190. * @param array $group_list
  1191. * @param integer $user_id
  1192. * @return bool
  1193. * @author Ymob
  1194. * @datetime 2019-10-25 15:50:48
  1195. */
  1196. public static function checkUserGroup($group_list = [], $user_id = 0)
  1197. {
  1198. $user_id = $user_id ?: self::userInfo('id');
  1199. if (empty($group_list))
  1200. return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group]])->value('user_id');
  1201. }
  1202. /**
  1203. * 顶部菜单栏显示
  1204. * @param $param
  1205. * @return array
  1206. */
  1207. public function sortList($param){
  1208. $list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->find();
  1209. $list=unserialize($list['value']);
  1210. return $list?:[];
  1211. }
  1212. /**
  1213. * 修改顶部菜单显示
  1214. * @param $param
  1215. */
  1216. public function updateSort($param){
  1217. $list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->select();
  1218. if($list){
  1219. $data= Db::name('admin_sort')->where('user_id',$param['user_id'])->update(['value'=>serialize($param['value'])]);
  1220. }else{
  1221. $data= Db::name('admin_sort')->insert(['user_id'=>$param['user_id'],'value'=>serialize($param['value'])]);
  1222. }
  1223. return $data;
  1224. }
  1225. /**
  1226. * 复制员工角色
  1227. *
  1228. * @param $param
  1229. * @return bool
  1230. */
  1231. public function copyRole($param)
  1232. {
  1233. $userIds = !empty($param['user_id']) ? $param['user_id'] : [];
  1234. $structureIds = !empty($param['structure_id']) ? $param['structure_id'] : [];
  1235. $groupIds = !empty($param['group_id']) ? $param['group_id'] : [];
  1236. # 员工与角色关联数据
  1237. $userGroup = [];
  1238. # 查询部门下的员工ID
  1239. if (!empty($structureIds)) {
  1240. $userIds = Db::name('admin_user')->whereIn('structure_id', $param['structure_id'])->column('id');
  1241. $userIds = array_unique((array)$userIds);
  1242. }
  1243. Db::startTrans();
  1244. try{
  1245. # 删除员工角色关联数据
  1246. Db::name('admin_access')->whereIn('user_id', $userIds)->delete();
  1247. # 重新设置员工角色
  1248. foreach ($userIds AS $key => $value) {
  1249. # 默认跳过超级管理员
  1250. if ($value == 1) continue;
  1251. foreach ($groupIds AS $k => $v) {
  1252. $userGroup[] = [
  1253. 'user_id' => $value,
  1254. 'group_id' => $v
  1255. ];
  1256. }
  1257. }
  1258. if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);
  1259. Db::commit();
  1260. return true;
  1261. } catch (\Exception $e) {
  1262. Db::rollback();
  1263. return false;
  1264. }
  1265. }
  1266. }