微信小程序会话管理服务器

This commit is contained in:
HNJKSDH
2016-10-28 17:26:21 +08:00
parent f25fa00915
commit 432188095d
25 changed files with 2040 additions and 0 deletions

View File

@@ -0,0 +1,322 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/1
* Time: 15:06
*/
class Auth
{
public function __construct()
{
require_once('application/services/qcloud/minaauth/Cappinfo_Service.php');
require_once('application/services/qcloud/minaauth/Csessioninfo_Service.php');
require_once('system/decrypt_data.php');
require_once('system/return_code.php');
require_once('system/report_data/ready_for_report_data.php');
require_once('system/http_util.php');
require_once('system/db/init_db.php');
}
/**
* @param $code
* @param $appid
* @param $secret
* @return array|int
* 描述登录校验返回id和skey
*/
public function get_id_skey($code, $encrypt_data)
{
$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 {
$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;
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/1
* Time: 15:14
*/
class Cappinfo_Service
{
public function __construct()
{
require_once('system/db/mysql_db.php');
}
/**
* @param $appid
* @param $secret
* @param int $login_duration
* @param int $session_duration
* @return bool
*/
public function insert_cappinfo($params)
{
$insert_sql = 'insert into cAppinfo SET appid = "' . $params['appid'] . '",secret = "' . $params['secret'] . '",qcloud_appid = "'.$params['qcloud_appid'].'",ip="'.$params['ip'].'"';
$mysql_insert = new mysql_db();
return $mysql_insert->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;
}
}
}

View File

@@ -0,0 +1,190 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/1
* Time: 15:15
*/
class Csessioninfo_Service
{
public function __construct()
{
require_once('system/db/mysql_db.php');
}
/**
* @param $skey
* @param $create_time
* @param $last_visit_time
* @param $open_id
* @param $session_key
* @return bool
*/
public function insert_csessioninfo($params)
{
$insert_sql = 'insert into cSessioninfo SET skey = "' . $params['skey'] . '",create_time = ' . $params['create_time'] . ',last_visit_time = ' . $params['last_visit_time'] . ',open_id = "' . $params['openid'] . '",session_key="' . $params['session_key'] . '",user_info=\''.$params['user_info'].'\'';
$mysql_insert = new mysql_db();
return $mysql_insert->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;
}
}
}

11
index.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/2
* Time: 10:54
*/
require_once('system/parse_request.php');
$request = file_get_contents("php://input");
$parse_request = new parse_request();
echo($parse_request->parse_json($request));

23
init_report_data.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/17
* Time: 10:18
*/
require_once('system/report_data/report_data.php');
require_once('system/report_data/ready_for_report_data.php');
require_once "system/load_config.php";
$load_config = new load_config();
$config = $load_config->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));

48
qcloud_report.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/13
* Time: 14:24
*/
require_once('system/report_data/report_data.php');
require_once('system/report_data/ready_for_report_data.php');
require_once "system/load_config.php";
$load_config = new load_config();
$config = $load_config->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();
}

5
sh/check_appid.sh Normal file
View File

@@ -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"

2
sh/init_config.sh Normal file
View File

@@ -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

32
sh/install_appid.sh Normal file
View File

@@ -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;
}
}

28
sh/install_config.sh Normal file
View File

@@ -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;
}
}

9
sh/schedule.sh Normal file
View File

@@ -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

3
sh/schedule_config.sh Normal file
View File

@@ -0,0 +1,3 @@
#!/bin/sh
./install_config.sh 10.141.20.104 Murphy.me appid1 secret1 qcloud_appid
echo "ok"

11
system/conf/config.ini Normal file
View File

@@ -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=

6
system/db/db.ini Normal file
View File

@@ -0,0 +1,6 @@
[db]
host = 127.0.0.1
port = 3306
user_name = root
pass_wd = root
data_base = cAuth

22
system/db/db.sql Normal file
View File

@@ -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;

66
system/db/init_db.php Normal file
View File

@@ -0,0 +1,66 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/12
* Time: 16:15
*/
class init_db {
public function __construct()
{
require_once "mysql_db.php";
}
public function init_db_config($params){
if(isset($params['cdb_ip']) && isset($params['cdb_port']) && isset($params['cdb_user_name']) && isset($params['cdb_pass_wd'])){
$host = $params['cdb_ip'];
$port = $params['cdb_port'];
$user_name = $params['cdb_user_name'];
$pass_wd = $params['cdb_pass_wd'];
$data_base = "cAuth";
$data = "[db]\nhost = $host\nport = $port\nuser_name = $user_name\npass_wd = $pass_wd\ndata_base= $data_base";
$data_path = "system/db/db.ini";
$handle = fopen($data_path,'w');
flock($handle, LOCK_EX);
if (fwrite($handle,$data) === false){
log_message("ERROR","init_db_config_wrong");
flock($handle, LOCK_UN);
fclose($handle);
return false;
}else{
flock($handle, LOCK_UN);
fclose($handle);
return true;
}
}else{
return false;
}
}
public function init_db_table(){
$sql = file_get_contents("system/db/db.sql");
if($sql === false){
return false;
}
$_arr = explode(';', $sql);
$mysql_db = new mysql_db();
if($mysql_db->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;
}
}

102
system/db/mysql_db.php Normal file
View File

@@ -0,0 +1,102 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/1
* Time: 16:47
*/
class mysql_db
{
private $host= null;
private $port= null;
private $user_name= null;
private $pass_wd = null;
private $data_base = null;
public function __construct()
{
require_once "system/load_config.php";
require_once('system/log/log.php');
$load_config = new load_config();
$config = $load_config->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;
}
}
}

