Kaynağa Gözat

Merge branch 'dev' of wugg/useraccount into master

wugg 1 yıl önce
ebeveyn
işleme
5cf4aac748

+ 57 - 0
app/controller/Base.php

@@ -0,0 +1,57 @@
+<?php
+
+
+namespace app\controller;
+
+
+use think\App;
+use think\Response;
+use think\exception\HttpResponseException;
+class Base extends \app\BaseController{
+	public function __construct(App $app) {parent::__construct($app);}
+	     /**
+	* @param string $message
+	* @param int $code
+	* @param null $data
+	 */
+    public function error($message='',$code=0,$data=null){
+        $this->result($message,$data,$code);
+    }
+    /**
+	* @param string $message
+	* @param int $code
+	* @param null $data
+	 */
+     public function success($message='',$data=null,$code=1){
+        $this->result($message,$data,$code);
+    }
+    
+     /**
+	* @param string $msg
+	* @param null $data
+	* @param int $code
+	* @param string|null $type
+	* @param array $header
+	* @param array $options
+	 */
+    private function result(string $msg, $data = null, int $code = 0, string $type = null, array $header = [], array
+    $options = [])
+    {
+        $result = [
+            'code' => $code,
+            'message'  => $msg,
+            'data' => $data,
+        ];
+        // 如果未设置类型则自动判断
+        $type = 'json';
+
+        $code = 200;
+        if (isset($header['statuscode'])) {
+            $code = $header['statuscode'];
+            unset($header['statuscode']);
+        }
+         $response = Response::create($result, $type, $code)->header($header)->options($options);
+         throw new HttpResponseException($response);
+    }
+	
+}

+ 99 - 44
app/controller/User.php

@@ -3,20 +3,22 @@ declare (strict_types = 1);
 
 namespace app\controller;
 
-use app\BaseController;
 use app\model\Account;
 use think\facade\Cache;
-use think\Exception;use think\facade\Db;
+use think\Exception;
+use think\facade\Db;
 use think\App;
 use think\facade\Validate;
 
-class User extends BaseController
+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 账户名称
@@ -128,11 +130,12 @@ class User extends BaseController
     }
 
 	/**
-    * @param string username 账户
+	* @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
@@ -140,53 +143,46 @@ class User extends BaseController
 	 */
     public function login()
     {
-        $post = $this->request->only(["username" => "", "password" => "", "plat_code" => ""], "post", "trim");
+        $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) return json_show(1004, $validate->getError());
-
-        $acc = Db::name("account")
-            ->where(['username' => $post['username'], "is_del" => Account::$account_del])
-            ->find();
-        if ($acc == false) return json_show(1003, '账户名不存在');
+        if ($validate->check($post) == false) $this->error($validate->getError(),1004);
 
