User.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\controller;
  4. use app\BaseController;
  5. use app\model\Account;
  6. use think\facade\Cache;
  7. use think\Exception;use think\facade\Db;
  8. use think\App;
  9. use think\facade\Validate;
  10. class User extends BaseController
  11. {
  12. private $token_time = 0;// token 有效时间
  13. public function __construct(App $app)
  14. {
  15. parent::__construct($app);
  16. $this->token_time= env("token.expire");
  17. }
  18. /**注册接口
  19. * @param string username 账户名称
  20. * @param string password 账户密码
  21. * @param string mobile 账户手机号
  22. * @param string source 来源默认register
  23. * @return \think\response\Json|void
  24. * @throws \think\db\exception\DataNotFoundException
  25. * @throws \think\db\exception\DbException
  26. * @throws \think\db\exception\ModelNotFoundException
  27. */
  28. public function register()
  29. {
  30. $post =$this->request->only(["username"=>'',"password"=>"","mobile"=>"","source"=>"register"],"post","trim");
  31. $validate=Validate::rule([
  32. 'username|账户名称' => 'require|max:255',
  33. 'password|密码' => 'require|min:6|max:200',
  34. 'mobile|手机号' => 'require|number|length:11|mobile',
  35. ]);
  36. if($validate->check($post)==false) return json_show(1004,$validate->getError());
  37. $source = isset($post['source']) ? trim($post['source']):"";
  38. $uiq = Db::table("sys_account")->where(["username"=>$post['mobile']])->find();
  39. if($uiq){
  40. return json_show(1002,"账户名已存在!");
  41. }
  42. $uiq = Db::table("sys_account")->where(["mobile"=>$post['mobile']])->find();
  43. if($uiq){
  44. return json_show(1002,"手机号已注册!");
  45. }
  46. Db::startTrans();
  47. try {
  48. $salt =makeSalt();
  49. $password = sha1($post['password'].$salt);
  50. $data = [
  51. 'username'=>$post['mobile'],
  52. "password"=>$password,
  53. "salt"=>$salt,
  54. "mobile"=>$post['mobile'],
  55. "source"=>$source,
  56. "status"=>1,
  57. "addtime"=>date("Y-m-d H:i:s"),
  58. "updatetime"=>date("Y-m-d H:i:s")
  59. ];
  60. $reuslt = Db::table('sys_account')->insert($data,true);
  61. if($reuslt){
  62. $data=[
  63. "nickname"=>$post['username'],
  64. "mobile"=>$post['mobile'],
  65. "email"=>"",
  66. "portrait"=>"",
  67. "sex"=>1,
  68. "post"=>"",
  69. "department"=>"",
  70. "account_id"=>$reuslt,
  71. "status"=>1,
  72. "addtime"=>date("Y-m-d H:i:s"),
  73. "updatetime"=>date("Y-m-d H:i:s")
  74. ];
  75. $user=Db::table("sys_user")->insert($data,true);
  76. if($user){
  77. Db::commit();
  78. return json_show(0,"账户注册成功");
  79. }
  80. }
  81. Db::rollback();
  82. return json_show(1002,"账户注册失败");
  83. }catch (\Exception $e){
  84. Db::rollback();
  85. return json_show(1002,"账户注册失败".$e->getMessage());
  86. }
  87. }
  88. /**
  89. * 显示创建资源表单页.
  90. *
  91. * @return \think\Response
  92. */
  93. public function verify_code()
  94. {
  95. $post = $this->request->only("mobile","post");
  96. $code = make_verify();
  97. $mobile = isset($post['mobile'])&&checkMobile($post['mobile']) ? $post['mobile'] :"" ;
  98. if($mobile==""){
  99. return json_show(1001,"手机号格式不正确");
  100. }
  101. $mess =Db::name("send_message")->where(['mobile'=>$mobile,"status"=>0,"msg_type"=>1])->find();
  102. if($mess){
  103. if($mess['expire']>time()-60){
  104. return json_show(1001,"验证码发送中!");
  105. }
  106. $mess['status']=1;
  107. Db::name("send_message")->save($mess);
  108. }
  109. // $sendJson = sendMessage($mobile, $code);
  110. // $sendResult = json_decode($sendJson, TRUE);
  111. // if($sendResult['description'] != 'Success') {
  112. // return json_show(1002, '短信发送失败,请重试');
  113. // }
  114. $data=['code'=>$code,"mobile"=>$mobile,"status"=>0,"msg_type"=>1,"addtime"=>date("Y-m-d H:i:s"),
  115. "expire"=>time()];
  116. $result = Db::name("send_message")->insert($data);
  117. return $result ? json_show(0,"验证码已发送",["code"=>$code]): json_show(1001,"验证码发送失败");
  118. }
  119. /**
  120. * @param string username 账户
  121. * @param string password 密码
  122. * @param string plat_code 来源
  123. * @return \think\response\Json
  124. * @throws \Psr\SimpleCache\InvalidArgumentException
  125. * @throws \think\db\exception\DataNotFoundException
  126. * @throws \think\db\exception\DbException
  127. * @throws \think\db\exception\ModelNotFoundException
  128. * @throws \think\exception\DbException
  129. */
  130. public function login()
  131. {
  132. $post = $this->request->only(["username" => "", "password" => "", "plat_code" => ""], "post", "trim");
  133. $validate = Validate::rule([
  134. 'username|账户名称' => 'require|max:255',
  135. 'password|密码' => 'require|min:6|max:200',
  136. ]);
  137. if ($validate->check($post) == false) return json_show(1004, $validate->getError());
  138. $acc = Db::name("account")
  139. ->where(['username' => $post['username'], "is_del" => Account::$account_del])
  140. ->find();
  141. if ($acc == false) return json_show(1003, '账户名不存在');
  142. if ($acc['status'] == Account::$account_end) return json_show(1003, '账户已禁用');
  143. $sha1 = sha1($post['password'] . $acc['salt']);
  144. if ($sha1 != $acc['password']) return json_show(1003, '账户或密码错误');
  145. $token = makeToken($acc);
  146. if ($token == "") return json_show(1003, 'token生成失败');
  147. //account_plat 是空表
  148. // if ($post['plat_code'] != "") {
  149. // $platinfo = Db::name("account_plat")
  150. // ->alias("a")
  151. // ->leftJoin("platform b", "a.plat_code=b.plat_code and b.is_del=0 and b.status=1")
  152. // ->where(["a.status" => 1, "a.is_del" => 0, "a.plat_code" => $post['plat_code'], "a.account_id" => $acc['id']])
  153. // ->findOrEmpty();
  154. // if (empty($platinfo)) return json_show(1003, '该系统账号未开通登录');
  155. //
  156. // }
  157. $user = Db::name("account")
  158. ->alias("a")
  159. ->leftJoin("user b", "a.id=b.account_id and b.status=1")
  160. ->leftJoin("account_item c", "c.account_id=a.id")
  161. ->field("a.id,a.username,a.mobile,a.source,a.level,b.nickname,b.sex,b.email,a.addtime,a.updatetime,c.itemid,c.position")
  162. ->where(["a.id" => $acc["id"]])
  163. ->find();
  164. if ($user == false) return json_show(1003, '用户信息不存在');
  165. $usercompany = Db::name("account_company")
  166. ->where(["account_id" => $user['id'], "is_del" => 0, "status" => 1])
  167. ->column("companyCode,companyCode companyNo,companyName,companyName company_name,company_type,is_main,status");
  168. $user['company_relaton'] = $usercompany;
  169. $cache = Cache::store("redis")->set("user:info:{$token}", $user, $this->token_time);
  170. if ($cache == false) return json_show(1003, 'token保存失败');
  171. $user['token'] = $token;
  172. return json_show(0, "登录成功", $user);
  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. }