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