-        if ($acc['status'] == Account::$account_end) return json_show(1003, '账户已禁用');
+        $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']) return json_show(1003, '账户或密码错误');
-
-        $token = makeToken($acc);
-        if ($token == "") return json_show(1003, 'token生成失败');
-
-        //account_plat 是空表
-//        if ($post['plat_code'] != "") {
-//            $platinfo = Db::name("account_plat")
-//                ->alias("a")
-//                ->leftJoin("platform b", "a.plat_code=b.plat_code and b.is_del=0 and b.status=1")
-//                ->where(["a.status" => 1, "a.is_del" => 0, "a.plat_code" => $post['plat_code'], "a.account_id" => $acc['id']])
-//                ->findOrEmpty();
-//            if (empty($platinfo)) return json_show(1003, '该系统账号未开通登录');
-//
-//        }
-        $user = Db::name("account")
-            ->alias("a")
-            ->leftJoin("user b", "a.id=b.account_id and b.status=1")
-            ->leftJoin("account_item c", "c.account_id=a.id")
-            ->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")
-            ->where(["a.id" => $acc["id"]])
-            ->find();
-        if ($user == false) return json_show(1003, '用户信息不存在');
-
-        $usercompany = Db::name("account_company")
-            ->where(["account_id" => $user['id'], "is_del" => 0, "status" => 1])
-            ->column("companyCode,companyCode companyNo,companyName,companyName company_name,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, "登录成功", $user);
+        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,
+        	];
+       
+        if($post['openId']!=''&& $acc->userinfo->openId!=$post['openId'] ){
+	        $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);
     }
 
     /**
@@ -363,4 +359,63 @@ class User extends BaseController
         $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,
+        	];
+   	   $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);
+   }
 }

+ 65 - 0
app/controller/WeChat.php

@@ -0,0 +1,65 @@
+<?php
+namespace app\controller;
+
+use app\model\Account;use think\App;
+use think\facade\Cache;use think\facade\Validate;
+class WeChat  extends  Base {
+	private $wechat=null;
+	private $token_time=3600;
+	protected $isLogin = 0;
+	 public function __construct(App $app)
+    {
+        parent::__construct($app);
+        $wechat_conf=['appid'=>env('WECHAT.APPID'),'appsecret'=>env('WECHAT.APPSECRET')];
+		$this->wechat=new \Wechat($wechat_conf);
+		$this->token_time= env('token.expire');
+    }
+    
+    public function WebAuth(){
+	 	$code =$this->request->only(['code'=>''],'post','trim');
+		$valid =Validate::rule([
+			'code|微信授权Code'=>'require|max:255|min:5',
+			]);
+		if($valid->check($code)==false) $this->error($valid->getError());
+		
+		$uid =$this->wechat->getAccessTokenByCode($code['code']);
+		if($uid==false){
+			$this->error('未获取到用户数据');
+		}
+		if(!isset($uid['openid'])|| $uid['openid']=='')	$this->error('用户openid 未获取到');
+		$userinfo = $this->checkOpendId($uid['openid']);
+		$wxinfo = $this->wechat->getUserInfo($uid['openid']);
+		$this->success("获取成功",["wxinfo"=>$wxinfo,"userinfo"=>$userinfo,"isLogin"=>$this->isLogin]);
+		
+    }
+    	//网页端调用jssdk配置config
+	public function getConfig(){
+		$url =$this->request->only(['url'=>''],'post','trim');
+		$valid =Validate::rule(['url|微信授权地址'=>'require|max:255|min:5']);
+		if($valid->check($url)==false)$this->error($valid->getError());
+		$baseconfig =$this->wechat->getJsTicket();
+		if($baseconfig==false){
+			$this->error('签名获取失败');
+		}
+		$baseconfig =$this->wechat->getJsSign($url['url']);
+		if($baseconfig==false){
+			$this->error('签名获取失败');
+		}
+		$this->success('获取成功',$baseconfig);
+	}
+	
+	protected function checkOpendId($openId){
+		$account =new Account();
+		$isT = $account->withJoin(["userinfo","accountitem"],"left")
+		->where(["openId"=>$openId])
+		->findOrEmpty();
+		if($isT->isEmpty())return [];
+		$token = makeToken($isT);
+		$cache = Cache::store('redis')->set("user:info:{$token}", $isT->toArray(), $this->token_time);
+		if ($cache == false) return [];
+        $isT['token'] = $token;
+        $this->isLogin=1;
+        return $isT;
+	}
+	
+}

+ 23 - 6
app/middleware/CheckAuth.php

@@ -6,6 +6,14 @@ namespace app\middleware;
 use think\facade\Db;
 class CheckAuth
 {
+	protected $noCheck=[];
+	// header头配置
+	protected $header = [
+		'Access-Control-Allow-Credentials' => 'true',
+		'Access-Control-Max-Age'           => 1800,
+		'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
+		'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token',
+	];
     /**
      * 处理请求
      *
@@ -18,12 +26,21 @@ class CheckAuth
     	if($request->isOptions()){
     		return json();
     	}
-    	$header =$request->header();
-    	$param =$request->post();
-    	$check =$this->check($header,$param);
-    	 if($check['code']==1){
-	    	return json_show(104,$check['msg']);
-		}
+//    	$header =$request->header();
+//	    $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
+//	    if (!isset($header['Access-Control-Allow-Origin'])) {
+//		    $origin = $request->header('origin');
+//		    $header['Access-Control-Allow-Origin'] = $origin;
+//	    }
+//
+	    $param =$request->post();
+//    	if($header['is_strict_login']==True){
+//    	    $check =$this->check($header,$param);
+//	         if($check['code']==1){
+//		        return json_show(104,$check['msg']);
+//			}
+//    	}
+    
        return $next($request);
     }
 

+ 35 - 1
app/model/Account.php

@@ -13,5 +13,39 @@ class Account extends Model
 	public static $account_start=1;
 	public static $account_end=0;
 	public static $account_del=0;
-
+	protected $globalScope=['Del'];
+	protected $append=['depart_name','company_relaton',"is_wx"];
+	
+    public function scopeDel($query){
+        $query->where('is_del',0);
+	}
+	
+	public function getDepartNameAttr($v,$row){
+        $item = new AccountItem();
+        $depart=$item->where(['account_id'=>$row['id']])->with(['depart'])->findOrEmpty();
+        return $depart->isEmpty()?'':$depart->depart_name;
+	}
+	
+	public function getCompanyRelatonAttr($v,$row){
+        $item = new AccountCompany();
+        $company=$item->where(['account_id'=>$row['id'],'is_del' => 0, 'status' => 1])->column("companyCode,companyCode companyNo,companyName,companyName company_name,company_type,is_main,status");
+        return $company;
+	}
+	public function UserInfo(){
+    	return $this->belongsTo(User::class,'id','account_id')->bind(["nickname","openId"]);
+	}
+	
+	public function AccountItem(){
+    	return $this->belongsTo(AccountItem::class,'id','account_id')->bind(["itemid"]);
+	}
+	
+	public function getIsWxAttr($v,$row){
+		return $row['openId']==''?0:1;
+	}
+	
+	public function setIsWxAttr($v,$data){
+		if($v==0){
+			$this->UserInfo()->where('account_id',$data['id'])->update(['openId'=>'']);
+		}
+	}
 }

+ 16 - 0
app/model/AccountItem.php

@@ -0,0 +1,16 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\model;
+
+use think\Model;
+
+/**
+ * @mixin \think\Model
+ */
+class AccountItem extends Model
+{
+      public function depart(){
+    	return $this->belongsTo(CompanyItem::class,'itemid','id')->bind(['depart_name'=>'name']);
+    }
+}