41
system/decrypt_data.php Normal file
View File

@@ -0,0 +1,41 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/2
* Time: 10:02
*/
class decrypt_data
{
/**
* @param $encrypt_data
* @param $session_key
* @return bool|string
* 描述:解密数据
*/
public function aes128cbc_Decrypt($encrypt_data, $session_key)
{
$aeskey = base64_decode($session_key);
$iv = $aeskey;
$encryptedData = base64_decode($encrypt_data);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $aeskey, $encryptedData, MCRYPT_MODE_CBC, $iv);
return $this->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));
}
}

70
system/http_util.php Normal file
View File

@@ -0,0 +1,70 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/11
* Time: 9:57
*/
class http_util {
/**
* POST 请求
* @param string $url
* @param array $param
* @return string content
*/
public function http_post($url,$param){
$oCurl = curl_init();
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
}
if (is_string($param)) {
$strPOST = $param;
} else {
$aPOST = array();
foreach($param as $key=>$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;
}
}
}

19
system/load_config.php Normal file
View File

@@ -0,0 +1,19 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/12
* Time: 11:38
*/
class load_config {
/**
* @param $file_path
* @return array
*/
public function fc_load_config($file_path){
$config = parse_ini_file($file_path);
return $config;
}
}

350
system/log/log.php Normal file
View File

@@ -0,0 +1,350 @@
<?php
require_once "system/load_config.php";
if ( ! function_exists('is_php'))
{
/**
* Determines if the current version of PHP is equal to or greater than the supplied value
*
* @param string
* @return bool TRUE if the current version is $version or higher
*/
function is_php($version)
{
static $_is_php;
$version = (string) $version;
if ( ! isset($_is_php[$version]))
{
$_is_php[$version] = version_compare(PHP_VERSION, $version, '>=');
}
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;
}
}
}
}

117
system/parse_request.php Normal file
View File

@@ -0,0 +1,117 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/3
* Time: 11:22
*/
class parse_request
{
public function __construct()
{
require_once('return_code.php');
require_once('application/controllers/qcloud/minaauth/Auth.php');
require_once('log/log.php');
}
/**
* @param $request_json
* @return array|int
* 描述:解析接口名称
*/
public function parse_json($request_json)
{
log_message("info",$request_json);
if ($this->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);
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/12
* Time: 10:11
*/
class ready_for_report_data {
private $report_data_path = 'reportdata/';
public function __construct()
{
require_once "system/load_config.php";
require_once('system/log/log.php');
$load_config = new load_config();
$config = $load_config->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);
}
}
}
}

View File

@@ -0,0 +1,360 @@
<?php
/**
* Created by PhpStorm.
* User: ayisun
* Date: 2016/10/11
* Time: 10:41
*/
class report_data
{
public function __construct()
{
require_once "system/load_config.php";
require_once('system/http_util.php');
require_once('system/log/log.php');
}
/**
* @param $params
* @return bool|string
*/
private function set_report_data($ip,$metricName,$value)
{
$obj=null;
$data = array();
$obj->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);
}
}

22
system/return_code.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
class return_code
{
const MA_OK = 0; //成功返回码
const MA_MYSQL_ERR = 1001; // Mysql错误等
const MA_NO_INTERFACE = 1002; // 接口参数不存在
const MA_PARA_ERR = 1003; //参数错误
const MA_DECRYPT_ERR = 60021; //解密失败
const MA_WEIXIN_NET_ERR = 1005; //连接微信服务器失败
const MA_WEIXIN_CODE_ERR = 40029; //CODE无效
const MA_CHANGE_SESSION_ERR = 1006; //新增修改SESSION失败
const MA_WEIXIN_RETURN_ERR = 1007; //微信返回值错误
const MA_AUTH_ERR = 60012; //鉴权失败
const MA_UPDATE_LASTVISITTIME_ERR = 1008; //更新最近访问时间失败
const MA_REQUEST_ERR = 1009; //请求包不是json
const MA_INTERFACE_ERR = 1010; //接口名称错误
const MA_NO_PARA = 1011; //不存在参数
const MA_NO_APPID = 1012; //不能获取AppID
const MA_INIT_APPINFO_ERR = 1013; //初始化AppID失败
}
//end of script