123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447 |
- <?php
- declare (strict_types = 1);
- namespace app\controller;
- use app\model\Account;
- use app\model\AccountPlat;use think\facade\Cache;
- use think\Exception;
- use think\facade\Db;
- use think\App;
- use think\facade\Validate;
- class User extends Base
- {
- private $token_time = 0;// token 有效时间
- private $model =null;// token 有效时间
- public function __construct(App $app)
- {
- parent::__construct($app);
- $this->token_time= env("token.expire");
- $this->model = new Account();
- }
- /**注册接口
- * @param string username 账户名称
- * @param string password 账户密码
- * @param string mobile 账户手机号
- * @param string source 来源默认register
- * @return \think\response\Json|void
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function register()
- {
- $post =$this->request->only(["username"=>'',"password"=>"","mobile"=>"","source"=>"register"],"post","trim");
- $validate=Validate::rule([
- 'username|账户名称' => 'require|max:255',
- 'password|密码' => 'require|min:6|max:200',
- 'mobile|手机号' => 'require|number|length:11|mobile',
- ]);
- if($validate->check($post)==false) return json_show(1004,$validate->getError());
- $source = isset($post['source']) ? trim($post['source']):"";
- $uiq = Db::table("sys_account")->where(["username"=>$post['mobile']])->find();
- if($uiq){
- return json_show(1002,"账户名已存在!");
- }
- $uiq = Db::table("sys_account")->where(["mobile"=>$post['mobile']])->find();
- if($uiq){
- return json_show(1002,"手机号已注册!");
- }
- Db::startTrans();
- try {
- $salt =makeSalt();
- $password = sha1($post['password'].$salt);
- $data = [
- 'username'=>$post['mobile'],
- "password"=>$password,
- "salt"=>$salt,
- "mobile"=>$post['mobile'],
- "source"=>$source,
- "status"=>1,
- "addtime"=>date("Y-m-d H:i:s"),
- "updatetime"=>date("Y-m-d H:i:s")
- ];
- $reuslt = Db::table('sys_account')->insert($data,true);
- if($reuslt){
- $data=[
- "nickname"=>$post['username'],
- "mobile"=>$post['mobile'],
- "email"=>"",
- "portrait"=>"",
- "sex"=>1,
- "post"=>"",
- "department"=>"",
- "account_id"=>$reuslt,
- "status"=>1,
- "addtime"=>date("Y-m-d H:i:s"),
- "updatetime"=>date("Y-m-d H:i:s")
- ];
- $user=Db::table("sys_user")->insert($data,true);
- if($user){
- Db::commit();
- return json_show(0,"账户注册成功");
- }
- }
- Db::rollback();
- return json_show(1002,"账户注册失败");
- }catch (\Exception $e){
- Db::rollback();
- return json_show(1002,"账户注册失败".$e->getMessage());
- }
- }
- /**
- * 显示创建资源表单页.
- *
- * @return \think\Response
- */
- public function verify_code()
- {
- $post = $this->request->only("mobile","post");
- $code = make_verify();
- $mobile = isset($post['mobile'])&&checkMobile($post['mobile']) ? $post['mobile'] :"" ;
- if($mobile==""){
- return json_show(1001,"手机号格式不正确");
- }
- $mess =Db::name("send_message")->where(['mobile'=>$mobile,"status"=>0,"msg_type"=>1])->find();
- if($mess){
- if($mess['expire']>time()-60){
- return json_show(1001,"验证码发送中!");
- }
- $mess['status']=1;
- Db::name("send_message")->save($mess);
- }
- // $sendJson = sendMessage($mobile, $code);
- // $sendResult = json_decode($sendJson, TRUE);
- // if($sendResult['description'] != 'Success') {
- // return json_show(1002, '短信发送失败,请重试');
- // }
- $data=['code'=>$code,"mobile"=>$mobile,"status"=>0,"msg_type"=>1,"addtime"=>date("Y-m-d H:i:s"),
- "expire"=>time()];
- $result = Db::name("send_message")->insert($data);
- return $result ? json_show(0,"验证码已发送",["code"=>$code]): json_show(1001,"验证码发送失败");
- }
- /**
- * @param string username 账户
- * @param string password 密码
- * @param string plat_code 来源
- * @return \think\response\Json
- * @throws \Psr\SimpleCache\InvalidArgumentException
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function login()
- {
- $post = $this->request->only(["username" => "", "password" => "", "plat_code" => "","openId"=>""], "post", "trim");
- $validate = Validate::rule([
- 'username|账户名称' => 'require|max:255',
- 'password|密码' => 'require|min:6|max:200',
- ]);
- if ($validate->check($post) == false) $this->error($validate->getError(),1004);
- $acc = $this->model->withJoin(["userinfo","accountitem"],"left")
- ->where(['username' => $post['username']])
- ->findOrEmpty();
- if ($acc->isEmpty()) return json_show(1003, '账户名不存在');
- if ($acc['status'] == Account::$account_end)$this->error('账户已禁用',1003);
- $sha1 = sha1($post['password'] . $acc['salt']);
- if ($sha1 != $acc['password']) $this->error('账户或密码错误',1003);
- $userinfo=[
- "id"=>$acc->id,
- "username"=>$acc->username,
- "mobile"=>$acc->mobile,
- "source"=>$acc->source,
- "nickname"=>$acc->userinfo->nickname,
- "sex"=>$acc->userinfo->sex,
- "email"=>$acc->userinfo->email,
- "level"=>$acc->level,
- "itemid"=>$acc->accountitem->itemid??0,
- "position"=>$acc->accountitem->position??'',
- "depart_name"=>$acc->depart_name,
- "company_relaton"=>$acc->company_relaton,
- "system_version"=>(new AccountPlat())->where(['account_id'=>$acc->id])->column('system_version','plat_code')
- ];
-
- if($post['openId']!=''){
- if($acc->userinfo->openId!='')$this->error('账户信息已绑定微信请先解除',1004);
- $acc->userinfo->openId=$post['openId'];
- $this->model->userinfo()->save($acc->userinfo->toArray());
- }
- $token = makeToken($userinfo);
- if ($token == "") $this->error('token生成失败',1003);
- $cache = Cache::store("redis")->set("user:info:{$token}", $userinfo, $this->token_time);
- if ($cache == false)$this->error('token保存失败',1003);
- $userinfo['token'] = $token;
- $this->success("登录成功", $userinfo,0);
- }
- /**
- *钉钉登录接口
- *
- * @param \think\Request $request
- * @param string $code
- * @return \think\Response
- */
- public function DingTalk()
- {
- $config= config("dingtalk");
- $dingtalk =new \DingTalk($config);
- $post = $this->request->only(["code"=>""],"post","trim");
- $code=isset($post["code"])&&$post["code"]!="" ? $post["code"]:"";
- if($code==""){
- return json_show(106,"参数code不能为空");
- }
- $li = $dingtalk->getUserByCode($code);
- if($li['errcode']!=0){
- return json_show(107,"授权失败",$li);
- }
- $list = $dingtalk->getUser($li['userid']);
- if($list['errcode']!=0){
- return json_show(107,"授权失败",$list);
- }
- $userinfo = Db::name("account")->alias("a")
- ->leftJoin("user b","a.id=b.account_id and b.status=1")
- ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
- ->where(['DTuserid'=>$list['userid'],"unionid"=>$list['unionid'],"a.is_del"=>0])
- ->findOrEmpty();
- if(empty($userinfo)){
- Db::startTrans();
- try{
- $accountid = $this->DingTalkRegister($list);
- Db::commit();
- }catch (\Exception $e){
- Db::rollback();
- return json_show(106,$e->getMessage());
- }
- $userinfo = Db::name("account")->alias("a")
- ->leftJoin("user b","a.id=b.account_id and b.status=1")
- ->field("a.id,a.username,a.mobile,a.source,b.nickname,b.sex,b.email,a.addtime,a.updatetime")
- ->where(["a.id"=>$accountid,"a.is_del"=>0])
- ->findOrEmpty();
- }
- $token = makeToken($userinfo);
- $usercompany = Db::name("account_company")->where(["account_id"=>$userinfo['id'],"is_del"=>0,"status"=>1])
- ->column("companyCode,companyName,company_type,is_main,status");
- $user['company_relaton'] = $usercompany;
- $cache = Cache::store("redis")->set("user:info:{$token}",$user ,$this->token_time);
- if($cache==false) return json_show(1003,'token保存失败');
- $user['token']=$token;
- return json_show(0,"授权成功",$userinfo);
- }
- /**
- * @param $Dingtalinfo
- * @return int|string
- * @throws \think\Exception
- */
- private function DingTalkRegister($Dingtalinfo){
- $salt=makeSalt();
- $data=[
- "username"=>$Dingtalinfo['mobile'],
- "password"=>sha1("dingding123".$salt),
- "mobile"=>$Dingtalinfo['mobile'],
- "salt"=>$salt,
- "status"=>1,
- "source"=>"dingtalk",
- "addtime"=>date("Y-m-d H:i:s"),
- "updatetime"=>date("Y-m-d H:i:s")
- ];
- $account = Db::table("sys_account")->insert($data,true);
- if($account<=0)throw new Exception("账户创建失败");
- $verify = Db::name("user")->where("mobile","=",$Dingtalinfo['mobile'])->findOrEmpty();
- if(!empty($verify)){
- $verify['unionid']=$Dingtalinfo['unionid'];
- $verify['openId']=$Dingtalinfo['openId'];
- $verify['DTuserid']=$Dingtalinfo['userid'];
- $verify['mobile']=$Dingtalinfo['mobile'];
- $verify['account_id']=$account;
- isset($verify['portrait'])??$verify['portrait']=$Dingtalinfo['avatar'];
- isset($verify['email'])??$verify['email']=$Dingtalinfo['email'];
- $verify['updatetime']=date("Y-m-d H:i:s");
- $user =Db::name("user")->save($verify);
- if($user==false) throw new Exception("用户信息创建失败");
- $uid = $verify["id"];
- }else{
- $data=[
- "nickname"=>$Dingtalinfo['name'],
- "mobile"=>$Dingtalinfo['mobile'],
- "email"=>$Dingtalinfo['email'],
- "portrait"=>$Dingtalinfo['avatar'],
- "sex"=>1,
- "post"=>"",
- "unionid"=>$Dingtalinfo['unionid'],
- "openId"=>$Dingtalinfo['openId'],
- "DTuserid"=>$Dingtalinfo['userid'],
- "department"=>"",
- "status"=>1,
- "account_id"=>$account,
- "addtime"=>date("Y-m-d H:i:s"),
- "updatetime"=>date("Y-m-d H:i:s")
- ];
- $uid =Db::name("user")->insert($data,true);
- }
- if($uid==false) throw new Exception("用户信息创建失败");
- return $account;
- }
- /**
- * @return \think\response\Json
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function verify_token()
- {
- $post = $this->request->only(["token" => ''], "post");
- $validate = Validate::rule(['token' => 'require']);
- if ($validate->check($post) == false) return json_show(1004, $validate->getError());
- $getToken = checkToken($post['token'], $this->token_time);
- if( $getToken == false)$this->error('token失效','104');
- else{
- $getToken['system_version']=(new AccountPlat())->where(['account_id'=>$getToken['id']])->column
- ('system_version','plat_code');
- $this->success('获取成功',$getToken,0);
- }
- }
- /**
- * @return \think\response\Json|void
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function reset_password_mobile(){
- $post=$this->request->post();
- $mobile = isset($post['mobile'])? trim($post['mobile']):"";
- if($mobile==""){
- return json_show(1001,"手机号不能为空");
- }
- if(checkMobile($mobile)==false){
- return json_show(1002,"手机号格式不正确!");
- }
- $code = isset($post['code'])? trim($post['code']):"";
- if($code==""){
- return json_show(1001,"验证码不能为空");
- }
- $username = isset($post['username'])?trim($post['username']):"";
- if($username==""){
- return json_show(1001,"参数username 不能为空");
- }
- $account = Db::name("account")->where("username","=",$username)->find();
- if($account['mobile']!=$mobile){
- return json_show(1004,"账户关联手机号不正确");
- }
- $password = isset($post['password'])?trim($post['password']):"";
- if($password==""){
- return json_show(1001,"新密码不能为空");
- }
- if(sha1($password.$account['salt'])==$account['password']){
- return json_show(1001,"新密码不能与原密码相同");
- }
- $codeinfo = Db::name("send_message")->where(["mobile"=>$mobile,"status"=>0,"msg_type"=>1])->find();
- if($code!=$codeinfo['code']){
- return json_show(1003,"验证码错误");
- }
- $codeinfo['status']=1;
- Db::name("send_message")->save($codeinfo);
- $account['salt']=makeSalt();
- $account['updatetime']=date("Y-m-d");
- $account['is_pass']=1;
- $account['password']=sha1($password.$account['salt']);
- $result=Db::name("account")->save($account);
- return $result?json_show(0,"密码修改成功"):json_show(1003,"密码修改失败");
- }
-
- public function AccountQuery(){
- $param = $this->request->only(['nickname' => '', 'username' => '',"is_wx"=>"",'level'=>'', 'status' => '',
- 'page'=> 1,'size'=>30], 'post', 'trim');
- $where=[];
- $param['nickname']==''?: $where[]=['userinfo.nickname','like',"%{$param['nickname']}%"];
- $param['is_wx']===''?: $where[]=['userinfo.openId', $param['is_wx']==0?"=":"<>",""];
- $param['status']==''?: $where[]=['account.status','=',$param['status']];
- $param['level']==''?: $where[]=['account.level','=',$param['level']];
- $param['username']==''?: $where[]=['username','like',"%{$param['username']}%"];
- $acc = $this->model->withJoin(['userinfo'],"left")->where($where)->order('id desc')
- ->paginate(['page'=>$param['page'],'list_rows'=>$param['size']]);
- $tenmp=[];
- foreach ($acc->items() as $value){
- $temp=[];
- $temp['id'] = $value->id;
- $temp['nickname'] = $value->nickname;
- $temp['mobile'] = substr_replace($value->mobile,"****",-4);
- $temp['is_wx'] = $value->is_wx;
- $temp['status'] = $value->status;
- $tenmp[]=$temp;
- }
- $this->success('获取成功',['list'=>$tenmp,'count'=>$acc->total()],0);
- }
-
-
- public function BindWx(){
- $param = $this->request->only(['id' => '', 'openId' => '','lastCode'=>''], 'post', 'trim');
- $valid =Validate::rule(["id|账户主键"=>"require|number|egt:0","openId|微信openid"=>"require|max:255","lastCode|手机号后四位"=>"require|number|length:4"]);
- if($valid->check($param)==false) $this->error($valid->getError());
- $acc = $this->model->withJoin(['userinfo','accountitem'],'left')->findOrEmpty($param['id']);
- if($acc->isEmpty())$this->error("账户信息不存在",1004);
- if($acc->userinfo->openId!='')$this->error("账户信息已绑定微信请先解除",1004);
- if(substr($acc->mobile,-4,4)!=$param['lastCode'])$this->error('手机后四位不正确!',1004);
- if($param['openId']!==''&& $acc->userinfo->openId!=$param['openId'] ){
- $acc->userinfo->openId=$param['openId'];
- $this->model->userinfo()->save($acc->userinfo->toArray());
- }
- $userinfo=[
- 'id'=>$acc->id,
- 'username'=>$acc->username,
- 'mobile'=>$acc->mobile,
- 'source'=>$acc->source,
- 'nickname'=>$acc->userinfo->nickname,
- 'sex'=>$acc->userinfo->sex,
- 'email'=>$acc->userinfo->email,
- 'level'=>$acc->level,
- 'itemid'=>$acc->accountitem->itemid??0,
- 'position'=>$acc->accountitem->position??'',
- 'depart_name'=>$acc->depart_name,
- 'company_relaton'=>$acc->company_relaton,
- 'system_version'=>(new AccountPlat())->where(['account_id'=>$acc->id])->column('system_version','plat_code')
- ];
- $token = makeToken($userinfo);
- if ($token == '') $this->error('token生成失败',1003);
- $cache = Cache::store('redis')->set("user:info:{$token}", $userinfo, $this->token_time);
- if ($cache == false)$this->error('token保存失败',1003);
- $userinfo['token'] = $token;
- $this->success('获取成功',$userinfo,0);
- }
- /**
- * 系统板本更新
- */
- public function setSystemVer(){
- $param = $this->request->only(['account_id' => '', 'plat_code' => '','system_version'=>''], 'post', 'trim');
- $valid =Validate::rule([
- 'account_id|账户主键'=>'require|number|egt:0',
- 'plat_code|系统类型'=>'require|max:255|in:cx,st',
- 'system_version|系统更新版本号'=>'require'
- ]);
- if($valid->check($param)==false) $this->error($valid->getError());
- $accountPlat= new AccountPlat();
- $info =$accountPlat->where($param)->findOrEmpty();
- if($info->isEmpty()==false) $this->error('记录信息已存在',1003);
- $accountPlat->where(["account_id"=>$param['account_id'],"plat_code"=>$param['plat_code']])->select()->delete();
- $pl= $accountPlat->save($param);
- $pl? $this->success('记录成功',[],0): $this->error('记录失败',1003);;
- }
- }
|