diff --git a/application/controllers/qcloud/minaauth/Auth.php b/application/controllers/qcloud/minaauth/Auth.php new file mode 100644 index 0000000..6564bab --- /dev/null +++ b/application/controllers/qcloud/minaauth/Auth.php @@ -0,0 +1,322 @@ +select_cappinfo(); + if (empty($cappinfo_data) || ($cappinfo_data == false)) { + $ret['returnCode'] = return_code::MA_NO_APPID; + $ret['returnMessage'] = 'NO_APPID'; + $ret['returnData'] = ''; + } else { + $appid = $cappinfo_data['appid']; + $secret = $cappinfo_data['secret']; + $ip = $cappinfo_data['ip']; + $qcloud_appid = $cappinfo_data['qcloud_appid']; + $login_duration = $cappinfo_data['login_duration']; + $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code'; + $http_util = new http_util(); + $return_message = $http_util->http_get($url); + if ($return_message!=false) { + $json_message = json_decode($return_message, true); + if (isset($json_message['openid']) && isset($json_message['session_key']) && isset($json_message['expires_in'])) { + $skey = md5(time() . mt_rand(1, 1000000)); + $create_time = time(); + $last_visit_time = time(); + $openid = $json_message['openid']; + $session_key = $json_message['session_key']; + $decrypt_data = new decrypt_data(); + $user_info = $decrypt_data->aes128cbc_Decrypt($encrypt_data, $session_key); + + if ($user_info === false) { + $ret['returnCode'] = return_code::MA_DECRYPT_ERR; + $ret['returnMessage'] = 'DECRYPT_FAIL'; + $ret['returnData'] = ''; + } else { + + $params = array( + "skey" => $skey, + "create_time" => $create_time, + "last_visit_time" => $last_visit_time, + "openid" => $openid, + "session_key" => $session_key, + "user_info" => $user_info, + "login_duration" => $login_duration + ); + + $csessioninfo_service = new Csessioninfo_Service(); + $change_result = $csessioninfo_service->change_csessioninfo($params); + if ($change_result === true) { + $id = $csessioninfo_service->get_id_csessioninfo($openid); + $arr_result['id'] = $id; + $arr_result['skey'] = $skey; + $arr_result['user_info'] = json_decode($user_info); + $arr_result['duration'] = $json_message['expires_in']; + $ret['returnCode'] = return_code::MA_OK; + $ret['returnMessage'] = 'NEW_SESSION_SUCCESS'; + $ret['returnData'] = $arr_result; + } else if ($change_result === false) { + $ret['returnCode'] = return_code::MA_CHANGE_SESSION_ERR; + $ret['returnMessage'] = 'CHANGE_SESSION_ERR'; + $ret['returnData'] = ''; + } else { + $arr_result['id'] = $change_result; + $arr_result['skey'] = $skey; + $arr_result['user_info'] = json_decode($user_info); + $arr_result['duration'] = $json_message['expires_in']; + $ret['returnCode'] = return_code::MA_OK; + $ret['returnMessage'] = 'UPDATE_SESSION_SUCCESS'; + $ret['returnData'] = $arr_result; + } + } + } else if (isset($json_message['errcode']) && isset($json_message['errmsg'])) { + $ret['returnCode'] = return_code::MA_WEIXIN_CODE_ERR; + $ret['returnMessage'] = 'WEIXIN_CODE_ERR'; + $ret['returnData'] = ''; + } else { + $ret['returnCode'] = return_code::MA_WEIXIN_RETURN_ERR; + $ret['returnMessage'] = 'WEIXIN_RETURN_ERR'; + $ret['returnData'] = ''; + } + } else { + $ret['returnCode'] = return_code::MA_WEIXIN_NET_ERR; + $ret['returnMessage'] = 'WEIXIN_NET_ERR'; + $ret['returnData'] = ''; + } + + /** + * 上报数据部分 + */ + $report_data = new ready_for_report_data(); + + $arr_report_data = array( + "ip"=>$ip, + "appid"=>$qcloud_appid, + "login_count"=>0, + "login_sucess"=>0, + "auth_count"=>0, + "auth_sucess"=>0 + ); + + if($report_data->check_data()){ + $report_data->ready_data("login_count"); + }else{ + $arr_report_data['login_count']=1; + $report_data->write_report_data(json_encode($arr_report_data)); + } + if($ret['returnCode']==0){ + if($report_data->check_data()){ + $report_data->ready_data("login_sucess"); + }else{ + $arr_report_data['login_count']=1; + $arr_report_data['login_sucess']=1; + $report_data->write_report_data(json_encode($arr_report_data)); + } + } + } + return $ret; + } + + /** + * @param $id + * @param $skey + * @return bool + * 描述:登录态验证 + */ + public function auth($id, $skey) + { + //根据Id和skey 在cSessionInfo中进行鉴权,返回鉴权失败和密钥过期 + $cappinfo_service = new Cappinfo_Service(); + $cappinfo_data = $cappinfo_service->select_cappinfo(); + if (empty($cappinfo_data) || ($cappinfo_data == false)) { + $ret['returnCode'] = return_code::MA_NO_APPID; + $ret['returnMessage'] = 'NO_APPID'; + $ret['returnData'] = ''; + } else { + $login_duration = $cappinfo_data['login_duration']; + $session_duration = $cappinfo_data['session_duration']; + $ip = $cappinfo_data['ip']; + $qcloud_appid = $cappinfo_data['qcloud_appid']; + + $params = array( + "id" => $id, + "skey" => $skey, + "login_duration" => $login_duration, + "session_duration" => $session_duration + ); + + $csessioninfo_service = new Csessioninfo_Service(); + $auth_result = $csessioninfo_service->check_session_for_auth($params); + if ($auth_result!==false) { + $arr_result['user_info'] = json_decode($auth_result); + $ret['returnCode'] = return_code::MA_OK; + $ret['returnMessage'] = 'AUTH_SUCCESS'; + $ret['returnData'] = $arr_result; + } else { + $ret['returnCode'] = return_code::MA_AUTH_ERR; + $ret['returnMessage'] = 'AUTH_FAIL'; + $ret['returnData'] = ''; + } + + /** + * 上报数据部分 + */ + $report_data = new ready_for_report_data(); + + $arr_report_data = array( + "ip"=>$ip, + "appid"=>$qcloud_appid, + "login_count"=>0, + "login_sucess"=>0, + "auth_count"=>0, + "auth_sucess"=>0 + ); + + if($report_data->check_data()){ + $report_data->ready_data("auth_count"); + }else{ + $arr_report_data['auth_count']=1; + $report_data->write_report_data(json_encode($arr_report_data)); + } + if($ret['returnCode']==0){ + if($report_data->check_data()){ + $report_data->ready_data("auth_sucess"); + }else{ + $arr_report_data['auth_count']=1; + $arr_report_data['auth_sucess']=1; + $report_data->write_report_data(json_encode($arr_report_data)); + } + } + + } + return $ret; + } + + /** + * @param $id + * @param $skey + * @param $encrypt_data + * @return bool|string + * 描述:解密数据 + */ + public function decrypt($id, $skey, $encrypt_data) + { + //1、根据id和skey获取session_key。 + //2、session_key获取成功则正常解密,可能解密失败。 + //3、获取不成功则解密失败。 + $csessioninfo_service = new Csessioninfo_Service(); + $params = array( + "id" => $id, + "skey" => $skey + ); + $result = $csessioninfo_service->select_csessioninfo($params); + if ($result !== false && count($result) != 0 && isset($result['session_key'])) { + $session_key = $result['session_key']; + $decrypt_data = new decrypt_data(); + $data = $decrypt_data->aes128cbc_Decrypt($encrypt_data, $session_key); + if ($data !== false) { + $ret['returnCode'] = return_code::MA_OK; + $ret['returnMessage'] = 'DECRYPT_SUCCESS'; + $ret['returnData'] = $data; + } else { + $ret['returnCode'] = return_code::MA_DECRYPT_ERR; + $ret['returnMessage'] = 'GET_SESSION_KEY_SUCCESS_BUT_DECRYPT_FAIL'; + $ret['returnData'] = ''; + } + } else { + $ret['returnCode'] = return_code::MA_DECRYPT_ERR; + $ret['returnMessage'] = 'GET_SESSION_KEY_FAIL'; + $ret['returnData'] = ''; + } + return $ret; + } + + public function init_data($appid,$secret,$qcloud_appid,$ip,$cdb_ip,$cdb_port,$cdb_user_name,$cdb_pass_wd){ + $init_db = new init_db(); + $params_db = array( + "cdb_ip"=>$cdb_ip, + "cdb_port"=>$cdb_port, + "cdb_user_name" => $cdb_user_name, + "cdb_pass_wd" => $cdb_pass_wd + ); + if($init_db->init_db_config($params_db)){ + if($init_db->init_db_table()){ + $cappinfo_service = new Cappinfo_Service(); + $cappinfo_data = $cappinfo_service->select_cappinfo(); + $params = array( + "appid"=>$appid, + "secret"=>$secret, + "qcloud_appid"=>$qcloud_appid, + "ip"=>$ip + ); + + if(empty($cappinfo_data)){ + if($cappinfo_service->insert_cappinfo($params)) + { + $ret['returnCode'] = return_code::MA_OK; + $ret['returnMessage'] = 'INIT_APPINFO_SUCCESS'; + $ret['returnData'] = ''; + }else{ + $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR; + $ret['returnMessage'] = 'INIT_APPINFO_FAIL'; + $ret['returnData'] = ''; + } + }else if($cappinfo_data != false){ + $cappinfo_service->delete_cappinfo(); + if($cappinfo_service->insert_cappinfo($params)) + { + $ret['returnCode'] = return_code::MA_OK; + $ret['returnMessage'] = 'INIT_APPINFO_SUCCESS'; + $ret['returnData'] = ''; + }else{ + $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR; + $ret['returnMessage'] = 'INIT_APPINFO_FAIL'; + $ret['returnData'] = ''; + } + }else{ + $ret['returnCode'] = return_code::MA_MYSQL_ERR; + $ret['returnMessage'] = 'MYSQL_ERR'; + $ret['returnData'] = ''; + } + } + else{ + $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR; + $ret['returnMessage'] = 'INIT_APPINFO_FAIL'; + $ret['returnData'] = ''; + } + + }else{ + $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR; + $ret['returnMessage'] = 'INIT_APPINFO_FAIL'; + $ret['returnData'] = ''; + } + return $ret; + } +} \ No newline at end of file diff --git a/application/services/qcloud/minaauth/Cappinfo_Service.php b/application/services/qcloud/minaauth/Cappinfo_Service.php new file mode 100644 index 0000000..5f2d2d4 --- /dev/null +++ b/application/services/qcloud/minaauth/Cappinfo_Service.php @@ -0,0 +1,81 @@ +query_db($insert_sql); + } + + /** + * @param $appid + * @param $secret + * @param $login_duration + * @param $session_duration + * @return bool + */ + public function update_cappinfo($params) + { + $update_sql = 'update cAppinfo set login_duration = ' . $params['login_duration'] . ',session_duration=' . $params['session_duration'] . ',$secret = "' . $params['secret'] . '" where appid = "' . $params['appid'] . '"'; + $mysql_update = new mysql_db(); + return $mysql_update->query_db($update_sql); + } + + /** + * @param $appid + * @return bool + */ + public function delete_cappinfo() + { + $delete_sql = 'delete from cAppinfo'; + $mysql_delete = new mysql_db(); + return $mysql_delete->query_db($delete_sql); + } + + + /** + * @param $appid + * @return array|bool + */ + public function select_cappinfo() + { + $select_sql = 'select * from cAppinfo'; + $mysql_select = new mysql_db(); + $result = $mysql_select->select_db($select_sql); + if ($result !== false && !empty($result)) { + $arr_result = array(); + while ($row = mysql_fetch_array($result)) { + $arr_result['appid'] = $row['appid']; + $arr_result['secret'] = $row['secret']; + $arr_result['login_duration'] = $row['login_duration']; + $arr_result['session_duration'] = $row['session_duration']; + $arr_result['qcloud_appid'] = $row['qcloud_appid']; + $arr_result['ip'] = $row['ip']; + } + return $arr_result; + } else { + return false; + } + } +} \ No newline at end of file diff --git a/application/services/qcloud/minaauth/Csessioninfo_Service.php b/application/services/qcloud/minaauth/Csessioninfo_Service.php new file mode 100644 index 0000000..0419117 --- /dev/null +++ b/application/services/qcloud/minaauth/Csessioninfo_Service.php @@ -0,0 +1,190 @@ +query_db($insert_sql); + } + + /** + * @param $id + * @param $skey + * @param $last_visit_time + * @return bool + */ + public function update_csessioninfo_time($params) + { + $update_sql = 'update cSessioninfo set last_visit_time = ' . $params['last_visit_time'] . ' where id = ' . $params['id']; + $mysql_update = new mysql_db(); + return $mysql_update->query_db($update_sql); + } + + public function update_csessioninfo($params) + { + $update_sql = 'update cSessioninfo set last_visit_time = ' . $params['last_visit_time'] . ',skey = "' . $params['skey'] .'",user_info=\''.$params['user_info'].'\' where id = ' . $params['id']; + $mysql_update = new mysql_db(); + return $mysql_update->query_db($update_sql); + } + + /** + * @param $id + * @param $skey + * @return bool + */ + public function delete_csessioninfo($open_id) + { + $delete_sql = 'delete from cSessioninfo where open_id = "' . $open_id . '"'; + $mysql_delete = new mysql_db(); + return $mysql_delete->query_db($delete_sql); + } + + public function delete_csessioninfo_by_id_skey($params) + { + $delete_sql = 'delete from cSessioninfo where id = ' . $params['id']; + $mysql_delete = new mysql_db(); + return $mysql_delete->query_db($delete_sql); + } + + /** + * @param $id + * @param $skey + * @return array|bool + */ + public function select_csessioninfo($params) + { + $select_sql = 'select * from cSessioninfo where id = ' . $params['id'] . ' and skey = "' . $params['skey'] . '"'; + $mysql_select = new mysql_db(); + $result = $mysql_select->select_db($select_sql); + if ($result !== false && !empty($result)) { + $arr_result = array(); + while ($row = mysql_fetch_array($result)) { + $arr_result['id'] = $row['id']; + $arr_result['skey'] = $row['skey']; + $arr_result['create_time'] = $row['create_time']; + $arr_result['last_visit_time'] = $row['last_visit_time']; + $arr_result['open_id'] = $row['open_id']; + $arr_result['session_key'] = $row['session_key']; + $arr_result['user_info'] = $row['user_info']; + } + return $arr_result; + } else { + return false; + } + } + + /** + * @param $open_id + * @return bool + */ + public function get_id_csessioninfo($open_id) + { + $select_sql = 'select id from cSessioninfo where open_id = "' . $open_id . '"'; + $mysql_select = new mysql_db(); + $result = $mysql_select->select_db($select_sql); + if ($result !== false && !empty($result)) { + $id = false; + while ($row = mysql_fetch_array($result)) { + $id = $row['id']; + } + return $id; + } else { + return false; + } + } + + public function check_session_for_login($params){ + $select_sql = 'select *_time from cSessioninfo where open_id = "' . $params['openid'] . '"'; + $mysql_select = new mysql_db(); + $result = $mysql_select->select_db($select_sql); + if ($result !== false && !empty($result)) { + $create_time = false; + while ($row = mysql_fetch_array($result)) { + $create_time = $row['create_time']; + } + if($create_time == false){ + return false; + }else{ + $now_time = time(); + if(($now_time-$create_time)/86400>$params['login_duration']){ + $this->delete_csessioninfo($params['openid']); + return true; + }else{ + return true; + } + } + } else { + return true; + } + } + + + public function check_session_for_auth($params){ + $result = $this->select_csessioninfo($params); + if(!empty($result) && $result !== false && count($result) != 0){ + $now_time = time(); + $create_time = $result['create_time']; + $last_visit_time = $result['last_visit_time']; + if(($now_time-$create_time)/86400>$params['login_duration']) { + $this->delete_csessioninfo_by_id_skey($params); + return false; + }else if(($now_time-$last_visit_time)>$params['session_duration']){ + return false; + }else{ + $params['last_visit_time'] = $now_time; + $this->update_csessioninfo_time($params); + return $result['user_info']; + } + }else{ + return false; + } + } + + /** + * @param $skey + * @param $create_time + * @param $last_visit_time + * @param $open_id + * @param $session_key + * @return bool + */ + public function change_csessioninfo($params) + { + if($this->check_session_for_login($params)){ + $id = $this->get_id_csessioninfo($params['openid']); + if ($id != false) { + $params['id'] = $id; + if ($this->update_csessioninfo($params)) + return $id; + else + return false; + } else { + return $this->insert_csessioninfo($params); + } + }else{ + return false; + } + } +} \ No newline at end of file diff --git a/index.php b/index.php new file mode 100644 index 0000000..bb33861 --- /dev/null +++ b/index.php @@ -0,0 +1,11 @@ +parse_json($request)); diff --git a/init_report_data.php b/init_report_data.php new file mode 100644 index 0000000..5b75950 --- /dev/null +++ b/init_report_data.php @@ -0,0 +1,23 @@ +fc_load_config("system/conf/config.ini"); +$region = $config['region'];//用户配置 +$secret_id = $config['secret_id'];//用户配置 +$secretKey = $config['secretKey'];//用户配置 +$ip = $config['ip'];//用户配置 + +$report_data = new report_data(); +var_dump($report_data->create_namespace($region,$secret_id,$secretKey)); +var_dump($report_data->create_metric($region,$secret_id,$secretKey,"authsucessrate","authsucessrate")); +var_dump($report_data->create_metric($region,$secret_id,$secretKey,"loginsucessrate","loginsucessrate")); +var_dump($report_data->bind_alarm_rule_objects($region,$secret_id,$secretKey,"authsucessrate",$ip)); +var_dump($report_data->bind_alarm_rule_objects($region,$secret_id,$secretKey,"loginsucessrate",$ip)); diff --git a/qcloud_report.php b/qcloud_report.php new file mode 100644 index 0000000..dccdc16 --- /dev/null +++ b/qcloud_report.php @@ -0,0 +1,48 @@ +fc_load_config("system/conf/config.ini"); +$region = $config['region'];//用户配置 +$secret_id = $config['secret_id'];//用户配置 +$secretKey = $config['secretKey'];//用户配置 +$ip = $config['ip'];//用户配置 + +$ready_for_report_data = new ready_for_report_data(); +$report_data = new report_data(); +$contents = $ready_for_report_data->check_data(); +if($contents){ + $arr_contents = json_decode($contents,true); + $arr_report_data['ip'] = $arr_contents['ip']; + $arr_report_data['login_count'] = "login_count"; + $arr_report_data['login_count_value'] = $arr_contents['login_count']; + $arr_report_data['login_sucess_rate'] = "login_sucess_rate"; + if($arr_contents['login_count']===0){ + $arr_report_data['login_sucess_value'] = 0 ; + }else{ + $arr_report_data['login_sucess_value'] = ($arr_contents['login_sucess']/$arr_contents['login_count'])*100; + } + $arr_report_data['auth_count'] = "auth_count"; + $arr_report_data['auth_count_value'] = $arr_contents['login_count']; + + $arr_report_data['auth_sucess_rate']="auth_sucess_rate"; + if($arr_report_data['auth_count']===0){ + $arr_report_data['auth_sucess_value']=0; + }else{ + + } + $arr_report_data['auth_sucess_value'] = ($arr_contents['auth_sucess']/$arr_contents['auth_count'])*100; + + $report_data->report_data($region, $secret_id, $secretKey,$ip,"authsucessrate",$arr_report_data['auth_sucess_value']); + $report_data->report_data($region, $secret_id, $secretKey,$ip,"loginsucessrate",$arr_report_data['login_sucess_value']); + + $ready_for_report_data->deletfile(); +} diff --git a/sh/check_appid.sh b/sh/check_appid.sh new file mode 100644 index 0000000..a665b65 --- /dev/null +++ b/sh/check_appid.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +appid_check=`curl -i -d "{\"version\":1,\"componentName\":\"MA\",\"interface\":{\"interfaceName\" : \"qcloud.cam.initdata\",\"para\" : {\"appid\":\"$1\",\"secret\":\"$2\",\"qcloud_appid\":\"$3\",\"ip\":\"$4\",\"cdb_ip\":\"$5\",\"cdb_port\":\"$6\",\"cdb_user_name\":\"$7\",\"cdb_pass_wd\":\"$8\"}}}" http://127.0.0.1/mina_auth/ 2>/dev/null` +echo $appid_check | grep "\"returnCode\":0" +test $? -eq 0 && echo "yes" || echo "no" \ No newline at end of file diff --git a/sh/init_config.sh b/sh/init_config.sh new file mode 100644 index 0000000..83234d9 --- /dev/null +++ b/sh/init_config.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo "{\"serverHost\": \"$1\",\n\"authServerUrl\": \"$2\",\n\"tunnelServerUrl\": \"https://ws.qcloud.com\",\n\"tunnelSignatureKey\": \"$3\",\n\"networkProxy\": \"127.0.0.1:8888\"}" > /etc/qcloud/sdk.config diff --git a/sh/install_appid.sh b/sh/install_appid.sh new file mode 100644 index 0000000..a3411c5 --- /dev/null +++ b/sh/install_appid.sh @@ -0,0 +1,32 @@ +#!/usr/bin/expect -f +set timeout 10 +set IP [lindex $argv 0] +set PASSWORD [lindex $argv 1] +set APPID [lindex $argv 2] +set SECRET [lindex $argv 3] +set QCLOUD_APPID [lindex $argv 4] +set P_IP [lindex $argv 5] +set CDB_IP [lindex $argv 6] +set CDB_PORT [lindex $argv 7] +set CDB_USER_NAME [lindex $argv 8] +set CDB_PASS_WD [lindex $argv 9] +spawn ssh -l root -p 22 $IP +expect { + "yes/no" { + send "yes\r";exp_continue + } + "password:" { + send "$PASSWORD\r"; + } +} +expect "]# " +send "/opt/lampp/htdocs/mina_auth/sh/check_appid.sh $APPID $SECRET $QCLOUD_APPID $P_IP $CDB_IP $CDB_PORT $CDB_USER_NAME $CDB_PASS_WD\r" +expect { + "yes\r" { + #send "exit\r"; + exit 0; + } + timeout { + exit 1; + } +} \ No newline at end of file diff --git a/sh/install_config.sh b/sh/install_config.sh new file mode 100644 index 0000000..c72c0a3 --- /dev/null +++ b/sh/install_config.sh @@ -0,0 +1,28 @@ +#!/usr/bin/expect -f +set timeout 10 +set IP [lindex $argv 0] +set PASSWORD [lindex $argv 1] +set serverHost [lindex $argv 2] +set authIp [lindex $argv 3] +set tunnelSignatureKey [lindex $argv 4] + +spawn ssh -l root -p 22 $IP +expect { + "yes/no" { + send "yes\r";exp_continue + } + "password:" { + send "$PASSWORD\r"; + } +} +expect "]# " +send "/etc/qcloud/init_config.sh $serverHost $authIp $tunnelSignatureKey \r" +expect { + "yes\r" { + #send "exit\r"; + exit 0; + } + timeout { + exit 1; + } +} \ No newline at end of file diff --git a/sh/schedule.sh b/sh/schedule.sh new file mode 100644 index 0000000..e1226d7 --- /dev/null +++ b/sh/schedule.sh @@ -0,0 +1,9 @@ +#!/bin/sh +#install_appid.sh ip passwd $appid $secret +./install_appid.sh 10.141.20.104 Murphy.me appid1 secret1 qcloud_appid 192.168.1.1 127.0.0.1 3306 root1 root1 +if [ $? -eq 0 ] +then + echo "ok" +else + echo "error" +fi \ No newline at end of file diff --git a/sh/schedule_config.sh b/sh/schedule_config.sh new file mode 100644 index 0000000..666a0ee --- /dev/null +++ b/sh/schedule_config.sh @@ -0,0 +1,3 @@ +#!/bin/sh +./install_config.sh 10.141.20.104 Murphy.me appid1 secret1 qcloud_appid + echo "ok" diff --git a/system/conf/config.ini b/system/conf/config.ini new file mode 100644 index 0000000..ee33a2d --- /dev/null +++ b/system/conf/config.ini @@ -0,0 +1,11 @@ +[log] +log_path = log/ +log_file_extension = log +log_threshold = 3 + +[report_data] +data_path = reportdata/ +region= +secret_id= +secretKey= +ip= \ No newline at end of file diff --git a/system/db/db.ini b/system/db/db.ini new file mode 100644 index 0000000..ce5598e --- /dev/null +++ b/system/db/db.ini @@ -0,0 +1,6 @@ +[db] +host = 127.0.0.1 +port = 3306 +user_name = root +pass_wd = root +data_base = cAuth \ No newline at end of file diff --git a/system/db/db.sql b/system/db/db.sql new file mode 100644 index 0000000..89ee285 --- /dev/null +++ b/system/db/db.sql @@ -0,0 +1,22 @@ +DROP TABLE IF EXISTS `cAppinfo`; +CREATE TABLE `cAppinfo` ( + `appid` varchar(200) COLLATE utf8_unicode_ci NOT NULL COMMENT '应用的唯一标识', + `secret` varchar(300) COLLATE utf8_unicode_ci NOT NULL COMMENT '应用的密钥', + `login_duration` int(11) DEFAULT '30' COMMENT '默认登陆有效期,单位天', + `session_duration` int(11) DEFAULT '3600' COMMENT '默认session有效期,单位秒', + `qcloud_appid` varchar(300) COLLATE utf8_unicode_ci DEFAULT 'appid_qcloud', + `ip` varchar(50) COLLATE utf8_unicode_ci DEFAULT '0.0.0.0', + PRIMARY KEY (`appid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='全局信息表 cAppinfo'; +DROP TABLE IF EXISTS `cSessioninfo`; +CREATE TABLE `cSessioninfo` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '本次会话分配给用户的id', + `skey` varchar(200) COLLATE utf8_unicode_ci NOT NULL COMMENT '本次会话分配给用户的skey', + `create_time` int(11) NOT NULL COMMENT '创建时间', + `last_visit_time` int(11) NOT NULL COMMENT '最近访问时间', + `open_id` varchar(200) COLLATE utf8_unicode_ci NOT NULL COMMENT '微信用户标识', + `session_key` varchar(200) COLLATE utf8_unicode_ci NOT NULL COMMENT '微信session', + `user_info` text COLLATE utf8_unicode_ci, + KEY `auth` (`id`,`skey`), + KEY `wexin` (`open_id`,`session_key`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/system/db/init_db.php b/system/db/init_db.php new file mode 100644 index 0000000..4638088 --- /dev/null +++ b/system/db/init_db.php @@ -0,0 +1,66 @@ +init_db("DROP DATABASE IF EXISTS `cAuth`")){ + if($mysql_db->init_db("CREATE DATABASE `cAuth`")){ + foreach ($_arr as $_value) { + if(!empty($_value)){ + if(!$mysql_db->query_db($_value.';')) + return false; + } + } + } + else{ + return false; + } + }else{ + return false; + } + return true; + } +} \ No newline at end of file diff --git a/system/db/mysql_db.php b/system/db/mysql_db.php new file mode 100644 index 0000000..d1df57f --- /dev/null +++ b/system/db/mysql_db.php @@ -0,0 +1,102 @@ +fc_load_config("system/db/db.ini"); + $this->host = $config['host']; + $this->port = $config['port']; + $this->user_name = $config['user_name']; + $this->pass_wd = $config['pass_wd']; + $this->data_base = $config['data_base']; + } + + /** + * @param $sql + * @return string + * 描述:安全过滤sql,防止sql注入 + */ + function safe($sql) + { + if (get_magic_quotes_gpc()) { + $sql = stripslashes($sql); + } + $sql = mysql_real_escape_string($sql); + return $sql; + } + + /** + * @param $sql + * @return bool + * 描述:执行Mysql增删改操作 + */ + public function query_db($sql) + { + $con = mysql_connect($this->host . ':' . $this->port, $this->user_name, $this->pass_wd); + if ($con) { + mysql_select_db($this->data_base, $con); + $mysql_result = mysql_query($sql); + if ($mysql_result === false) { + mysql_close($con); + log_message("ERROR","$sql mysql_err"); + return false; + } + mysql_close($con); + return true; + } else { + log_message("ERROR","$sql mysql_connect_err"); + return false; + } + } + + /** + * @param $sql + * @return bool|resource + * 描述:执行mysql查询操作 + */ + public function select_db($sql) + { + $con = mysql_connect($this->host . ':' . $this->port, $this->user_name, $this->pass_wd); + if ($con) { + mysql_select_db($this->data_base, $con); + $arr_result = mysql_query($sql); + mysql_close($con); + return $arr_result; + } else { + log_message("ERROR","$sql mysql_connect_err"); + return false; + } + } + + public function init_db($sql){ + $con = mysql_connect($this->host . ':' . $this->port, $this->user_name, $this->pass_wd); + if ($con) { + $result = mysql_query("$sql",$con); + if($result===false){ + log_message("ERROR","$sql mysql_err"); + return false; + } + return true; + }else{ + log_message("ERROR","$sql mysql_connect_err"); + return false; + } + } +} \ No newline at end of file diff --git a/system/decrypt_data.php b/system/decrypt_data.php new file mode 100644 index 0000000..7230aad --- /dev/null +++ b/system/decrypt_data.php @@ -0,0 +1,41 @@ +stripPkcs7Padding($decrypted); + } + + /** + * 对解密后的明文进行补位删除 + * @param text 解密后的明文 + * @return 删除填充补位后的明文 + */ + function stripPkcs7Padding($text) + { + + $pad = ord(substr($text, -1)); + if ($pad < 1 || $pad > 32) { + $pad = 0; + } + return substr($text, 0, (strlen($text) - $pad)); + } +} \ No newline at end of file diff --git a/system/http_util.php b/system/http_util.php new file mode 100644 index 0000000..a8b3919 --- /dev/null +++ b/system/http_util.php @@ -0,0 +1,70 @@ +$val){ + $aPOST[] = $key."=".urlencode($val); + } + $strPOST = join("&", $aPOST); + } + curl_setopt($oCurl, CURLOPT_URL, $url); + curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 ); + curl_setopt($oCurl, CURLOPT_POST,true); + curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST); + $sContent = curl_exec($oCurl); + $aStatus = curl_getinfo($oCurl); + curl_close($oCurl); + if(intval($aStatus["http_code"])==200){ + return $sContent; + }else{ + return false; + } + } + + /** + * GET 请求 + * @param string $url + */ + public function http_get($url){ + $oCurl = curl_init(); + if(stripos($url,"https://")!==FALSE){ + curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); + } + curl_setopt($oCurl, CURLOPT_URL, $url); + curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 ); + $sContent = curl_exec($oCurl); + $aStatus = curl_getinfo($oCurl); + curl_close($oCurl); + if(intval($aStatus["http_code"])==200){ + return $sContent; + }else{ + return false; + } + } + + + +} \ No newline at end of file diff --git a/system/load_config.php b/system/load_config.php new file mode 100644 index 0000000..98b6408 --- /dev/null +++ b/system/load_config.php @@ -0,0 +1,19 @@ +='); + } + + return $_is_php[$version]; + } +} + +if ( ! function_exists('is_really_writable')) +{ + /** + * Tests for file writability + * + * is_writable() returns TRUE on Windows servers when you really can't write to + * the file, based on the read-only attribute. is_writable() is also unreliable + * on Unix servers if safe_mode is on. + * + * @link https://bugs.php.net/bug.php?id=54709 + * @param string + * @return bool + */ + function is_really_writable($file) + { + // If we're on a Unix server with safe_mode off we call is_writable + if (DIRECTORY_SEPARATOR === '/' && (is_php('5.4') OR ! ini_get('safe_mode'))) + { + return is_writable($file); + } + + /* For Windows servers and safe_mode "on" installations we'll actually + * write a file then read it. Bah... + */ + if (is_dir($file)) + { + $file = rtrim($file, '/').'/'.md5(mt_rand()); + if (($fp = @fopen($file, 'ab')) === FALSE) + { + return FALSE; + } + + fclose($fp); + @chmod($file, 0777); + @unlink($file); + return TRUE; + } + elseif ( ! is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) + { + return FALSE; + } + + fclose($fp); + return TRUE; + } +} + +class Log { + + /** + * Path to save log files + * + * @var string + */ + protected $_log_path; + + protected $_sub_path; + + /** + * File permissions + * + * @var int + */ + protected $_file_permissions = 0644; + + /** + * Level of logging + * + * @var int + */ + protected $_threshold = 1; + + /** + * Array of threshold levels to log + * + * @var array + */ + protected $_threshold_array = array(); + + /** + * Format of timestamp for log files + * + * @var string + */ + protected $_date_fmt = 'Y-m-d H:i:s.u'; + + protected $_file_prefix = ""; + + protected $_file_idx = "0"; + + protected $_file_size = 104857600; + + /** + * Filename extension + * + * @var string + */ + protected $_file_ext; + + /** + * Whether or not the logger can write to the log files + * + * @var bool + */ + protected $_enabled = TRUE; + + /** + * Predefined logging levels + * + * @var array + */ + protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4); + + // -------------------------------------------------------------------- + + /** + * Class constructor + * + * @return void + */ + public function __construct($file_prefix = "") + { + ini_set('date.timezone','Asia/Shanghai'); + $load_config = new load_config(); + $config = $load_config->fc_load_config("system/conf/config.ini"); + $this->_log_path = ($config['log_path'] != '') ? $config['log_path'] : 'logs/'; + $this->_sub_path = date("Y-m-d"); + $this->_file_ext = (isset($config['log_file_extension']) && $config['log_file_extension'] !== '') + ? ltrim($config['log_file_extension'], '.') : 'log'; + + file_exists($this->_log_path) OR mkdir($this->_log_path, 0755, TRUE); + + $this->_file_prefix = $file_prefix; + + $this->_file_idx = 0; + while (true) + { + if (file_exists($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx)) + { + $cur_size = filesize($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx); + if ($cur_size > $this->_file_size) + $this->_file_idx++; + else + break; + } + else + { + break; + } + } + + if (is_numeric($config['log_threshold'])) + { + $this->_threshold = (int) $config['log_threshold']; + } + elseif (is_array($config['log_threshold'])) + { + $this->_threshold = 0; + $this->_threshold_array = array_flip($config['log_threshold']); + } + + if (!empty($config['log_file_size']) && is_numeric($config['log_file_size'])) + { + $this->_file_size = (int)$config['log_file_size']; + } + + + if ( ! empty($config['log_date_format'])) + { + $this->_date_fmt = $config['log_date_format']; + } + + if ( ! empty($config['log_file_permissions']) && is_int($config['log_file_permissions'])) + { + $this->_file_permissions = $config['log_file_permissions']; + } + } + + // -------------------------------------------------------------------- + + /** + * Write Log File + * + * Generally this function will be called using the global log_message() function + * + * @param string the error level: 'error', 'debug' or 'info' + * @param string the error message + * @return bool + */ + public function write_log($level, $msg) + { + + $level = strtoupper($level); + + if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold)) + && ! isset($this->_threshold_array[$this->_levels[$level]])) + { + return FALSE; + } + + if ($this->_sub_path == date("Y-m-d")) + { + if (file_exists($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx)) + { + $cur_size = filesize($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx); + if ($cur_size > $this->_file_size) + $this->_file_idx++; + } + } + else + { + $this->_sub_path = date("Y-m-d"); + $this->_file_idx = 0; + } + del_dir_file($this->_log_path.date("Y-m-d",strtotime("-2 day")),true); + file_exists($this->_log_path.$this->_sub_path) OR mkdir($this->_log_path.$this->_sub_path, 0755, TRUE); + + if ( ! is_dir($this->_log_path) OR ! is_really_writable($this->_log_path)) + { + $this->_enabled = FALSE; + return false; + } + + $filepath = $this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx; + + $message = ''; + + if ( ! $fp = @fopen($filepath, 'ab')) + { + return FALSE; + } + + // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format + if (strpos($this->_date_fmt, 'u') !== FALSE) + { + $microtime_full = microtime(TRUE); + $microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000); + $date = new DateTime(date('Y-m-d H:i:s.'.$microtime_short, $microtime_full)); + $date = $date->format($this->_date_fmt); + } + else + { + $date = date($this->_date_fmt); + } + + $bt = debug_backtrace(false); + $filename = ''; + $linenumber = ''; + if (isset($bt[1])) { + $filename = $bt[1]['file']; + $linenumber = $bt[1]['line']; + } + + $message .= "{$level}|{$date}|{$filename}:{$linenumber}|{$msg}\n"; + + flock($fp, LOCK_EX); + + for ($written = 0, $length = strlen($message); $written < $length; $written += $result) + { + if (($result = fwrite($fp, substr($message, $written))) === FALSE) + { + break; + } + } + + flock($fp, LOCK_UN); + fclose($fp); + + if (isset($newfile) && $newfile === TRUE) + { + chmod($filepath, $this->_file_permissions); + } + + return is_int($result); + } +} + +function log_message($level, $message, $name='mina_auth') +{ + static $_log; + + if ($_log == NULL) + { + // references cannot be directly assigned to static variables, so we use an array + $_log[0] = new Log($name); + } + + $_log[0]->write_log($level, $message); +} + +function stat_log($level, $message) +{ + static $_log_stat; + + if ($_log_stat == NULL) + { + $pid = getmypid(); + // references cannot be directly assigned to static variables, so we use an array + $_log_stat[0] = new Log('stat'.$pid); + } + + $_log_stat[0]->write_log($level, $message); +} + + +function del_dir_file($path, $delDir = FALSE) { + if(file_exists($path)){ + $handle = opendir($path); + if ($handle) { + while (false !== ( $item = readdir($handle) )) { + if ($item != "." && $item != "..") + is_dir("$path/$item") ? del_dir_file("$path/$item", $delDir) : unlink("$path/$item"); + } + closedir($handle); + if ($delDir) + return rmdir($path); + }else { + if (file_exists($path)) { + return unlink($path); + } else { + return FALSE; + } + } + } +} \ No newline at end of file diff --git a/system/parse_request.php b/system/parse_request.php new file mode 100644 index 0000000..6419740 --- /dev/null +++ b/system/parse_request.php @@ -0,0 +1,117 @@ +is_json($request_json)) { + $json_decode = json_decode($request_json, true); + if (!isset($json_decode['interface']['interfaceName'])) { + $ret['returnCode'] = return_code::MA_NO_INTERFACE; + $ret['returnMessage'] = 'NO_INTERFACENAME_PARA'; + $ret['returnData'] = ''; + } else if (!isset($json_decode['interface']['para'])) { + $ret['returnCode'] = return_code::MA_NO_PARA; + $ret['returnMessage'] = 'NO_PARA'; + $ret['returnData'] = ''; + } else { + if ($json_decode['interface']['interfaceName'] == 'qcloud.cam.id_skey') { + if (isset($json_decode['interface']['para']['code'])&&isset($json_decode['interface']['para']['encrypt_data'])) { + $code = $json_decode['interface']['para']['code']; + $encrypt_data = $json_decode['interface']['para']['encrypt_data']; + $auth = new Auth(); + $ret = $auth->get_id_skey($code,$encrypt_data); + } else { + $ret['returnCode'] = return_code::MA_PARA_ERR; + $ret['returnMessage'] = 'PARA_ERR'; + $ret['returnData'] = ''; + } + } else if ($json_decode['interface']['interfaceName'] == 'qcloud.cam.auth') { + if (isset($json_decode['interface']['para']['id']) && isset($json_decode['interface']['para']['skey'])) { + $id = $json_decode['interface']['para']['id']; + $skey = $json_decode['interface']['para']['skey']; + $auth = new Auth(); + $ret = $auth->auth($id, $skey); + } else { + $ret['returnCode'] = return_code::MA_PARA_ERR; + $ret['returnMessage'] = 'PARA_ERR'; + $ret['returnData'] = ''; + } + } else if ($json_decode['interface']['interfaceName'] == 'qcloud.cam.decrypt') { + if (isset($json_decode['interface']['para']['id']) && isset($json_decode['interface']['para']['skey']) && isset($json_decode['interface']['para']['encrypt_data'])) { + $id = $json_decode['interface']['para']['id']; + $skey = $json_decode['interface']['para']['skey']; + $encrypt_data = $json_decode['interface']['para']['encrypt_data']; + $auth = new Auth(); + $ret = $auth->decrypt($id, $skey, $encrypt_data); + } else { + $ret['returnCode'] = return_code::MA_PARA_ERR; + $ret['returnMessage'] = 'PARA_ERR'; + $ret['returnData'] = ''; + } + }else if($json_decode['interface']['interfaceName'] == 'qcloud.cam.initdata'){ + if (isset($json_decode['interface']['para']['appid']) && isset($json_decode['interface']['para']['secret']) && isset($json_decode['interface']['para']['qcloud_appid']) && isset($json_decode['interface']['para']['ip']) + && isset($json_decode['interface']['para']['cdb_ip'])&& isset($json_decode['interface']['para']['cdb_port']) && isset($json_decode['interface']['para']['cdb_user_name'])&& isset($json_decode['interface']['para']['cdb_pass_wd']) ) { + $appid = $json_decode['interface']['para']['appid']; + $secret = $json_decode['interface']['para']['secret']; + $qcloud_appid = $json_decode['interface']['para']['qcloud_appid']; + $ip = $json_decode['interface']['para']['ip']; + $cdb_ip = $json_decode['interface']['para']['cdb_ip']; + $cdb_port = $json_decode['interface']['para']['cdb_port']; + $cdb_user_name = $json_decode['interface']['para']['cdb_user_name']; + $cdb_pass_wd = $json_decode['interface']['para']['cdb_pass_wd']; + $auth = new Auth(); + $ret = $auth->init_data($appid,$secret,$qcloud_appid,$ip,$cdb_ip,$cdb_port,$cdb_user_name,$cdb_pass_wd); + } else { + $ret['returnCode'] = return_code::MA_PARA_ERR; + $ret['returnMessage'] = 'PARA_ERR'; + $ret['returnData'] = ''; + } + } else { + $ret['returnCode'] = return_code::MA_INTERFACE_ERR; + $ret['returnMessage'] = 'INTERFACENAME_PARA_ERR'; + $ret['returnData'] = ''; + } + } + } else { + $ret['returnCode'] = return_code::MA_REQUEST_ERR; + $ret['returnMessage'] = 'REQUEST_IS_NOT_JSON'; + $ret['returnData'] = ''; + } + $ret['version'] = 1; + $ret['componentName'] = "MA"; + log_message("info",json_encode($ret)); + return json_encode($ret); + } + + /** + * @param $str + * @return bool + * 描述:判断字符串是不是合法的json + */ + private function is_json($str) + { + json_decode($str); + return (json_last_error() == JSON_ERROR_NONE); + } +} \ No newline at end of file diff --git a/system/report_data/ready_for_report_data.php b/system/report_data/ready_for_report_data.php new file mode 100644 index 0000000..2a28fd6 --- /dev/null +++ b/system/report_data/ready_for_report_data.php @@ -0,0 +1,100 @@ +fc_load_config("system/conf/config.ini"); + $this->report_data_path = $config['data_path']; + } + + /** + * @param $report_data + */ + public function write_report_data($report_data){ + file_exists($this->report_data_path) OR mkdir($this->report_data_path, 0755, TRUE); + $data_path = $this->report_data_path."data"; + $handle = fopen($data_path,'w'); + flock($handle, LOCK_EX); + $write_result = fwrite($handle,$report_data); + if ($write_result === false){ + log_message("ERROR","$report_data write_report_data_wrong"); + } + flock($handle, LOCK_UN); + fclose($handle); + return $write_result; + } + + /** + * @return string + */ + public function read_report_data(){ + $data_path = $this->report_data_path."data"; + if(!file_exists($data_path)){ + log_message("ERROR","report_data_not_exit"); + return false; + } + $handle = fopen($data_path, "r"); + $contents = fread($handle, filesize($data_path)); + fclose($handle); + if($contents===false){ + log_message("ERROR","read_report_data_wrong"); + } + return $contents; + } + + + public function check_data(){ + $contents = $this->read_report_data(); + if($contents){ + if($this->is_json($contents)){ + $json_contents = json_decode($contents, true); + if(isset($json_contents['ip']) && isset($json_contents['appid']) && isset($json_contents['login_count']) && isset($json_contents['login_sucess']) && isset($json_contents['auth_count']) && isset($json_contents['auth_sucess'])){ + return $contents; + } + return false; + } + return false; + }else{ + return false; + } + } + + public function ready_data($type){ + $content = $this->check_data(); + if($content != false){ + $arr_content = json_decode($content,true); + $arr_content[$type]++; + $json_content = json_encode($arr_content); + return $this->write_report_data($json_content); + } + return false; + } + + public function is_json($str) + { + json_decode($str); + return (json_last_error() == JSON_ERROR_NONE); + } + + public function deletfile(){ + $data_path = $this->report_data_path."data"; + if(is_file($data_path)){ + if(!unlink($data_path)){ + chmod($data_path,0777); + unlink($data_path); + } + } + } +} \ No newline at end of file diff --git a/system/report_data/report_data.php b/system/report_data/report_data.php new file mode 100644 index 0000000..04ae4d6 --- /dev/null +++ b/system/report_data/report_data.php @@ -0,0 +1,360 @@ +ip = $ip; + $data[0]->dimensions = $obj; + $data[0]->metricName = $metricName; + $data[0]->value = $value; + return $data; + } + + + + public function report_data($region, $secret_id, $secretKey,$ip,$metricName,$value) + { + $data = $this->set_report_data($ip,$metricName,$value); + if ($this->put_monitor_data($region, $secret_id, $secretKey,$data) == false) { + log_message("ERROR", "report_data_err"); + } + } + + /** + * @param $region + * @param $secret_id + * @param $signature + * @return bool + * 描述:创建命名空间 + */ + public function create_namespace($region, $secret_id, $secretKey) + { + $time = time(); + $nonce = mt_rand(10000, 99999); + $arr = Array( + "Action" => "CreateNamespace", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id, + "namespace" => "minaauth" + ); + $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey); + $signature = urlencode($signature); + $url = "https://monitor.api.qcloud.com/v2/index.php?Action=CreateNamespace&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature&namespace=minaauth"; + $http_util = new http_util(); + $ret_msg = $http_util->http_get($url); + if ($ret_msg && $this->is_json($ret_msg)) { + $json_ret_msg = json_decode($ret_msg, true); + if ($json_ret_msg['code'] == 0) + return true; + } + return false; + } + + + /** + * @param $region + * @param $secret_id + * @param $signature + * @param $metric_name + * @param $metric_cname + * @return bool + * 描述:创建指标 + */ + public function create_metric($region, $secret_id, $secretKey, $metric_name, $metric_cname) + { + $time = time(); + $nonce = mt_rand(10000, 99999); + $arr = Array( + "Action" => "CreateMetric", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id, + "namespace" => "minaauth", + "metricName" => $metric_name, + "metricCname" => $metric_cname, + "dimensionNames.0" => "ip", + "statisticsType.0.period" => 300, + "statisticsType.0.statistics" => "max" + ); + $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey); + $signature = urlencode($signature); + $url = "https://monitor.api.qcloud.com/v2/index.php?Action=CreateMetric&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature&namespace=minaauth&metricName=$metric_name&metricCname=$metric_cname&dimensionNames.0=ip&statisticsType.0.period=300&statisticsType.0.statistics=max"; + $http_util = new http_util(); + $ret_msg = $http_util->http_get($url); + if ($ret_msg && $this->is_json($ret_msg)) { + $json_ret_msg = json_decode($ret_msg, true); + if ($json_ret_msg['code'] == 0) + return true; + } + return false; + } + + /** + * @param $region + * @param $secret_id + * @param $signature + * @param $data + * @return bool + * 描述:创建指标上报数据 + */ + public function put_monitor_data($region, $secret_id, $secretKey, $data) + { + $time = time(); + $nonce = mt_rand(10000, 99999); + $arr = Array( + "Action" => "PutMonitorData", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id + ); + $signature = $this->post_signature($arr, 'receiver.monitor.tencentyun.com/v2/index.php?', $secretKey); + + $params = array( + "Action" => "PutMonitorData", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id, + "Signature"=>$signature, + "Namespace"=>"minaauth", + "Data"=>$data + ); + $params_json = json_encode($params); + $http_util = new http_util(); + $ret_msg = $http_util->http_post('http://receiver.monitor.tencentyun.com:8080/v2/index.php',$params_json); + if ($ret_msg && $this->is_json($ret_msg)) { + $json_ret_msg = json_decode($ret_msg, true); + if ($json_ret_msg['code'] == 0) + return true; + } + return false; + + } + + /** + * @return bool + * 描述:获取用户组ID + */ + public function describe_user_group($region, $secret_id, $secretKey) + { + $time = time(); + $nonce = mt_rand(10000, 99999); + $arr = Array( + "Action" => "DescribeUserGroup", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id, + ); + $signature = $this->get_signature($arr, 'account.api.qcloud.com/v2/index.php?', $secretKey); + + $url = "https://account.api.qcloud.com/v2/index.php?Action=DescribeUserGroup&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature"; + $http_util = new http_util(); + $ret_msg = $http_util->http_get($url); + if ($ret_msg && $this->is_json($ret_msg)) { + $json_ret_msg = json_decode($ret_msg, true); + if (isset($json_ret_msg['data']['groupSet'][0]['groupId'])) + return $json_ret_msg['data']['groupSet'][0]['groupId']; + } + return false; + } + + /** + * @param $region + * @param $secret_id + * @param $signature + * @param $metric_name + * @param $metric_cname + * @return bool + * 描述:创建告警规则 + */ + public function create_alarm_rule($region, $secret_id, $secretKey, $metric_name) + { + $time = time(); + $nonce = mt_rand(10000, 99999); + $receivers_id = $this->describe_user_group($region, $secret_id, $secretKey); + $arr = Array( + "Action" => "CreateAlarmRule", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id, + "namespace"=>"minaauth", + "metricName"=>$metric_name, + "dimensionNames.0"=>"ip", + "operatorType"=>"<", + "threshold"=>95, + "period"=>300, + "statistics"=>"max", + "constancy"=>2, + "receiversId"=>$receivers_id + ); + $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey); + if ($receivers_id) { + $url = "https://monitor.api.qcloud.com/v2/index.php?Action=CreateAlarmRule&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature&namespace=minaauth&metricName=$metric_name&dimensionNames.0=ip&operatorType=<&threshold=95&period=300&statistics=max&constancy=2&receiversId=$receivers_id"; + $http_util = new http_util(); + $ret_msg = $http_util->http_get($url); + if ($ret_msg && $this->is_json($ret_msg)) { + $json_ret_msg = json_decode($ret_msg, true); + if (isset($json_ret_msg['data']['alarmRuleId'])) + return $json_ret_msg['data']['alarmRuleId']; + } + } + + return false; + } + + /** + * @param $region + * @param $secret_id + * @param $signature + * @param $metric_name + * @param $ip + * @param $metric_name_value + * @return bool + * 描述:绑定告警规则和对象 + */ + public function bind_alarm_rule_objects($region, $secret_id, $secretKey, $metric_name, $ip) + { + $time = time(); + $nonce = mt_rand(10000, 99999); + $alarmRule_id = $this->create_alarm_rule($region, $secret_id, $secretKey, $metric_name); + $arr = Array( + "Action" => "BindAlarmRuleObjects", + "Region" => $region, + "Timestamp" => $time, + "Nonce" => $nonce, + "SecretId" => $secret_id, + "alarmRuleId" => $alarmRule_id, + "dimensions.0.name"=>"ip", + "dimensions.0.value"=>$ip + ); + $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey); + + if ($alarmRule_id) { + $url = "https://monitor.api.qcloud.com/v2/index.php?Action=BindAlarmRuleObjects&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature&alarmRuleId=$alarmRule_id&dimensions.0.name=ip&dimensions.0.value=$ip"; + $http_util = new http_util(); + $ret_msg = $http_util->http_get($url); + if ($ret_msg && $this->is_json($ret_msg)) { + $json_ret_msg = json_decode($ret_msg, true); + if ($json_ret_msg['code'] == 0) + return true; + } + } + return false; + } + + public function is_json($str) + { + json_decode($str); + return (json_last_error() == JSON_ERROR_NONE); + } + + /** + * @param $arr + * @param $get_url + * @param $secretKey + * @return bool|string + * 描述:生成签名 + */ + public function get_signature($arr, $get_url, $secretKey) + { + $sort_arr = ksort($arr); + if ($sort_arr) { + $sort_json = json_encode($arr); + $sort_json = $this->wipe_illegal_char($sort_json); + $str_sig = 'GET' . $get_url . $sort_json; + $sign_str = base64_encode(hash_hmac('sha1', $str_sig, $secretKey, true)); + return $sign_str; + } + return false; + } + + public function post_signature($arr, $get_url, $secretKey) + { + $sort_arr = ksort($arr); + if ($sort_arr) { + $sort_json = json_encode($arr); + $sort_json = $this->wipe_illegal_char($sort_json); + $str_sig = 'POST' . $get_url . $sort_json; + $sign_str = base64_encode(hash_hmac('sha1', $str_sig, $secretKey, true)); + return $sign_str; + } + return false; + } + + private function wipe_illegal_char($str) + { + $tmp_begin = -1; + $tmp_end = -1; + $str_tmp = ""; + for ($i = 0; $i < strlen($str); $i++) { + if ($str[$i] == "[") { + if ($tmp_begin == -1) + $tmp_begin = $i; + } + if ($str[$i] == "]") { + if ($tmp_end == -1) + $tmp_end = $i; + } + } + for ($j = 0; $j < strlen($str); $j++) { + $str_tmp[$j] = $str[$j]; + if ($tmp_begin != -1 && $tmp_end != -1) { + if ($j < $tmp_begin || $j > $tmp_end) { + if ($str_tmp[$j] == ",") + $str_tmp[$j] = "&"; + if ($str_tmp[$j] == "_") + $str_tmp[$j] = "."; + if ($str_tmp[$j] == "\"") + $str_tmp[$j] = ""; + if ($str_tmp[$j] == "{") + $str_tmp[$j] = ""; + if ($str_tmp[$j] == "}") + $str_tmp[$j] = ""; + if ($str_tmp[$j] == ":") + $str_tmp[$j] = "="; + } + } else { + if ($str_tmp[$j] == ",") + $str_tmp[$j] = "&"; + if ($str_tmp[$j] == "_") + $str_tmp[$j] = "."; + if ($str_tmp[$j] == "\"") + $str_tmp[$j] = ""; + if ($str_tmp[$j] == "{") + $str_tmp[$j] = ""; + if ($str_tmp[$j] == "}") + $str_tmp[$j] = ""; + if ($str_tmp[$j] == ":") + $str_tmp[$j] = "="; + } + } + return implode($str_tmp); + } +} \ No newline at end of file diff --git a/system/return_code.php b/system/return_code.php new file mode 100644 index 0000000..bf6716a --- /dev/null +++ b/system/return_code.php @@ -0,0 +1,22 @@ +