User.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\controller;
  4. use app\model\Account;
  5. 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. ];
  162. if($post['openId']!=''){
  163. if($acc->userinfo->openId!='')$this->error('账户信息已绑定微信请先解除',1004);
  164. $acc->userinfo->openId=$post['openId'];
  165. $this->model->userinfo()->save($acc->userinfo->toArray());
  166. }
  167. $token = makeToken($userinfo);
  168. if ($token == "") $this->error('token生成失败',1003);
  169. $cache = Cache::store("redis")->set("user:info:{$token}", $userinfo, $this->token_time);
  170. if ($cache == false)$this->error('token保存失败',1003);
  171. $userinfo['token'] = $token;
  172. $this->success("登录成功", $userinfo,0);
  173. }
  174. /**
  175. *钉钉登录接口
  176. *
  177. * @param \think\Request $request
  178. * @param string $code
  179. * @return \think\Response
  180. */
  181. public function DingTalk()
  182. {
  183. $config= config("dingtalk");
  184. $dingtalk =new \DingTalk($config);
  185. $post = $this->request->only(["code"=>""],"post","trim");
  186. $code=isset($post["code"])&&$post["code"]!="" ? $post["code"]:"";
  187. if($code==""){
  188. return json_show(106,"参数code不能为空");
  189. }
  190. $li = $dingtalk->getUserByCode($code);
  191. if($li['errcode']!=0){
  192. return json_show(107,"授权失败",$li);
  193. }
  194. $list = $dingtalk->getUser($li['userid']);
  195. if($list['errcode']!=0){
  196. return json_show(107,"授权失败",$list);
  197. }
  198. $userinfo = Db::name("account")->alias("a")
  199. ->leftJoin("user b","a.id=b.account_id and b.status=1")
  200. ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
  201. ->where(['DTuserid'=>$list['userid'],"unionid"=>$list['unionid'],"a.is_del"=>0])
  202. ->findOrEmpty();
  203. if(empty($userinfo)){
  204. Db::startTrans();
  205. try{
  206. $accountid = $this->DingTalkRegister($list);
  207. Db::commit();
  208. }catch (\Exception $e){
  209. Db::rollback();
  210. return json_show(106,$e->getMessage());
  211. }
  212. $userinfo = Db::name("account")->alias("a")
  213. ->leftJoin("user b","a.id=b.account_id and b.status=1")
  214. ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
  215. ->where(["a.id"=>$accountid,"a.is_del"=>0])
  216. ->findOrEmpty();
  217. }
  218. $token = makeToken($userinfo);
  219. $usercompany = Db::name("account_company")->where(["account_id"=>$userinfo['id'],"is_del"=>0,"status"=>1])
  220. ->column("companyCode,companyName,company_type,is_main,status");
  221. $user['company_relaton'] = $usercompany;
  222. $cache = Cache::store("redis")->set("user:info:{$token}",$user ,$this->token_time);
  223. if($cache==false) return json_show(1003,'token保存失败');
  224. $user['token']=$token;
  225. return json_show(0,"授权成功",$userinfo);
  226. }
  227. /**
  228. * @param $Dingtalinfo
  229. * @return int|string
  230. * @throws \think\Exception
  231. */
  232. private function DingTalkRegister($Dingtalinfo){
  233. $salt=makeSalt();
  234. $data=[
  235. "username"=>$Dingtalinfo['mobile'],
  236. "password"=>sha1("dingding123".$salt),
  237. "mobile"=>$Dingtalinfo['mobile'],
  238. "salt"=>$salt,
  239. "status"=>1,
  240. "source"=>"dingtalk",
  241. "addtime"=>date("Y-m-d H:i:s"),
  242. "updatetime"=>date("Y-m-d H:i:s")
  243. ];
  244. $account = Db::table("sys_account")->insert($data,true);
  245. if($account<=0)throw new Exception("账户创建失败");
  246. $verify = Db::name("user")->where("mobile","=",$Dingtalinfo['mobile'])->findOrEmpty();
  247. if(!empty($verify)){
  248. $verify['unionid']=$Dingtalinfo['unionid'];
  249. $verify['openId']=$Dingtalinfo['openId'];
  250. $verify['DTuserid']=$Dingtalinfo['userid'];
  251. $verify['mobile']=$Dingtalinfo['mobile'];
  252. $verify['account_id']=$account;
  253. isset($verify['portrait'])??$verify['portrait']=$Dingtalinfo['avatar'];
  254. isset($verify['email'])??$verify['email']=$Dingtalinfo['email'];
  255. $verify['updatetime']=date("Y-m-d H:i:s");
  256. $user =Db::name("user")->save($verify);
  257. if($user==false) throw new Exception("用户信息创建失败");
  258. $uid = $verify["id"];
  259. }else{
  260. $data=[
  261. "nickname"=>$Dingtalinfo['name'],
  262. "mobile"=>$Dingtalinfo['mobile'],
  263. "email"=>$Dingtalinfo['email'],
  264. "portrait"=>$Dingtalinfo['avatar'],
  265. "sex"=>1,
  266. "post"=>"",
  267. "unionid"=>$Dingtalinfo['unionid'],
  268. "openId"=>$Dingtalinfo['openId'],
  269. "DTuserid"=>$Dingtalinfo['userid'],
  270. "department"=>"",
  271. "status"=>1,
  272. "account_id"=>$account,
  273. "addtime"=>date("Y-m-d H:i:s"),
  274. "updatetime"=>date("Y-m-d H:i:s")
  275. ];
  276. $uid =Db::name("user")->insert($data,true);
  277. }
  278. if($uid==false) throw new Exception("用户信息创建失败");
  279. return $account;
  280. }
  281. /**
  282. * @return \think\response\Json
  283. * @throws \think\db\exception\DataNotFoundException
  284. * @throws \think\db\exception\DbException
  285. * @throws \think\db\exception\ModelNotFoundException
  286. * @throws \think\exception\DbException
  287. */
  288. public function verify_token()
  289. {
  290. $post = $this->request->only(["token" => ''], "post");
  291. $validate = Validate::rule(['token' => 'require']);
  292. if ($validate->check($post) == false) return json_show(1004, $validate->getError());
  293. $getToken = checkToken($post['token'], $this->token_time);
  294. return $getToken == false ? json_show(104, "token失效") : json_show(0, "获取成功", $getToken);
  295. }
  296. /**
  297. * @return \think\response\Json|void
  298. * @throws \think\db\exception\DataNotFoundException
  299. * @throws \think\db\exception\DbException
  300. * @throws \think\db\exception\ModelNotFoundException
  301. */
  302. public function reset_password_mobile(){
  303. $post=$this->request->post();
  304. $mobile = isset($post['mobile'])? trim($post['mobile']):"";
  305. if($mobile==""){
  306. return json_show(1001,"手机号不能为空");
  307. }
  308. if(checkMobile($mobile)==false){
  309. return json_show(1002,"手机号格式不正确!");
  310. }
  311. $code = isset($post['code'])? trim($post['code']):"";
  312. if($code==""){
  313. return json_show(1001,"验证码不能为空");
  314. }
  315. $username = isset($post['username'])?trim($post['username']):"";
  316. if($username==""){
  317. return json_show(1001,"参数username 不能为空");
  318. }
  319. $account = Db::name("account")->where("username","=",$username)->find();
  320. if($account['mobile']!=$mobile){
  321. return json_show(1004,"账户关联手机号不正确");
  322. }
  323. $password = isset($post['password'])?trim($post['password']):"";
  324. if($password==""){
  325. return json_show(1001,"新密码不能为空");
  326. }
  327. if(sha1($password.$account['salt'])==$account['password']){
  328. return json_show(1001,"新密码不能与原密码相同");
  329. }
  330. $codeinfo = Db::name("send_message")->where(["mobile"=>$mobile,"status"=>0,"msg_type"=>1])->find();
  331. if($code!=$codeinfo['code']){
  332. return json_show(1003,"验证码错误");
  333. }
  334. $codeinfo['status']=1;
  335. Db::name("send_message")->save($codeinfo);
  336. $account['salt']=makeSalt();
  337. $account['updatetime']=date("Y-m-d");
  338. $account['is_pass']=1;
  339. $account['password']=sha1($password.$account['salt']);
  340. $result=Db::name("account")->save($account);
  341. return $result?json_show(0,"密码修改成功"):json_show(1003,"密码修改失败");
  342. }
  343. public function AccountQuery(){
  344. $param = $this->request->only(['nickname' => '', 'username' => '',"is_wx"=>"",'level'=>'', 'status' => '',
  345. 'page'=> 1,'size'=>30], 'post', 'trim');
  346. $where=[];
  347. $param['nickname']==''?: $where[]=['userinfo.nickname','like',"%{$param['nickname']}%"];
  348. $param['is_wx']===''?: $where[]=['userinfo.openId', $param['is_wx']==0?"=":"<>",""];
  349. $param['status']==''?: $where[]=['account.status','=',$param['status']];
  350. $param['level']==''?: $where[]=['account.level','=',$param['level']];
  351. $param['username']==''?: $where[]=['username','like',"%{$param['username']}%"];
  352. $acc = $this->model->withJoin(['userinfo'],"left")->where($where)->order('id desc')
  353. ->paginate(['page'=>$param['page'],'list_rows'=>$param['size']]);
  354. $tenmp=[];
  355. foreach ($acc->items() as $value){
  356. $temp=[];
  357. $temp['id'] = $value->id;
  358. $temp['nickname'] = $value->nickname;
  359. $temp['mobile'] = substr_replace($value->mobile,"****",-4);
  360. $temp['is_wx'] = $value->is_wx;
  361. $temp['status'] = $value->status;
  362. $tenmp[]=$temp;
  363. }
  364. $this->success('获取成功',['list'=>$tenmp,'count'=>$acc->total()],0);
  365. }
  366. public function BindWx(){
  367. $param = $this->request->only(['id' => '', 'openId' => '','lastCode'=>''], 'post', 'trim');
  368. $valid =Validate::rule(["id|账户主键"=>"require|number|egt:0","openId|微信openid"=>"require|max:255","lastCode|手机号后四位"=>"require|number|length:4"]);
  369. if($valid->check($param)==false) $this->error($valid->getError());
  370. $acc = $this->model->withJoin(['userinfo','accountitem'],'left')->findOrEmpty($param['id']);
  371. if($acc->isEmpty())$this->error("账户信息不存在",1004);
  372. if($acc->userinfo->openId!='')$this->error("账户信息已绑定微信请先解除",1004);
  373. if(substr($acc->mobile,-4,4)!=$param['lastCode'])$this->error('手机后四位不正确!',1004);
  374. if($param['openId']!==''&& $acc->userinfo->openId!=$param['openId'] ){
  375. $acc->userinfo->openId=$param['openId'];
  376. $this->model->userinfo()->save($acc->userinfo->toArray());
  377. }
  378. $userinfo=[
  379. 'id'=>$acc->id,
  380. 'username'=>$acc->username,
  381. 'mobile'=>$acc->mobile,
  382. 'source'=>$acc->source,
  383. 'nickname'=>$acc->userinfo->nickname,
  384. 'sex'=>$acc->userinfo->sex,
  385. 'email'=>$acc->userinfo->email,
  386. 'level'=>$acc->level,
  387. 'itemid'=>$acc->accountitem->itemid??0,
  388. 'position'=>$acc->accountitem->position??'',
  389. 'depart_name'=>$acc->depart_name,
  390. 'company_relaton'=>$acc->company_relaton,
  391. ];
  392. $token = makeToken($userinfo);
  393. if ($token == '') $this->error('token生成失败',1003);
  394. $cache = Cache::store('redis')->set("user:info:{$token}", $userinfo, $this->token_time);
  395. if ($cache == false)$this->error('token保存失败',1003);
  396. $userinfo['token'] = $token;
  397. $this->success('获取成功',$userinfo,0);
  398. }
  399. }