User.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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")->where(['username' => $post['username']])->findOrEmpty();
  142. if ($acc->isEmpty() == false) return json_show(1003, '账户名不存在');
  143. if ($acc['status'] == Account::$account_end)$this->error('账户已禁用',1003);
  144. $sha1 = sha1($post['password'] . $acc['salt']);
  145. if ($sha1 != $acc['password']) $this->error('账户或密码错误',1003);
  146. $token = makeToken($acc);
  147. if ($token == "") $this->error('token生成失败',1003);
  148. $cache = Cache::store("redis")->set("user:info:{$token}", $acc->toArray(), $this->token_time);
  149. if ($cache == false)$this->error('token保存失败',1003);
  150. $acc['token'] = $token;
  151. $this->success("登录成功", $acc);
  152. }
  153. /**
  154. *钉钉登录接口
  155. *
  156. * @param \think\Request $request
  157. * @param string $code
  158. * @return \think\Response
  159. */
  160. public function DingTalk()
  161. {
  162. $config= config("dingtalk");
  163. $dingtalk =new \DingTalk($config);
  164. $post = $this->request->only(["code"=>""],"post","trim");
  165. $code=isset($post["code"])&&$post["code"]!="" ? $post["code"]:"";
  166. if($code==""){
  167. return json_show(106,"参数code不能为空");
  168. }
  169. $li = $dingtalk->getUserByCode($code);
  170. if($li['errcode']!=0){
  171. return json_show(107,"授权失败",$li);
  172. }
  173. $list = $dingtalk->getUser($li['userid']);
  174. if($list['errcode']!=0){
  175. return json_show(107,"授权失败",$list);
  176. }
  177. $userinfo = Db::name("account")->alias("a")
  178. ->leftJoin("user b","a.id=b.account_id and b.status=1")
  179. ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
  180. ->where(['DTuserid'=>$list['userid'],"unionid"=>$list['unionid'],"a.is_del"=>0])
  181. ->findOrEmpty();
  182. if(empty($userinfo)){
  183. Db::startTrans();
  184. try{
  185. $accountid = $this->DingTalkRegister($list);
  186. Db::commit();
  187. }catch (\Exception $e){
  188. Db::rollback();
  189. return json_show(106,$e->getMessage());
  190. }
  191. $userinfo = Db::name("account")->alias("a")
  192. ->leftJoin("user b","a.id=b.account_id and b.status=1")
  193. ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
  194. ->where(["a.id"=>$accountid,"a.is_del"=>0])
  195. ->findOrEmpty();
  196. }
  197. $token = makeToken($userinfo);
  198. $usercompany = Db::name("account_company")->where(["account_id"=>$userinfo['id'],"is_del"=>0,"status"=>1])
  199. ->column("companyCode,companyName,company_type,is_main,status");
  200. $user['company_relaton'] = $usercompany;
  201. $cache = Cache::store("redis")->set("user:info:{$token}",$user ,$this->token_time);
  202. if($cache==false) return json_show(1003,'token保存失败');
  203. $user['token']=$token;
  204. return json_show(0,"授权成功",$userinfo);
  205. }
  206. /**
  207. * @param $Dingtalinfo
  208. * @return int|string
  209. * @throws \think\Exception
  210. */
  211. private function DingTalkRegister($Dingtalinfo){
  212. $salt=makeSalt();
  213. $data=[
  214. "username"=>$Dingtalinfo['mobile'],
  215. "password"=>sha1("dingding123".$salt),
  216. "mobile"=>$Dingtalinfo['mobile'],
  217. "salt"=>$salt,
  218. "status"=>1,
  219. "source"=>"dingtalk",
  220. "addtime"=>date("Y-m-d H:i:s"),
  221. "updatetime"=>date("Y-m-d H:i:s")
  222. ];
  223. $account = Db::table("sys_account")->insert($data,true);
  224. if($account<=0)throw new Exception("账户创建失败");
  225. $verify = Db::name("user")->where("mobile","=",$Dingtalinfo['mobile'])->findOrEmpty();
  226. if(!empty($verify)){
  227. $verify['unionid']=$Dingtalinfo['unionid'];
  228. $verify['openId']=$Dingtalinfo['openId'];
  229. $verify['DTuserid']=$Dingtalinfo['userid'];
  230. $verify['mobile']=$Dingtalinfo['mobile'];
  231. $verify['account_id']=$account;
  232. isset($verify['portrait'])??$verify['portrait']=$Dingtalinfo['avatar'];
  233. isset($verify['email'])??$verify['email']=$Dingtalinfo['email'];
  234. $verify['updatetime']=date("Y-m-d H:i:s");
  235. $user =Db::name("user")->save($verify);
  236. if($user==false) throw new Exception("用户信息创建失败");
  237. $uid = $verify["id"];
  238. }else{
  239. $data=[
  240. "nickname"=>$Dingtalinfo['name'],
  241. "mobile"=>$Dingtalinfo['mobile'],
  242. "email"=>$Dingtalinfo['email'],
  243. "portrait"=>$Dingtalinfo['avatar'],
  244. "sex"=>1,
  245. "post"=>"",
  246. "unionid"=>$Dingtalinfo['unionid'],
  247. "openId"=>$Dingtalinfo['openId'],
  248. "DTuserid"=>$Dingtalinfo['userid'],
  249. "department"=>"",
  250. "status"=>1,
  251. "account_id"=>$account,
  252. "addtime"=>date("Y-m-d H:i:s"),
  253. "updatetime"=>date("Y-m-d H:i:s")
  254. ];
  255. $uid =Db::name("user")->insert($data,true);
  256. }
  257. if($uid==false) throw new Exception("用户信息创建失败");
  258. return $account;
  259. }
  260. /**
  261. * @return \think\response\Json
  262. * @throws \think\db\exception\DataNotFoundException
  263. * @throws \think\db\exception\DbException
  264. * @throws \think\db\exception\ModelNotFoundException
  265. * @throws \think\exception\DbException
  266. */
  267. public function verify_token()
  268. {
  269. $post = $this->request->only(["token" => ''], "post");
  270. $validate = Validate::rule(['token' => 'require']);
  271. if ($validate->check($post) == false) return json_show(1004, $validate->getError());
  272. $getToken = checkToken($post['token'], $this->token_time);
  273. return $getToken == false ? json_show(104, "token失效") : json_show(0, "获取成功", $getToken);
  274. }
  275. /**
  276. * @return \think\response\Json|void
  277. * @throws \think\db\exception\DataNotFoundException
  278. * @throws \think\db\exception\DbException
  279. * @throws \think\db\exception\ModelNotFoundException
  280. */
  281. public function reset_password_mobile(){
  282. $post=$this->request->post();
  283. $mobile = isset($post['mobile'])? trim($post['mobile']):"";
  284. if($mobile==""){
  285. return json_show(1001,"手机号不能为空");
  286. }
  287. if(checkMobile($mobile)==false){
  288. return json_show(1002,"手机号格式不正确!");
  289. }
  290. $code = isset($post['code'])? trim($post['code']):"";
  291. if($code==""){
  292. return json_show(1001,"验证码不能为空");
  293. }
  294. $username = isset($post['username'])?trim($post['username']):"";
  295. if($username==""){
  296. return json_show(1001,"参数username 不能为空");
  297. }
  298. $account = Db::name("account")->where("username","=",$username)->find();
  299. if($account['mobile']!=$mobile){
  300. return json_show(1004,"账户关联手机号不正确");
  301. }
  302. $password = isset($post['password'])?trim($post['password']):"";
  303. if($password==""){
  304. return json_show(1001,"新密码不能为空");
  305. }
  306. if(sha1($password.$account['salt'])==$account['password']){
  307. return json_show(1001,"新密码不能与原密码相同");
  308. }
  309. $codeinfo = Db::name("send_message")->where(["mobile"=>$mobile,"status"=>0,"msg_type"=>1])->find();
  310. if($code!=$codeinfo['code']){
  311. return json_show(1003,"验证码错误");
  312. }
  313. $codeinfo['status']=1;
  314. Db::name("send_message")->save($codeinfo);
  315. $account['salt']=makeSalt();
  316. $account['updatetime']=date("Y-m-d");
  317. $account['is_pass']=1;
  318. $account['password']=sha1($password.$account['salt']);
  319. $result=Db::name("account")->save($account);
  320. return $result?json_show(0,"密码修改成功"):json_show(1003,"密码修改失败");
  321. }
  322. }