+ 14 - 0
app/model/CompanyItem.php

@@ -0,0 +1,14 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\model;
+
+use think\Model;
+
+/**
+ * @mixin \think\Model
+ */
+class CompanyItem extends Model
+{
+    //
+}

+ 14 - 0
app/model/User.php

@@ -0,0 +1,14 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\model;
+
+use think\Model;
+
+/**
+ * @mixin \think\Model
+ */
+class User extends Model
+{
+    //
+}

+ 1 - 1
config/cache.php

@@ -6,7 +6,7 @@
 
 return [
     // 默认缓存驱动
-    'default' => env('cache.driver', 'file'),
+    'default' => env('cache.driver', 'redis'),
 
     // 缓存连接方式配置
     'stores'  => [

+ 1 - 1
config/database.php

@@ -34,7 +34,7 @@ return [
             // 端口
             'hostport'        => env('database.hostport', '3306'),
             // 数据库连接参数
-            'params'          => [],
+           'params'          => [\PDO::ATTR_STRINGIFY_FETCHES=>true],
             // 数据库编码默认采用utf8
             'charset'         => env('database.charset', 'utf8'),
             // 数据库表前缀

+ 8 - 1
public/index.php

@@ -11,7 +11,14 @@
 
 // [ 应用入口文件 ]
 namespace think;
-
+header('Access-Control-Allow-Origin:*');
+header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');
+header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization,sign,appid,noce,timestamp');
+// 执行HTTP应用并响应
+if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
+    echo '';
+    exit();
+}
 require __DIR__ . '/../vendor/autoload.php';
 
 // 执行HTTP应用并响应

+ 4 - 3
route/app.php

@@ -14,6 +14,8 @@ Route::rule('login', 'User/login');
 Route::rule('verifyToken', 'User/verify_token');
 Route::rule('register', 'User/register');
 Route::rule('dingTalk', 'User/DingTalk');
+Route::rule('accountquery', 'User/AccountQuery');
+Route::rule('bindwx', 'User/BindWx');
 
 Route::rule('userlist', 'UserInfo/UserList');
 Route::rule('usersave', 'UserInfo/UserSave');
@@ -24,8 +26,6 @@ Route::rule('setcompany', 'UserInfo/setCompany');
 Route::rule('companystatus', 'UserInfo/setCompanyStatus');
 Route::rule('useradd', 'UserInfo/userAdd');
 Route::rule('userall', 'UserInfo/userAll');
-//Route::rule('add_admin_account', 'UserInfo/addAdminAccount');
-//Route::rule('add_supplier_account', 'UserInfo/addSupplierAccount');
 Route::rule('userDelete', 'UserInfo/userDelete');
 Route::rule('userlistbycompany', 'UserInfo/UserListByCompany');
 Route::rule('passSetByPassword', 'UserInfo/passSetByPassword');
@@ -93,4 +93,5 @@ Route::rule('ciinfo', 'CompanyItem/info');
 Route::rule('get_company_name_by_uid', 'CompanyItem/getCompanyNameByUid');//获取用户id对应的部门名称
 Route::rule('get_company_item_user_by_name', 'CompanyItem/getCompanyItemUserByName');//获取部门名称下的所有用户
 
-
+Route::rule("webAuth","WeChat/WebAuth");
+Route::rule("getConfig","WeChat/getConfig");