User.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\controller;
  4. use app\model\Account;
  5. use app\model\AccountPlat;use think\facade\Cache;
  6. use think\Exception;
  7. use think\facade\Db;
  8. use think\App;
  9. use think\facade\Validate;
  10. class User extends Base
  11. {
  12. private $token_time = 0;// token 有效时间
  13. private $model =null;// token 有效时间
  14. public function __construct(App $app)
  15. {
  16. parent::__construct($app);
  17. $this->token_time= env("token.expire");
  18. $this->model = new Account();
  19. }
  20. /**注册接口
  21. * @param string username 账户名称
  22. * @param string password 账户密码
  23. * @param string mobile 账户手机号
  24. * @param string source 来源默认register
  25. * @return \think\response\Json|void
  26. * @throws \think\db\exception\DataNotFoundException
  27. * @throws \think\db\exception\DbException
  28. * @throws \think\db\exception\ModelNotFoundException
  29. */
  30. public function register()
  31. {
  32. $post =$this->request->only(["username"=>'',"password"=>"","mobile"=>"","source"=>"register"],"post","trim");
  33. $validate=Validate::rule([
  34. 'username|账户名称' => 'require|max:255',
  35. 'password|密码' => 'require|min:6|max:200',
  36. 'mobile|手机号' => 'require|number|length:11|mobile',
  37. ]);
  38. if($validate->check($post)==false) return json_show(1004,$validate->getError());
  39. $source = isset($post['source']) ? trim($post['source']):"";
  40. $uiq = Db::table("sys_account")->where(["username"=>$post['mobile']])->find();
  41. if($uiq){
  42. return json_show(1002,"账户名已存在!");
  43. }
  44. $uiq = Db::table("sys_account")->where(["mobile"=>$post['mobile']])->find();
  45. if($uiq){
  46. return json_show(1002,"手机号已注册!");
  47. }
  48. Db::startTrans();
  49. try {
  50. $salt =makeSalt();
  51. $password = sha1($post['password'].$salt);
  52. $data = [
  53. 'username'=>$post['mobile'],
  54. "password"=>$password,
  55. "salt"=>$salt,
  56. "mobile"=>$post['mobile'],
  57. "source"=>$source,
  58. "status"=>1,
  59. "addtime"=>date("Y-m-d H:i:s"),
  60. "updatetime"=>date("Y-m-d H:i:s")
  61. ];
  62. $reuslt = Db::table('sys_account')->insert($data,true);
  63. if($reuslt){
  64. $data=[
  65. "nickname"=>$post['username'],
  66. "mobile"=>$post['mobile'],
  67. "email"=>"",
  68. "portrait"=>"",
  69. "sex"=>1,
  70. "post"=>"",
  71. "department"=>"",
  72. "account_id"=>$reuslt,
  73. "status"=>1,
  74. "addtime"=>date("Y-m-d H:i:s"),
  75. "updatetime"=>date("Y-m-d H:i:s")
  76. ];
  77. $user=Db::table("sys_user")->insert($data,true);
  78. if($user){
  79. Db::commit();
  80. return json_show(0,"账户注册成功");
  81. }
  82. }
  83. Db::rollback();
  84. return json_show(1002,"账户注册失败");
  85. }catch (\Exception $e){
  86. Db::rollback();
  87. return json_show(1002,"账户注册失败".$e->getMessage());
  88. }
  89. }
  90. /**
  91. * 显示创建资源表单页.
  92. *
  93. * @return \think\Response
  94. */
  95. public function verify_code()
  96. {
  97. $post = $this->request->only("mobile","post");
  98. $code = make_verify();
  99. $mobile = isset($post['mobile'])&&checkMobile($post['mobile']) ? $post['mobile'] :"" ;
  100. if($mobile==""){
  101. return json_show(1001,"手机号格式不正确");
  102. }
  103. $mess =Db::name("send_message")->where(['mobile'=>$mobile,"status"=>0,"msg_type"=>1])->find();
  104. if($mess){
  105. if($mess['expire']>time()-60){
  106. return json_show(1001,"验证码发送中!");
  107. }
  108. $mess['status']=1;
  109. Db::name("send_message")->save($mess);
  110. }
  111. // $sendJson = sendMessage($mobile, $code);
  112. // $sendResult = json_decode($sendJson, TRUE);
  113. // if($sendResult['description'] != 'Success') {
  114. // return json_show(1002, '短信发送失败,请重试');
  115. // }
  116. $data=['code'=>$code,"mobile"=>$mobile,"status"=>0,"msg_type"=>1,"addtime"=>date("Y-m-d H:i:s"),
  117. "expire"=>time()];
  118. $result = Db::name("send_message")->insert($data);
  119. return $result ? json_show(0,"验证码已发送",["code"=>$code]): json_show(1001,"验证码发送失败");
  120. }
  121. /**
  122. * @param string username 账户
  123. * @param string password 密码
  124. * @param string plat_code 来源
  125. * @return \think\response\Json
  126. * @throws \Psr\SimpleCache\InvalidArgumentException
  127. * @throws \think\Exception
  128. * @throws \think\db\exception\DataNotFoundException
  129. * @throws \think\db\exception\DbException
  130. * @throws \think\db\exception\ModelNotFoundException
  131. * @throws \think\exception\DbException
  132. */
  133. public function login()
  134. {
  135. $post = $this->request->only(["username" => "", "password" => "", "plat_code" => "","openId"=>""], "post", "trim");
  136. $validate = Validate::rule([
  137. 'username|账户名称' => 'require|max:255',
  138. 'password|密码' => 'require|min:6|max:200',
  139. ]);
  140. if ($validate->check($post) == false) $this->error($validate->getError(),1004);
  141. $acc = $this->model->withJoin(["userinfo","accountitem"],"left")
  142. ->where(['username' => $post['username']])
  143. ->findOrEmpty();
  144. if ($acc->isEmpty()) return json_show(1003, '账户名不存在');
  145. if ($acc['status'] == Account::$account_end)$this->error('账户已禁用',1003);
  146. $sha1 = sha1($post['password'] . $acc['salt']);
  147. if ($sha1 != $acc['password']) $this->error('账户或密码错误',1003);
  148. $userinfo=[
  149. "id"=>$acc->id,
  150. "username"=>$acc->username,
  151. "mobile"=>$acc->mobile,
  152. "source"=>$acc->source,
  153. "nickname"=>$acc->userinfo->nickname,
  154. "sex"=>$acc->userinfo->sex,
  155. "email"=>$acc->userinfo->email,
  156. "level"=>$acc->level,
  157. "itemid"=>$acc->accountitem->itemid??0,
  158. "position"=>$acc->accountitem->position??'',
  159. "depart_name"=>$acc->depart_name,
  160. "company_relaton"=>$acc->company_relaton,
  161. "system_version"=>(new AccountPlat())->where(['account_id'=>$acc->id])->column('system_version','plat_code')
  162. ];
  163. if($post['openId']!=''){
  164. if($acc->userinfo->openId!='')$this->error('账户信息已绑定微信请先解除',1004);
  165. $acc->userinfo->openId=$post['openId'];
  166. $this->model->userinfo()->save($acc->userinfo->toArray());
  167. }
  168. $token = makeToken($userinfo);
  169. if ($token == "") $this->error('token生成失败',1003);
  170. $cache = Cache::store("redis")->set("user:info:{$token}", $userinfo, $this->token_time);
  171. if ($cache == false)$this->error('token保存失败',1003);
  172. $userinfo['token'] = $token;
  173. $this->success("登录成功", $userinfo,0);
  174. }
  175. /**
  176. *钉钉登录接口
  177. *
  178. * @param \think\Request $request
  179. * @param string $code
  180. * @return \think\Response
  181. */
  182. public function DingTalk()
  183. {
  184. $config= config("dingtalk");
  185. $dingtalk =new \DingTalk($config);
  186. $post = $this->request->only(["code"=>""],"post","trim");
  187. $code=isset($post["code"])&&$post["code"]!="" ? $post["code"]:"";
  188. if($code==""){
  189. return json_show(106,"参数code不能为空");
  190. }
  191. $li = $dingtalk->getUserByCode($code);
  192. if($li['errcode']!=0){
  193. return json_show(107,"授权失败",$li);
  194. }
  195. $list = $dingtalk->getUser($li['userid']);
  196. if($list['errcode']!=0){
  197. return json_show(107,"授权失败",$list);
  198. }
  199. $userinfo = Db::name("account")->alias("a")
  200. ->leftJoin("user b","a.id=b.account_id and b.status=1")
  201. ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
  202. ->where(['DTuserid'=>$list['userid'],"unionid"=>$list['unionid'],"a.is_del"=>0])
  203. ->findOrEmpty();
  204. if(empty($userinfo)){
  205. Db::startTrans();
  206. try{
  207. $accountid = $this->DingTalkRegister($list);
  208. Db::commit();
  209. }catch (\Exception $e){
  210. Db::rollback();
  211. return json_show(106,$e->getMessage());
  212. }
  213. $userinfo = Db::name("account")->alias("a")
  214. ->leftJoin("user b","a.id=b.account_id and b.status=1")
  215. ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
  216. ->where(["a.id"=>$accountid,"a.is_del"=>0])
  217. ->findOrEmpty();
  218. }
  219. $token = makeToken($userinfo);
  220. $usercompany = Db::name("account_company")->where(["account_id"=>$userinfo['id'],"is_del"=>0,"status"=>1])
  221. ->column("companyCode,companyName,company_type,is_main,status");
  222. $user['company_relaton'] = $usercompany;
  223. $cache = Cache::store("redis")->set("user:info:{$token}",$user ,$this->token_time);
  224. if($cache==false) return json_show(1003,'token保存失败');
  225. $user['token']=$token;
  226. return json_show(0,"授权成功",$userinfo);
  227. }
  228. /**
  229. * @param $Dingtalinfo
  230. * @return int|string
  231. * @throws \think\Exception
  232. */
  233. private function DingTalkRegister($Dingtalinfo){
  234. $salt=makeSalt();
  235. $data=[
  236. "username"=>$Dingtalinfo['mobile'],
  237. "password"=>sha1("dingding123".$salt),
  238. "mobile"=>$Dingtalinfo['mobile'],
  239. "salt"=>$salt,
  240. "status"=>1,
  241. "source"=>"dingtalk",
  242. "addtime"=>date("Y-m-d H:i:s"),
  243. "updatetime"=>date("Y-m-d H:i:s")
  244. ];
  245. $account = Db::table("sys_account")->insert($data,true);
  246. if($account<=0)throw new Exception("账户创建失败");
  247. $verify = Db::name("user")->where("mobile","=",$Dingtalinfo['mobile'])->findOrEmpty();
  248. if(!empty($verify)){
  249. $verify['unionid']=$Dingtalinfo['unionid'];
  250. $verify['openId']=$Dingtalinfo['openId'];
  251. $verify['DTuserid']=$Dingtalinfo['userid'];
  252. $verify['mobile']=$Dingtalinfo['mobile'];
  253. $verify['account_id']=$account;
  254. isset($verify['portrait'])??$verify['portrait']=$Dingtalinfo['avatar'];
  255. isset($verify['email'])??$verify['email']=$Dingtalinfo['email'];
  256. $verify['updatetime']=date("Y-m-d H:i:s");
  257. $user =Db::name("user")->save($verify);
  258. if($user==false) throw new Exception("用户信息创建失败");
  259. $uid = $verify["id"];
  260. }else{
  261. $data=[
  262. "nickname"=>$Dingtalinfo['name'],
  263. "mobile"=>$Dingtalinfo['mobile'],
  264. "email"=>$Dingtalinfo['email'],
  265. "portrait"=>$Dingtalinfo['avatar'],
  266. "sex"=>1,
  267. "post"=>"",
  268. "unionid"=>$Dingtalinfo['unionid'],
  269. "openId"=>$Dingtalinfo['openId'],
  270. "DTuserid"=>$Dingtalinfo['userid'],
  271. "department"=>"",
  272. "status"=>1,
  273. "account_id"=>$account,
  274. "addtime"=>date("Y-m-d H:i:s"),
  275. "updatetime"=>date("Y-m-d H:i:s")
  276. ];
  277. $uid =Db::name("user")->insert($data,true);
  278. }
  279. if($uid==false) throw new Exception("用户信息创建失败");
  280. return $account;
  281. }
  282. /**
  283. * @return \think\response\Json
  284. * @throws \think\db\exception\DataNotFoundException
  285. * @throws \think\db\exception\DbException
  286. * @throws \think\db\exception\ModelNotFoundException
  287. * @throws \think\exception\DbException
  288. */
  289. public function verify_token()
  290. {
  291. $post = $this->request->only(["token" => ''], "post");
  292. $validate = Validate::rule(['token' => 'require']);
  293. if ($validate->check($post) == false) return json_show(1004, $validate->getError());
  294. $getToken = checkToken($post['token'], $this->token_time);
  295. if( $getToken == false)$this->error('token失效','104');
  296. else{
  297. $getToken['system_version']=(new AccountPlat())->where(['account_id'=>$getToken['id']])->column
  298. ('system_version','plat_code');
  299. $this->success('获取成功',$getToken,0);
  300. }
  301. }
  302. /**
  303. * @return \think\response\Json|void
  304. * @throws \think\db\exception\DataNotFoundException
  305. * @throws \think\db\exception\DbException
  306. * @throws \think\db\exception\ModelNotFoundException
  307. */
  308. public function reset_password_mobile(){
  309. $post=$this->request->post();
  310. $mobile = isset($post['mobile'])? trim($post['mobile']):"";
  311. if($mobile==""){
  312. return json_show(1001,"手机号不能为空");
  313. }
  314. if(checkMobile($mobile)==false){
  315. return json_show(1002,"手机号格式不正确!");
  316. }
  317. $code = isset($post['code'])? trim($post['code']):"";
  318. if($code==""){
  319. return json_show(1001,"验证码不能为空");
  320. }
  321. $username = isset($post['username'])?trim($post['username']):"";
  322. if($username==""){
  323. return json_show(1001,"参数username 不能为空");
  324. }
  325. $account = Db::name("account")->where("username","=",$username)->find();
  326. if($account['mobile']!=$mobile){
  327. return json_show(1004,"账户关联手机号不正确");
  328. }
  329. $password = isset($post['password'])?trim($post['password']):"";
  330. if($password==""){
  331. return json_show(1001,"新密码不能为空");
  332. }
  333. if(sha1($password.$account['salt'])==$account['password']){
  334. return json_show(1001,"新密码不能与原密码相同");
  335. }
  336. $codeinfo = Db::name("send_message")->where(["mobile"=>$mobile,"status"=>0,"msg_type"=>1])->find();
  337. if($code!=$codeinfo['code']){
  338. return json_show(1003,"验证码错误");
  339. }
  340. $codeinfo['status']=1;
  341. Db::name("send_message")->save($codeinfo);
  342. $account['salt']=makeSalt();
  343. $account['updatetime']=date("Y-m-d");
  344. $account['is_pass']=1;
  345. $account['password']=sha1($password.$account['salt']);
  346. $result=Db::name("account")->save($account);
  347. return $result?json_show(0,"密码修改成功"):json_show(1003,"密码修改失败");
  348. }
  349. public function AccountQuery(){
  350. $param = $this->request->only(['nickname' => '', 'username' => '',"is_wx"=>"",'level'=>'', 'status' => '',
  351. 'page'=> 1,'size'=>30], 'post', 'trim');
  352. $where=[];
  353. $param['nickname']==''?: $where[]=['userinfo.nickname','like',"%{$param['nickname']}%"];
  354. $param['is_wx']===''?: $where[]=['userinfo.openId', $param['is_wx']==0?"=":"<>",""];
  355. $param['status']==''?: $where[]=['account.status','=',$param['status']];
  356. $param['level']==''?: $where[]=['account.level','=',$param['level']];
  357. $param['username']==''?: $where[]=['username','like',"%{$param['username']}%"];
  358. $acc = $this->model->withJoin(['userinfo'],"left")->where($where)->order('id desc')
  359. ->paginate(['page'=>$param['page'],'list_rows'=>$param['size']]);
  360. $tenmp=[];
  361. foreach ($acc->items() as $value){
  362. $temp=[];
  363. $temp['id'] = $value->id;
  364. $temp['nickname'] = $value->nickname;
  365. $temp['mobile'] = substr_replace($value->mobile,"****",-4);
  366. $temp['is_wx'] = $value->is_wx;
  367. $temp['status'] = $value->status;
  368. $tenmp[]=$temp;
  369. }
  370. $this->success('获取成功',['list'=>$tenmp,'count'=>$acc->total()],0);
  371. }
  372. public function BindWx(){
  373. $param = $this->request->only(['id' => '', 'openId' => '','lastCode'=>''], 'post', 'trim');
  374. $valid =Validate::rule(["id|账户主键"=>"require|number|egt:0","openId|微信openid"=>"require|max:255","lastCode|手机号后四位"=>"require|number|length:4"]);
  375. if($valid->check($param)==false) $this->error($valid->getError());
  376. $acc = $this->model->withJoin(['userinfo','accountitem'],'left')->findOrEmpty($param['id']);
  377. if($acc->isEmpty())$this->error("账户信息不存在",1004);
  378. if($acc->userinfo->openId!='')$this->error("账户信息已绑定微信请先解除",1004);
  379. if(substr($acc->mobile,-4,4)!=$param['lastCode'])$this->error('手机后四位不正确!',1004);
  380. if($param['openId']!==''&& $acc->userinfo->openId!=$param['openId'] ){
  381. $acc->userinfo->openId=$param['openId'];
  382. $this->model->userinfo()->save($acc->userinfo->toArray());
  383. }
  384. $userinfo=[
  385. 'id'=>$acc->id,
  386. 'username'=>$acc->username,
  387. 'mobile'=>$acc->mobile,
  388. 'source'=>$acc->source,
  389. 'nickname'=>$acc->userinfo->nickname,
  390. 'sex'=>$acc->userinfo->sex,
  391. 'email'=>$acc->userinfo->email,
  392. 'level'=>$acc->level,
  393. 'itemid'=>$acc->accountitem->itemid??0,
  394. 'position'=>$acc->accountitem->position??'',
  395. 'depart_name'=>$acc->depart_name,
  396. 'company_relaton'=>$acc->company_relaton,
  397. 'system_version'=>(new AccountPlat())->where(['account_id'=>$acc->id])->column('system_version','plat_code')
  398. ];
  399. $token = makeToken($userinfo);
  400. if ($token == '') $this->error('token生成失败',1003);
  401. $cache = Cache::store('redis')->set("user:info:{$token}", $userinfo, $this->token_time);
  402. if ($cache == false)$this->error('token保存失败',1003);
  403. $userinfo['token'] = $token;
  404. $this->success('获取成功',$userinfo,0);
  405. }
  406. /**
  407. * 系统板本更新
  408. */
  409. public function setSystemVer(){
  410. $param = $this->request->only(['account_id' => '', 'plat_code' => '','system_version'=>''], 'post', 'trim');
  411. $valid =Validate::rule([
  412. 'account_id|账户主键'=>'require|number|egt:0',
  413. 'plat_code|系统类型'=>'require|max:255|in:cx,st',
  414. 'system_version|系统更新版本号'=>'require'
  415. ]);
  416. if($valid->check($param)==false) $this->error($valid->getError());
  417. $accountPlat= new AccountPlat();
  418. $info =$accountPlat->where($param)->findOrEmpty();
  419. if($info->isEmpty()==false) $this->error('记录信息已存在',1003);
  420. $accountPlat->where(["account_id"=>$param['account_id'],"plat_code"=>$param['plat_code']])->select()->delete();
  421. $pl= $accountPlat->save($param);
  422. $pl? $this->success('记录成功',[],0): $this->error('记录失败',1003);;
  423. }
  424. }