├── system
├── db
│ ├── db.ini
│ ├── db.sql
│ ├── init_db.php
│ └── mysql_db.php
├── conf
│ └── config.ini
├── load_config.php
├── wx_decrypt_data
│ ├── new
│ │ ├── errorCode.php
│ │ ├── wxBizDataCrypt.php
│ │ └── pkcs7Encoder.php
│ └── old
│ │ └── decrypt_data.php
├── return_code.php
├── http_util.php
├── report_data
│ ├── ready_for_report_data.php
│ └── report_data.php
├── parse_request.php
└── log
│ └── log.php
├── index.php
├── init_report_data.php
├── LICENSE
├── db.sql
├── qcloud_report.php
├── application
├── services
│ └── qcloud
│ │ └── minaauth
│ │ ├── Cappinfo_Service.php
│ │ └── Csessioninfo_Service.php
└── controllers
│ └── qcloud
│ └── minaauth
│ └── Auth.php
└── README.md
/system/db/db.ini:
--------------------------------------------------------------------------------
1 | [db]
2 | host = 127.0.0.1
3 | port = 3306
4 | user_name = root
5 | pass_wd = root
6 | data_base = cAuth
--------------------------------------------------------------------------------
/system/conf/config.ini:
--------------------------------------------------------------------------------
1 | [log]
2 | log_path = log/
3 | log_file_extension = log
4 | log_threshold = 3
5 |
6 | [report_data]
7 | data_path = reportdata/
8 | region=
9 | secret_id=
10 | secretKey=
11 | ip=
--------------------------------------------------------------------------------
/system/load_config.php:
--------------------------------------------------------------------------------
1 | parse_json($request);
13 | log_message("INFO",$return_result);
14 | echo($return_result);
15 |
--------------------------------------------------------------------------------
/system/wx_decrypt_data/new/errorCode.php:
--------------------------------------------------------------------------------
1 |
6 |
7 | *
-41001: encodingAesKey 非法
8 | * -41003: aes 解密失败
9 | * -41004: 解密后得到的buffer非法
10 | * -41005: base64加密失败
11 | * -41016: base64解密失败
12 | *
13 | */
14 | class ErrorCode
15 | {
16 | public static $OK = 0;
17 | public static $IllegalAesKey = -41001;
18 | public static $IllegalIv = -41002;
19 | public static $IllegalBuffer = -41003;
20 | public static $DecodeBase64Error = -41004;
21 | }
22 |
23 | ?>
--------------------------------------------------------------------------------
/system/wx_decrypt_data/old/decrypt_data.php:
--------------------------------------------------------------------------------
1 | stripPkcs7Padding($decrypted);
25 | }
26 |
27 | /**
28 | * 对解密后的明文进行补位删除
29 | * @param text 解密后的明文
30 | * @return 删除填充补位后的明文
31 | */
32 | function stripPkcs7Padding($text)
33 | {
34 |
35 | $pad = ord(substr($text, -1));
36 | if ($pad < 1 || $pad > 32) {
37 | $pad = 0;
38 | }
39 | return substr($text, 0, (strlen($text) - $pad));
40 | }
41 | }
--------------------------------------------------------------------------------
/init_report_data.php:
--------------------------------------------------------------------------------
1 | fc_load_config("system/conf/config.ini");
13 | $region = $config['region'];//用户配置
14 | $secret_id = $config['secret_id'];//用户配置
15 | $secretKey = $config['secretKey'];//用户配置
16 | $ip = $config['ip'];//用户配置
17 |
18 | $report_data = new report_data();
19 | var_dump($report_data->create_namespace($region,$secret_id,$secretKey));
20 | var_dump($report_data->create_metric($region,$secret_id,$secretKey,"authsucessrate","authsucessrate"));
21 | var_dump($report_data->create_metric($region,$secret_id,$secretKey,"loginsucessrate","loginsucessrate"));
22 | var_dump($report_data->bind_alarm_rule_objects($region,$secret_id,$secretKey,"authsucessrate",$ip));
23 | var_dump($report_data->bind_alarm_rule_objects($region,$secret_id,$secretKey,"loginsucessrate",$ip));
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | LICENSE - "MIT License"
2 |
3 | Copyright (c) 2016 by Tencent Cloud
4 |
5 | Permission is hereby granted, free of charge, to any person
6 | obtaining a copy of this software and associated documentation
7 | files (the "Software"), to deal in the Software without
8 | restriction, including without limitation the rights to use,
9 | copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the
11 | Software is furnished to do so, subject to the following
12 | conditions:
13 |
14 | The above copyright notice and this permission notice shall be
15 | included in all copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 | OTHER DEALINGS IN THE SOFTWARE.
25 |
--------------------------------------------------------------------------------
/system/return_code.php:
--------------------------------------------------------------------------------
1 | sessionKey = $sessionKey;
27 | $this->appid = $appid;
28 | }
29 |
30 |
31 | /**
32 | * 检验数据的真实性,并且获取解密后的明文.
33 | * @param $encryptedData string 加密的用户数据
34 | * @param $iv string 与用户数据一同返回的初始向量
35 | * @param $data string 解密后的原文
36 | *
37 | * @return int 成功0,失败返回对应的错误码
38 | */
39 | public function decryptData( $encryptedData, $iv, &$data )
40 | {
41 | if (strlen($this->sessionKey) != 24) {
42 | return ErrorCode::$IllegalAesKey;
43 | }
44 | $aesKey=base64_decode($this->sessionKey);
45 |
46 |
47 | if (strlen($iv) != 24) {
48 | return ErrorCode::$IllegalIv;
49 | }
50 | $aesIV=base64_decode($iv);
51 |
52 | $aesCipher=base64_decode($encryptedData);
53 |
54 | $pc = new Prpcrypt($aesKey);
55 | $result = $pc->decrypt($aesCipher,$aesIV);
56 |
57 | if ($result[0] != 0) {
58 | return $result[0];
59 | }
60 |
61 | $dataObj=json_decode( $result[1] );
62 | if( $dataObj == NULL )
63 | {
64 | return ErrorCode::$IllegalBuffer;
65 | }
66 | if( $dataObj->watermark->appid != $this->appid )
67 | {
68 | return ErrorCode::$IllegalBuffer;
69 | }
70 | $data = $result[1];
71 | return ErrorCode::$OK;
72 | }
73 |
74 | }
75 |
76 |
--------------------------------------------------------------------------------
/qcloud_report.php:
--------------------------------------------------------------------------------
1 | fc_load_config("system/conf/config.ini");
14 | $region = $config['region'];//用户配置
15 | $secret_id = $config['secret_id'];//用户配置
16 | $secretKey = $config['secretKey'];//用户配置
17 | $ip = $config['ip'];//用户配置
18 |
19 | $ready_for_report_data = new ready_for_report_data();
20 | $report_data = new report_data();
21 | $contents = $ready_for_report_data->check_data();
22 | if($contents){
23 | $arr_contents = json_decode($contents,true);
24 | $arr_report_data['ip'] = $arr_contents['ip'];
25 | $arr_report_data['login_count'] = "login_count";
26 | $arr_report_data['login_count_value'] = $arr_contents['login_count'];
27 | $arr_report_data['login_sucess_rate'] = "login_sucess_rate";
28 | if($arr_contents['login_count']===0){
29 | $arr_report_data['login_sucess_value'] = 0 ;
30 | }else{
31 | $arr_report_data['login_sucess_value'] = ($arr_contents['login_sucess']/$arr_contents['login_count'])*100;
32 | }
33 | $arr_report_data['auth_count'] = "auth_count";
34 | $arr_report_data['auth_count_value'] = $arr_contents['login_count'];
35 |
36 | $arr_report_data['auth_sucess_rate']="auth_sucess_rate";
37 | if($arr_report_data['auth_count']===0){
38 | $arr_report_data['auth_sucess_value']=0;
39 | }else{
40 |
41 | }
42 | $arr_report_data['auth_sucess_value'] = ($arr_contents['auth_sucess']/$arr_contents['auth_count'])*100;
43 |
44 | $report_data->report_data($region, $secret_id, $secretKey,$ip,"authsucessrate",$arr_report_data['auth_sucess_value']);
45 | $report_data->report_data($region, $secret_id, $secretKey,$ip,"loginsucessrate",$arr_report_data['login_sucess_value']);
46 |
47 | $ready_for_report_data->deletfile();
48 | }
49 |
--------------------------------------------------------------------------------
/system/http_util.php:
--------------------------------------------------------------------------------
1 | $val){
28 | $aPOST[] = $key."=".urlencode($val);
29 | }
30 | $strPOST = join("&", $aPOST);
31 | }
32 | curl_setopt($oCurl, CURLOPT_URL, $url);
33 | curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
34 | curl_setopt($oCurl, CURLOPT_POST,true);
35 | curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
36 | $sContent = curl_exec($oCurl);
37 | $aStatus = curl_getinfo($oCurl);
38 | curl_close($oCurl);
39 | if(intval($aStatus["http_code"])==200){
40 | return $sContent;
41 | }else{
42 | return false;
43 | }
44 | }
45 |
46 | /**
47 | * GET 请求
48 | * @param string $url
49 | */
50 | public function http_get($url){
51 | $oCurl = curl_init();
52 | if(stripos($url,"https://")!==FALSE){
53 | curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
54 | curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
55 | }
56 | curl_setopt($oCurl, CURLOPT_URL, $url);
57 | curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
58 | $sContent = curl_exec($oCurl);
59 | $aStatus = curl_getinfo($oCurl);
60 | curl_close($oCurl);
61 | if(intval($aStatus["http_code"])==200){
62 | return $sContent;
63 | }else{
64 | return false;
65 | }
66 | }
67 |
68 |
69 |
70 | }
--------------------------------------------------------------------------------
/system/db/init_db.php:
--------------------------------------------------------------------------------
1 | init_db("DROP DATABASE IF EXISTS `cAuth`")){
50 | if($mysql_db->init_db("CREATE DATABASE `cAuth`")){
51 | foreach ($_arr as $_value) {
52 | if(!empty($_value)){
53 | if(!$mysql_db->query_db($_value.';'))
54 | return false;
55 | }
56 | }
57 | }
58 | else{
59 | return false;
60 | }
61 | }else{
62 | return false;
63 | }
64 | return true;
65 | }
66 | }
--------------------------------------------------------------------------------
/system/wx_decrypt_data/new/pkcs7Encoder.php:
--------------------------------------------------------------------------------
1 | 32) {
47 | $pad = 0;
48 | }
49 | return substr($text, 0, (strlen($text) - $pad));
50 | }
51 |
52 | }
53 |
54 | /**
55 | * Prpcrypt class
56 | *
57 | *
58 | */
59 | class Prpcrypt
60 | {
61 | public $key;
62 |
63 | function Prpcrypt( $k )
64 | {
65 | $this->key = $k;
66 | }
67 |
68 | /**
69 | * 对密文进行解密
70 | * @param string $aesCipher 需要解密的密文
71 | * @param string $aesIV 解密的初始向量
72 | * @return string 解密得到的明文
73 | */
74 | public function decrypt( $aesCipher, $aesIV )
75 | {
76 |
77 | try {
78 |
79 | $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
80 |
81 | mcrypt_generic_init($module, $this->key, $aesIV);
82 |
83 | //解密
84 | $decrypted = mdecrypt_generic($module, $aesCipher);
85 | mcrypt_generic_deinit($module);
86 | mcrypt_module_close($module);
87 | } catch (Exception $e) {
88 | return array(ErrorCode::$IllegalBuffer, null);
89 | }
90 |
91 |
92 | try {
93 | //去除补位字符
94 | $pkc_encoder = new PKCS7Encoder;
95 | $result = $pkc_encoder->decode($decrypted);
96 |
97 | } catch (Exception $e) {
98 | //print $e;
99 | return array(ErrorCode::$IllegalBuffer, null);
100 | }
101 | return array(0, $result);
102 | }
103 | }
104 |
105 | ?>
--------------------------------------------------------------------------------
/application/services/qcloud/minaauth/Cappinfo_Service.php:
--------------------------------------------------------------------------------
1 | query_db($insert_sql);
29 | }
30 |
31 | /**
32 | * @param $appid
33 | * @param $secret
34 | * @param $login_duration
35 | * @param $session_duration
36 | * @return bool
37 | */
38 | public function update_cappinfo($params)
39 | {
40 | $update_sql = 'update cAppinfo set login_duration = ' . $params['login_duration'] . ',session_duration=' . $params['session_duration'] . ',$secret = "' . $params['secret'] . '" where appid = "' . $params['appid'] . '"';
41 | $mysql_update = new mysql_db();
42 | return $mysql_update->query_db($update_sql);
43 | }
44 |
45 | /**
46 | * @param $appid
47 | * @return bool
48 | */
49 | public function delete_cappinfo()
50 | {
51 | $delete_sql = 'delete from cAppinfo';
52 | $mysql_delete = new mysql_db();
53 | return $mysql_delete->query_db($delete_sql);
54 | }
55 |
56 |
57 | /**
58 | * @param $appid
59 | * @return array|bool
60 | */
61 | public function select_cappinfo()
62 | {
63 | $select_sql = 'select * from cAppinfo';
64 | $mysql_select = new mysql_db();
65 | $result = $mysql_select->select_db($select_sql);
66 | if ($result !== false && !empty($result)) {
67 | $arr_result = array();
68 | while ($row = mysql_fetch_array($result)) {
69 | $arr_result['appid'] = $row['appid'];
70 | $arr_result['secret'] = $row['secret'];
71 | $arr_result['login_duration'] = $row['login_duration'];
72 | $arr_result['session_duration'] = $row['session_duration'];
73 | $arr_result['qcloud_appid'] = $row['qcloud_appid'];
74 | $arr_result['ip'] = $row['ip'];
75 | }
76 | return $arr_result;
77 | } else {
78 | return false;
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/system/db/mysql_db.php:
--------------------------------------------------------------------------------
1 | fc_load_config("system/db/db.ini");
24 | $this->host = $config['host'];
25 | $this->port = $config['port'];
26 | $this->user_name = $config['user_name'];
27 | $this->pass_wd = $config['pass_wd'];
28 | $this->data_base = $config['data_base'];
29 | }
30 |
31 | /**
32 | * @param $sql
33 | * @return string
34 | * 描述:安全过滤sql,防止sql注入
35 | */
36 | function safe($sql)
37 | {
38 | if (get_magic_quotes_gpc()) {
39 | $sql = stripslashes($sql);
40 | }
41 | $sql = mysql_real_escape_string($sql);
42 | return $sql;
43 | }
44 |
45 | /**
46 | * @param $sql
47 | * @return bool
48 | * 描述:执行Mysql增删改操作
49 | */
50 | public function query_db($sql)
51 | {
52 | $con = mysql_connect($this->host . ':' . $this->port, $this->user_name, $this->pass_wd);
53 | if ($con) {
54 | mysql_select_db($this->data_base, $con);
55 | $mysql_result = mysql_query($sql);
56 | if ($mysql_result === false) {
57 | mysql_close($con);
58 | log_message("ERROR","$sql mysql_err");
59 | return false;
60 | }
61 | mysql_close($con);
62 | return true;
63 | } else {
64 | log_message("ERROR","$sql mysql_connect_err");
65 | return false;
66 | }
67 | }
68 |
69 | /**
70 | * @param $sql
71 | * @return bool|resource
72 | * 描述:执行mysql查询操作
73 | */
74 | public function select_db($sql)
75 | {
76 | $con = mysql_connect($this->host . ':' . $this->port, $this->user_name, $this->pass_wd);
77 | if ($con) {
78 | mysql_select_db($this->data_base, $con);
79 | $arr_result = mysql_query($sql);
80 | mysql_close($con);
81 | if(mysql_num_rows($arr_result) < 1)
82 | return false;
83 | return $arr_result;
84 | } else {
85 | log_message("ERROR","$sql mysql_connect_err");
86 | return false;
87 | }
88 | }
89 |
90 | public function init_db($sql){
91 | $con = mysql_connect($this->host . ':' . $this->port, $this->user_name, $this->pass_wd);
92 | if ($con) {
93 | $result = mysql_query("$sql",$con);
94 | if($result===false){
95 | log_message("ERROR","$sql mysql_err");
96 | return false;
97 | }
98 | return true;
99 | }else{
100 | log_message("ERROR","$sql mysql_connect_err");
101 | return false;
102 | }
103 | }
104 | }
--------------------------------------------------------------------------------
/system/report_data/ready_for_report_data.php:
--------------------------------------------------------------------------------
1 | fc_load_config("system/conf/config.ini");
19 | $this->report_data_path = $config['data_path'];
20 | }
21 |
22 | /**
23 | * @param $report_data
24 | */
25 | public function write_report_data($report_data){
26 | file_exists($this->report_data_path) OR mkdir($this->report_data_path, 0755, TRUE);
27 | $data_path = $this->report_data_path."data";
28 | $handle = fopen($data_path,'w');
29 | flock($handle, LOCK_EX);
30 | $write_result = fwrite($handle,$report_data);
31 | if ($write_result === false){
32 | log_message("ERROR","$report_data write_report_data_wrong");
33 | }
34 | flock($handle, LOCK_UN);
35 | fclose($handle);
36 | return $write_result;
37 | }
38 |
39 | /**
40 | * @return string
41 | */
42 | public function read_report_data(){
43 | $data_path = $this->report_data_path."data";
44 | if(!file_exists($data_path)){
45 | log_message("ERROR","report_data_not_exit");
46 | return false;
47 | }
48 | $handle = fopen($data_path, "r");
49 | $contents = fread($handle, filesize($data_path));
50 | fclose($handle);
51 | if($contents===false){
52 | log_message("ERROR","read_report_data_wrong");
53 | }
54 | return $contents;
55 | }
56 |
57 |
58 | public function check_data(){
59 | $contents = $this->read_report_data();
60 | if($contents){
61 | if($this->is_json($contents)){
62 | $json_contents = json_decode($contents, true);
63 | 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'])){
64 | return $contents;
65 | }
66 | return false;
67 | }
68 | return false;
69 | }else{
70 | return false;
71 | }
72 | }
73 |
74 | public function ready_data($type){
75 | $content = $this->check_data();
76 | if($content != false){
77 | $arr_content = json_decode($content,true);
78 | $arr_content[$type]++;
79 | $json_content = json_encode($arr_content);
80 | return $this->write_report_data($json_content);
81 | }
82 | return false;
83 | }
84 |
85 | public function is_json($str)
86 | {
87 | json_decode($str);
88 | return (json_last_error() == JSON_ERROR_NONE);
89 | }
90 |
91 | public function deletfile(){
92 | $data_path = $this->report_data_path."data";
93 | if(is_file($data_path)){
94 | if(!unlink($data_path)){
95 | chmod($data_path,0777);
96 | unlink($data_path);
97 | }
98 | }
99 | }
100 | }
--------------------------------------------------------------------------------
/system/parse_request.php:
--------------------------------------------------------------------------------
1 | is_json($request_json)) {
28 | $json_decode = json_decode($request_json, true);
29 | if (!isset($json_decode['interface']['interfaceName'])) {
30 | $ret['returnCode'] = return_code::MA_NO_INTERFACE;
31 | $ret['returnMessage'] = 'NO_INTERFACENAME_PARA';
32 | $ret['returnData'] = '';
33 | } else if (!isset($json_decode['interface']['para'])) {
34 | $ret['returnCode'] = return_code::MA_NO_PARA;
35 | $ret['returnMessage'] = 'NO_PARA';
36 | $ret['returnData'] = '';
37 | } else {
38 | if ($json_decode['interface']['interfaceName'] == 'qcloud.cam.id_skey') {
39 | if (isset($json_decode['interface']['para']['code'])&&isset($json_decode['interface']['para']['encrypt_data'])) {
40 | $code = $json_decode['interface']['para']['code'];
41 | $encrypt_data = $json_decode['interface']['para']['encrypt_data'];
42 | $auth = new Auth();
43 | if(!isset($json_decode['interface']['para']['iv']))
44 | $ret = $auth->get_id_skey($code,$encrypt_data);
45 | else{
46 | $iv = $json_decode['interface']['para']['iv'];
47 | $ret = $auth->get_id_skey($code,$encrypt_data,$iv);
48 | }
49 | } else {
50 | $ret['returnCode'] = return_code::MA_PARA_ERR;
51 | $ret['returnMessage'] = 'PARA_ERR';
52 | $ret['returnData'] = '';
53 | }
54 | } else if ($json_decode['interface']['interfaceName'] == 'qcloud.cam.auth') {
55 | if (isset($json_decode['interface']['para']['id']) && isset($json_decode['interface']['para']['skey'])) {
56 | $id = $json_decode['interface']['para']['id'];
57 | $skey = $json_decode['interface']['para']['skey'];
58 | $auth = new Auth();
59 | $ret = $auth->auth($id, $skey);
60 | } else {
61 | $ret['returnCode'] = return_code::MA_PARA_ERR;
62 | $ret['returnMessage'] = 'PARA_ERR';
63 | $ret['returnData'] = '';
64 | }
65 | } else if ($json_decode['interface']['interfaceName'] == 'qcloud.cam.decrypt') {
66 | if (isset($json_decode['interface']['para']['id']) && isset($json_decode['interface']['para']['skey']) && isset($json_decode['interface']['para']['encrypt_data'])) {
67 | $id = $json_decode['interface']['para']['id'];
68 | $skey = $json_decode['interface']['para']['skey'];
69 | $encrypt_data = $json_decode['interface']['para']['encrypt_data'];
70 | $auth = new Auth();
71 | $ret = $auth->decrypt($id, $skey, $encrypt_data);
72 | } else {
73 | $ret['returnCode'] = return_code::MA_PARA_ERR;
74 | $ret['returnMessage'] = 'PARA_ERR';
75 | $ret['returnData'] = '';
76 | }
77 | }else if($json_decode['interface']['interfaceName'] == 'qcloud.cam.initdata'){
78 | 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'])
79 | && 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']) ) {
80 | $appid = $json_decode['interface']['para']['appid'];
81 | $secret = $json_decode['interface']['para']['secret'];
82 | $qcloud_appid = $json_decode['interface']['para']['qcloud_appid'];
83 | $ip = $json_decode['interface']['para']['ip'];
84 | $cdb_ip = $json_decode['interface']['para']['cdb_ip'];
85 | $cdb_port = $json_decode['interface']['para']['cdb_port'];
86 | $cdb_user_name = $json_decode['interface']['para']['cdb_user_name'];
87 | $cdb_pass_wd = $json_decode['interface']['para']['cdb_pass_wd'];
88 | $auth = new Auth();
89 | $ret = $auth->init_data($appid,$secret,$qcloud_appid,$ip,$cdb_ip,$cdb_port,$cdb_user_name,$cdb_pass_wd);
90 | } else {
91 | $ret['returnCode'] = return_code::MA_PARA_ERR;
92 | $ret['returnMessage'] = 'PARA_ERR';
93 | $ret['returnData'] = '';
94 | }
95 | } else {
96 | $ret['returnCode'] = return_code::MA_INTERFACE_ERR;
97 | $ret['returnMessage'] = 'INTERFACENAME_PARA_ERR';
98 | $ret['returnData'] = '';
99 | }
100 | }
101 | } else {
102 | $ret['returnCode'] = return_code::MA_REQUEST_ERR;
103 | $ret['returnMessage'] = 'REQUEST_IS_NOT_JSON';
104 | $ret['returnData'] = '';
105 | }
106 | $ret['version'] = 1;
107 | $ret['componentName'] = "MA";
108 | log_message("info",json_encode($ret));
109 | return json_encode($ret);
110 | }
111 |
112 | /**
113 | * @param $str
114 | * @return bool
115 | * 描述:判断字符串是不是合法的json
116 | */
117 | private function is_json($str)
118 | {
119 | json_decode($str);
120 | return (json_last_error() == JSON_ERROR_NONE);
121 | }
122 | }
--------------------------------------------------------------------------------
/application/services/qcloud/minaauth/Csessioninfo_Service.php:
--------------------------------------------------------------------------------
1 | query_db($insert_sql);
25 | }
26 |
27 |
28 |
29 | public function update_csessioninfo_time($params)
30 | {
31 | $update_sql = 'update cSessionInfo set last_visit_time = "' . $params['last_visit_time'] . '" where uuid = "' . $params['uuid'].'"';
32 | $mysql_update = new mysql_db();
33 | return $mysql_update->query_db($update_sql);
34 | }
35 |
36 |
37 | public function update_csessioninfo($params)
38 | {
39 | $update_sql = 'update cSessionInfo set session_key= "'.$params['session_key'].'",create_time = "'.$params['create_time'].'" ,last_visit_time = "' . $params['last_visit_time'] . '",skey = "' . $params['skey'] .'",user_info=\''.$params['user_info'].'\' where uuid = "' . $params['uuid'].'"';
40 | $mysql_update = new mysql_db();
41 | return $mysql_update->query_db($update_sql);
42 | }
43 |
44 |
45 |
46 | public function delete_csessioninfo($open_id)
47 | {
48 | $delete_sql = 'delete from cSessionInfo where open_id = "' . $open_id . '"';
49 | $mysql_delete = new mysql_db();
50 | return $mysql_delete->query_db($delete_sql);
51 | }
52 |
53 |
54 | public function delete_csessioninfo_by_id_skey($params)
55 | {
56 | $delete_sql = 'delete from cSessionInfo where uuid = "' . $params['uuid'].'"';
57 | $mysql_delete = new mysql_db();
58 | return $mysql_delete->query_db($delete_sql);
59 | }
60 |
61 |
62 | public function select_csessioninfo($params)
63 | {
64 | $select_sql = 'select * from cSessionInfo where uuid = "' . $params['uuid'] . '" and skey = "' . $params['skey'] . '"';
65 | $mysql_select = new mysql_db();
66 | $result = $mysql_select->select_db($select_sql);
67 | if ($result !== false && !empty($result)) {
68 | $arr_result = array();
69 | while ($row = mysql_fetch_array($result)) {
70 | $arr_result['id'] = $row['id'];
71 | $arr_result['uuid'] = $row['uuid'];
72 | $arr_result['skey'] = $row['skey'];
73 | $arr_result['create_time'] = $row['create_time'];
74 | $arr_result['last_visit_time'] = $row['last_visit_time'];
75 | $arr_result['open_id'] = $row['open_id'];
76 | $arr_result['session_key'] = $row['session_key'];
77 | $arr_result['user_info'] = $row['user_info'];
78 | }
79 | return $arr_result;
80 | } else {
81 | return false;
82 | }
83 | }
84 |
85 |
86 | public function get_id_csessioninfo($open_id)
87 | {
88 | $select_sql = 'select uuid from cSessionInfo where open_id = "' . $open_id . '"';
89 | $mysql_select = new mysql_db();
90 | $result = $mysql_select->select_db($select_sql);
91 | if ($result !== false && !empty($result)) {
92 | $id = false;
93 | while ($row = mysql_fetch_array($result)) {
94 | $id = $row['uuid'];
95 | }
96 | return $id;
97 | } else {
98 | return false;
99 | }
100 | }
101 |
102 |
103 | public function check_session_for_login($params){
104 | $select_sql = 'select * from cSessionInfo where open_id = "' . $params['openid'] . '"';
105 | $mysql_select = new mysql_db();
106 | $result = $mysql_select->select_db($select_sql);
107 | if ($result !== false && !empty($result)) {
108 | $create_time = false;
109 | while ($row = mysql_fetch_array($result)) {
110 | $create_time = strtotime($row['create_time']);
111 | }
112 | if($create_time == false){
113 | return false;
114 | }else{
115 | $now_time = time();
116 | if(($now_time-$create_time)/86400>$params['login_duration']){
117 | //$this->update_csessioninfo($params);
118 | return true;
119 | }else{
120 | return true;
121 | }
122 | }
123 | } else {
124 | return true;
125 | }
126 | }
127 |
128 |
129 |
130 | public function check_session_for_auth($params){
131 | $result = $this->select_csessioninfo($params);
132 | if(!empty($result) && $result !== false && count($result) != 0){
133 | $now_time = time();
134 | $create_time = strtotime($result['create_time']);
135 | $last_visit_time = strtotime($result['last_visit_time']);
136 | if(($now_time-$create_time)/86400>$params['login_duration']) {
137 | //$this->delete_csessioninfo_by_id_skey($params);
138 | return false;
139 | }else if(($now_time-$last_visit_time)>$params['session_duration']){
140 | return false;
141 | }else{
142 | $params['last_visit_time'] = date('Y-m-d H:i:s',$now_time);
143 | $this->update_csessioninfo_time($params);
144 | return $result['user_info'];
145 | }
146 | }else{
147 | return false;
148 | }
149 | }
150 |
151 |
152 | public function change_csessioninfo($params)
153 | {
154 | if($this->check_session_for_login($params)){
155 | $uuid = $this->get_id_csessioninfo($params['openid']);
156 | if ($uuid != false) {
157 | $params['uuid'] = $uuid;
158 | if ($this->update_csessioninfo($params))
159 | return $uuid;
160 | else
161 | return false;
162 | } else {
163 | return $this->insert_csessioninfo($params);
164 | }
165 | }else{
166 | return false;
167 | }
168 | }
169 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Wafer 会话服务器
2 | ===============
3 |
4 | 本项目是 [Wafer](https://github.com/tencentyun/wafer) 组成部分,提供会话服务供 SDK 或独立使用。
5 |
6 | 会话服务的实现细请参考 [Wiki](https://github.com/tencentyun/wafer/wiki/%E4%BC%9A%E8%AF%9D%E6%9C%8D%E5%8A%A1)。
7 |
8 |
9 | ## 接口协议
10 |
11 | ### 请求
12 |
13 | 会话服务器提供 HTTP 接口来实现会话管理,下面是协议说明。
14 |
15 | * 协议类型:`HTTP`
16 | * 传输方式:`POST`
17 | * 编码类型:`UTF-8`
18 | * 编码格式:`JSON`
19 |
20 | 请求示例:
21 |
22 | ```http
23 | POST /mina_auth/ HTTP/1.1
24 | Content-Type: application/json;charset=utf-8
25 |
26 | {
27 | "version": 1,
28 | "componentName": "MA",
29 | "interface": {
30 | "interfaceName": "qcloud.cam.id_skey",
31 | "para": { "code": "...", "encrypt_data": "..." }
32 | }
33 | }
34 | ```
35 |
36 | ### 响应
37 |
38 | HTTP 输出为响应内容,下面是响应内容说明:
39 |
40 | * 内容编码:`UTF-8`
41 | * 内容格式:`JSON`
42 |
43 | 响应示例:
44 |
45 | ```json
46 | {
47 | "returnCode": 0,
48 | "returnMessage": "OK",
49 | "returnData": {
50 | "id": "...",
51 | "skey": "..."
52 | }
53 | }
54 | ```
55 |
56 | * `returnCode` - 返回码,如果成功则取值为 `0`,如果失败则取值为具体错误码;
57 | * `returnMessage` - 如果返回码非零,内容为出错信息;
58 | * `returnData` - 返回的数据
59 |
60 | ### qcloud.cam.id_skey
61 |
62 | `qcloud.cam.id_skey` 处理用户登录请求。
63 |
64 | 使用示例:
65 |
66 | ```sh
67 | curl -i -d'{"version":1,"componentName":"MA","interface":{"interfaceName":"qcloud.cam.id_skey","para":{"code":"001EWYiD1CVtKg0jXGjD1e6WiD1EWYiC","encrypt_data":"DNlJKYA0mJ3+RDXD/syznaLVLlaF4drGzeZvJFmjnEKtOAi37kAzC/1tCBr7KqGX8EpiLuWl8qt/kcH9a4LxDC5LQvlRLJlDogTEIwtlT/2jBWBuWwBC3vWFhm7Uuq5AOLZV+xG9UmWPKECDZX9UZpWcPRGQpiY8OOUNBAywVniJv6rC2eADFimdRR2qPiebdC3cry7QAvgvttt1Wk56Nb/1TmIbtJRTay5wb+6AY1H7AT1xPoB6XAXW3RqODXtRR0hZT1s/o5y209Vcc6EBal5QdsbJroXa020ZSD62EnlrOwgYnXy5c8SO+bzNAfRw59SVbI4wUNYz6kJb4NDn+y9dlASRjlt8Rau4xTQS+fZSi8HHUwkwE6RRak3qo8YZ7FWWbN2uwUKgQNlc/MfAfLRcfQw4XUqIdn9lxtRblaY="}}}' http://127.0.0.1/mina_auth/
68 | ```
69 |
70 | 响应数据:
71 |
72 | * `id` - 会话 id
73 | * `skey` - 会话 skey
74 | * `userInfo` - 用户信息
75 |
76 | ### qcloud.cam.auth
77 |
78 | 使用 `qcloud.cam.auth` 接口检查用户登录态。
79 |
80 | 响应数据:
81 |
82 | * `true` - 登录态有效
83 | * `false` - 登录态无效
84 |
85 | ### 错误码
86 |
87 |
88 |
89 | | 错误码 |
90 | 解释 |
91 |
92 |
93 | | 0 |
94 | 成功 |
95 |
96 |
97 | | 1001 |
98 | 数据库错误 |
99 |
100 |
101 | | 1002 |
102 | 接口不存在 |
103 |
104 |
105 | | 1003 |
106 | 参数错误 |
107 |
108 |
109 | | 1005 |
110 | 连接微信服务器失败 |
111 |
112 |
113 | | 1006 |
114 | 新增或修改 SESSION 失败 |
115 |
116 |
117 | | 1007 |
118 | 微信返回值错误 |
119 |
120 |
121 | | 1008 |
122 | 更新最近访问时间失败 |
123 |
124 |
125 | | 1009 |
126 | 请求包不是json |
127 |
128 |
129 | | 1010 |
130 | 接口名称错误 |
131 |
132 |
133 | | 1011 |
134 | 参数不存在 |
135 |
136 |
137 | | 1012 |
138 | 不能获取 AppID |
139 |
140 |
141 | | 1013 |
142 | 初始化 AppID 失败 |
143 |
144 |
145 | | 40029 |
146 | CODE 无效 |
147 |
148 |
149 | | 60021 |
150 | 解密失败 |
151 |
152 |
153 | | 60012 |
154 | 鉴权失败 |
155 |
156 |
157 |
158 |
159 |
160 | ## 数据库设计
161 |
162 | 全局信息表 `cAppInfo` 保存会话服务所需要的配置项。
163 |
164 |
165 |
166 |
167 | | Field |
168 | Type |
169 | Null |
170 | key |
171 | Extra |
172 |
173 |
174 | | appid |
175 | varchar(200) |
176 | NO |
177 | PRI |
178 | 申请微信小程序开发者时,微信分配的 appId |
179 |
180 |
181 | | secret |
182 | varchar(300) |
183 | NO |
184 | |
185 | 申请微信小程序开发者时,微信分配的 appSecret |
186 |
187 |
188 | | login_duration |
189 | int(11) |
190 | NO |
191 | |
192 | 登录过期时间,单位为天,默认 30 天 |
193 |
194 |
195 | | session_duration |
196 | int(11) |
197 | NO |
198 | |
199 | 会话过期时间,单位为秒,默认为 2592000 秒(即30天) |
200 |
201 |
202 |
203 |
204 |
205 |
206 | 会话记录 `cSessionInfo` 保存每个会话的数据。
207 |
208 |
209 |
210 |
211 | | Field |
212 | Type |
213 | Null |
214 | key |
215 | Extra |
216 |
217 |
218 | | id |
219 | int(11) |
220 | NO |
221 | MUL |
222 | 会话 ID(自增长) |
223 |
224 |
225 | | uuid |
226 | varchar(100) |
227 | NO |
228 | |
229 | 会话 uuid |
230 |
231 |
232 | | skey |
233 | varchar(100) |
234 | NO |
235 | |
236 | 会话 Skey |
237 |
238 |
239 | | create_time |
240 | datetime |
241 | NO |
242 | |
243 | 会话创建时间,用于判断会话对应的 open_id 和 session_key 是否过期(是否超过 `cAppInfo` 表中字段 `login_duration` 配置的天数) |
244 |
245 |
246 | | last_visit_time |
247 | datetime |
248 | NO |
249 | |
250 | 最近访问时间,用于判断会话是否过期(是否超过 `cAppInfo` 表中字段 `session_duration` 的配置的秒数) |
251 |
252 |
253 | | open_id |
254 | varchar(100) |
255 | NO |
256 | MUL |
257 | 微信服务端返回的 `open_id` 值 |
258 |
259 |
260 | | session_key |
261 | varchar(100) |
262 | NO |
263 | |
264 | 微信服务端返回的 `session_key` 值 |
265 |
266 |
267 | | user_info |
268 | varchar(2048) |
269 | YES |
270 | |
271 | 已解密的用户数据 |
272 |
273 |
274 |
275 |
276 | 建数据库的详细 SQL 脚本请参考 [db.sql](https://github.com/tencentyun/wafer-session-server/blob/master/db.sql)
277 |
278 |
279 | ## 搭建会话管理服务器
280 |
281 | 选择合适的方式[部署](https://github.com/tencentyun/wafer/wiki#%E9%83%A8%E7%BD%B2%E6%96%B9%E5%BC%8F) Wafer 服务后,按照部署类型:
282 |
283 | * 自动部署 - 无需进行任何操作,会话服务器已经可以使用
284 | * 镜像部署 - 按照下面步骤进行初始化工作
285 | * 自行部署 - 按照下面步骤进行初始化工作
286 |
287 |
288 | ### 环境准备
289 |
290 | 确保机器中已安装 LAMP 环境。
291 |
292 | ### 代码部署
293 |
294 | 把本项目代码部署到 `/opt/lampp/htdocs/mina_auth` 目录中。
295 |
296 | ### 自动建表
297 |
298 | 执行下面命令创建运行时所需表:
299 |
300 | ```sh
301 | /opt/lampp/bin/mysql -u root -p mypassword < /opt/lampp/htdocs/mina_auth/system/db/db.sql
302 | ```
303 |
304 | ## 初始化 appId 和 appSecret
305 |
306 | 登录到 MySql 后,手动插入配置到 `cAuth` 表中。
307 |
308 | ```sh
309 | /opt/lampp/bin/mysql -u root -p root #登录本地mysql
310 | use cAuth;
311 | insert into cAppinfo set appid='Your appid',secret='Your secret';
312 | ```
313 |
314 | ### 测试服务可用性
315 |
316 | ```sh
317 | curl -i -d'{"version":1,"componentName":"MA","interface":{"interfaceName":"qcloud.cam.id_skey","para":{"code":"001EWYiD1CVtKg0jXGjD1e6WiD1EWYiC","encrypt_data":"DNlJKYA0mJ3+RDXD/syznaLVLlaF4drGzeZvJFmjnEKtOAi37kAzC/1tCBr7KqGX8EpiLuWl8qt/kcH9a4LxDC5LQvlRLJlDogTEIwtlT/2jBWBuWwBC3vWFhm7Uuq5AOLZV+xG9UmWPKECDZX9UZpWcPRGQpiY8OOUNBAywVniJv6rC2eADFimdRR2qPiebdC3cry7QAvgvttt1Wk56Nb/1TmIbtJRTay5wb+6AY1H7AT1xPoB6XAXW3RqODXtRR0hZT1s/o5y209Vcc6EBal5QdsbJroXa020ZSD62EnlrOwgYnXy5c8SO+bzNAfRw59SVbI4wUNYz6kJb4NDn+y9dlASRjlt8Rau4xTQS+fZSi8HHUwkwE6RRak3qo8YZ7FWWbN2uwUKgQNlc/MfAfLRcfQw4XUqIdn9lxtRblaY="}}}' http://127.0.0.1/mina_auth/
318 | ```
319 |
320 |
321 |
--------------------------------------------------------------------------------
/system/log/log.php:
--------------------------------------------------------------------------------
1 | =');
20 | }
21 |
22 | return $_is_php[$version];
23 | }
24 | }
25 |
26 | if ( ! function_exists('is_really_writable'))
27 | {
28 | /**
29 | * Tests for file writability
30 | *
31 | * is_writable() returns TRUE on Windows servers when you really can't write to
32 | * the file, based on the read-only attribute. is_writable() is also unreliable
33 | * on Unix servers if safe_mode is on.
34 | *
35 | * @link https://bugs.php.net/bug.php?id=54709
36 | * @param string
37 | * @return bool
38 | */
39 | function is_really_writable($file)
40 | {
41 | // If we're on a Unix server with safe_mode off we call is_writable
42 | if (DIRECTORY_SEPARATOR === '/' && (is_php('5.4') OR ! ini_get('safe_mode')))
43 | {
44 | return is_writable($file);
45 | }
46 |
47 | /* For Windows servers and safe_mode "on" installations we'll actually
48 | * write a file then read it. Bah...
49 | */
50 | if (is_dir($file))
51 | {
52 | $file = rtrim($file, '/').'/'.md5(mt_rand());
53 | if (($fp = @fopen($file, 'ab')) === FALSE)
54 | {
55 | return FALSE;
56 | }
57 |
58 | fclose($fp);
59 | @chmod($file, 0777);
60 | @unlink($file);
61 | return TRUE;
62 | }
63 | elseif ( ! is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE)
64 | {
65 | return FALSE;
66 | }
67 |
68 | fclose($fp);
69 | return TRUE;
70 | }
71 | }
72 |
73 | class Log {
74 |
75 | /**
76 | * Path to save log files
77 | *
78 | * @var string
79 | */
80 | protected $_log_path;
81 |
82 | protected $_sub_path;
83 |
84 | /**
85 | * File permissions
86 | *
87 | * @var int
88 | */
89 | protected $_file_permissions = 0644;
90 |
91 | /**
92 | * Level of logging
93 | *
94 | * @var int
95 | */
96 | protected $_threshold = 1;
97 |
98 | /**
99 | * Array of threshold levels to log
100 | *
101 | * @var array
102 | */
103 | protected $_threshold_array = array();
104 |
105 | /**
106 | * Format of timestamp for log files
107 | *
108 | * @var string
109 | */
110 | protected $_date_fmt = 'Y-m-d H:i:s.u';
111 |
112 | protected $_file_prefix = "";
113 |
114 | protected $_file_idx = "0";
115 |
116 | protected $_file_size = 104857600;
117 |
118 | /**
119 | * Filename extension
120 | *
121 | * @var string
122 | */
123 | protected $_file_ext;
124 |
125 | /**
126 | * Whether or not the logger can write to the log files
127 | *
128 | * @var bool
129 | */
130 | protected $_enabled = TRUE;
131 |
132 | /**
133 | * Predefined logging levels
134 | *
135 | * @var array
136 | */
137 | protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4);
138 |
139 | // --------------------------------------------------------------------
140 |
141 | /**
142 | * Class constructor
143 | *
144 | * @return void
145 | */
146 | public function __construct($file_prefix = "")
147 | {
148 | ini_set('date.timezone','Asia/Shanghai');
149 | $load_config = new load_config();
150 | $config = $load_config->fc_load_config("system/conf/config.ini");
151 | $this->_log_path = ($config['log_path'] != '') ? $config['log_path'] : 'logs/';
152 | $this->_sub_path = date("Y-m-d");
153 | $this->_file_ext = (isset($config['log_file_extension']) && $config['log_file_extension'] !== '')
154 | ? ltrim($config['log_file_extension'], '.') : 'log';
155 |
156 | file_exists($this->_log_path) OR mkdir($this->_log_path, 0755, TRUE);
157 |
158 | $this->_file_prefix = $file_prefix;
159 |
160 | $this->_file_idx = 0;
161 | while (true)
162 | {
163 | if (file_exists($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx))
164 | {
165 | $cur_size = filesize($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx);
166 | if ($cur_size > $this->_file_size)
167 | $this->_file_idx++;
168 | else
169 | break;
170 | }
171 | else
172 | {
173 | break;
174 | }
175 | }
176 |
177 | if (is_numeric($config['log_threshold']))
178 | {
179 | $this->_threshold = (int) $config['log_threshold'];
180 | }
181 | elseif (is_array($config['log_threshold']))
182 | {
183 | $this->_threshold = 0;
184 | $this->_threshold_array = array_flip($config['log_threshold']);
185 | }
186 |
187 | if (!empty($config['log_file_size']) && is_numeric($config['log_file_size']))
188 | {
189 | $this->_file_size = (int)$config['log_file_size'];
190 | }
191 |
192 |
193 | if ( ! empty($config['log_date_format']))
194 | {
195 | $this->_date_fmt = $config['log_date_format'];
196 | }
197 |
198 | if ( ! empty($config['log_file_permissions']) && is_int($config['log_file_permissions']))
199 | {
200 | $this->_file_permissions = $config['log_file_permissions'];
201 | }
202 | }
203 |
204 | // --------------------------------------------------------------------
205 |
206 | /**
207 | * Write Log File
208 | *
209 | * Generally this function will be called using the global log_message() function
210 | *
211 | * @param string the error level: 'error', 'debug' or 'info'
212 | * @param string the error message
213 | * @return bool
214 | */
215 | public function write_log($level, $msg)
216 | {
217 |
218 | $level = strtoupper($level);
219 |
220 | if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
221 | && ! isset($this->_threshold_array[$this->_levels[$level]]))
222 | {
223 | return FALSE;
224 | }
225 |
226 | if ($this->_sub_path == date("Y-m-d"))
227 | {
228 | if (file_exists($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx))
229 | {
230 | $cur_size = filesize($this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx);
231 | if ($cur_size > $this->_file_size)
232 | $this->_file_idx++;
233 | }
234 | }
235 | else
236 | {
237 | $this->_sub_path = date("Y-m-d");
238 | $this->_file_idx = 0;
239 | }
240 | del_dir_file($this->_log_path.date("Y-m-d",strtotime("-5 day")),true);
241 | file_exists($this->_log_path.$this->_sub_path) OR mkdir($this->_log_path.$this->_sub_path, 0755, TRUE);
242 |
243 | if ( ! is_dir($this->_log_path) OR ! is_really_writable($this->_log_path))
244 | {
245 | $this->_enabled = FALSE;
246 | return false;
247 | }
248 |
249 | $filepath = $this->_log_path.$this->_sub_path.'/'.$this->_file_prefix.".".$this->_file_ext.".".$this->_file_idx;
250 |
251 | $message = '';
252 |
253 | if ( ! $fp = @fopen($filepath, 'ab'))
254 | {
255 | return FALSE;
256 | }
257 |
258 | // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
259 | if (strpos($this->_date_fmt, 'u') !== FALSE)
260 | {
261 | $microtime_full = microtime(TRUE);
262 | $microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
263 | $date = new DateTime(date('Y-m-d H:i:s.'.$microtime_short, $microtime_full));
264 | $date = $date->format($this->_date_fmt);
265 | }
266 | else
267 | {
268 | $date = date($this->_date_fmt);
269 | }
270 |
271 | $bt = debug_backtrace(false);
272 | $filename = '';
273 | $linenumber = '';
274 | if (isset($bt[1])) {
275 | $filename = $bt[1]['file'];
276 | $linenumber = $bt[1]['line'];
277 | }
278 |
279 | $message .= "{$level}|{$date}|{$filename}:{$linenumber}|{$msg}\n";
280 |
281 | flock($fp, LOCK_EX);
282 |
283 | for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
284 | {
285 | if (($result = fwrite($fp, substr($message, $written))) === FALSE)
286 | {
287 | break;
288 | }
289 | }
290 |
291 | flock($fp, LOCK_UN);
292 | fclose($fp);
293 |
294 | if (isset($newfile) && $newfile === TRUE)
295 | {
296 | chmod($filepath, $this->_file_permissions);
297 | }
298 |
299 | return is_int($result);
300 | }
301 | }
302 |
303 | function log_message($level, $message, $name='mina_auth')
304 | {
305 | static $_log;
306 |
307 | if ($_log == NULL)
308 | {
309 | // references cannot be directly assigned to static variables, so we use an array
310 | $_log[0] = new Log($name);
311 | }
312 |
313 | $_log[0]->write_log($level, $message);
314 | }
315 |
316 | function stat_log($level, $message)
317 | {
318 | static $_log_stat;
319 |
320 | if ($_log_stat == NULL)
321 | {
322 | $pid = getmypid();
323 | // references cannot be directly assigned to static variables, so we use an array
324 | $_log_stat[0] = new Log('stat'.$pid);
325 | }
326 |
327 | $_log_stat[0]->write_log($level, $message);
328 | }
329 |
330 |
331 | function del_dir_file($path, $delDir = FALSE) {
332 | if(file_exists($path)){
333 | $handle = opendir($path);
334 | if ($handle) {
335 | while (false !== ( $item = readdir($handle) )) {
336 | if ($item != "." && $item != "..")
337 | is_dir("$path/$item") ? del_dir_file("$path/$item", $delDir) : unlink("$path/$item");
338 | }
339 | closedir($handle);
340 | if ($delDir)
341 | return rmdir($path);
342 | }else {
343 | if (file_exists($path)) {
344 | return unlink($path);
345 | } else {
346 | return FALSE;
347 | }
348 | }
349 | }
350 | }
--------------------------------------------------------------------------------
/system/report_data/report_data.php:
--------------------------------------------------------------------------------
1 | ip = $ip;
28 | $data[0]->dimensions = $obj;
29 | $data[0]->metricName = $metricName;
30 | $data[0]->value = $value;
31 | return $data;
32 | }
33 |
34 |
35 |
36 | public function report_data($region, $secret_id, $secretKey,$ip,$metricName,$value)
37 | {
38 | $data = $this->set_report_data($ip,$metricName,$value);
39 | if ($this->put_monitor_data($region, $secret_id, $secretKey,$data) == false) {
40 | log_message("ERROR", "report_data_err");
41 | }
42 | }
43 |
44 | /**
45 | * @param $region
46 | * @param $secret_id
47 | * @param $signature
48 | * @return bool
49 | * 描述:创建命名空间
50 | */
51 | public function create_namespace($region, $secret_id, $secretKey)
52 | {
53 | $time = time();
54 | $nonce = mt_rand(10000, 99999);
55 | $arr = Array(
56 | "Action" => "CreateNamespace",
57 | "Region" => $region,
58 | "Timestamp" => $time,
59 | "Nonce" => $nonce,
60 | "SecretId" => $secret_id,
61 | "namespace" => "minaauth"
62 | );
63 | $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey);
64 | $signature = urlencode($signature);
65 | $url = "https://monitor.api.qcloud.com/v2/index.php?Action=CreateNamespace&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature&namespace=minaauth";
66 | $http_util = new http_util();
67 | $ret_msg = $http_util->http_get($url);
68 | if ($ret_msg && $this->is_json($ret_msg)) {
69 | $json_ret_msg = json_decode($ret_msg, true);
70 | if ($json_ret_msg['code'] == 0)
71 | return true;
72 | }
73 | return false;
74 | }
75 |
76 |
77 | /**
78 | * @param $region
79 | * @param $secret_id
80 | * @param $signature
81 | * @param $metric_name
82 | * @param $metric_cname
83 | * @return bool
84 | * 描述:创建指标
85 | */
86 | public function create_metric($region, $secret_id, $secretKey, $metric_name, $metric_cname)
87 | {
88 | $time = time();
89 | $nonce = mt_rand(10000, 99999);
90 | $arr = Array(
91 | "Action" => "CreateMetric",
92 | "Region" => $region,
93 | "Timestamp" => $time,
94 | "Nonce" => $nonce,
95 | "SecretId" => $secret_id,
96 | "namespace" => "minaauth",
97 | "metricName" => $metric_name,
98 | "metricCname" => $metric_cname,
99 | "dimensionNames.0" => "ip",
100 | "statisticsType.0.period" => 300,
101 | "statisticsType.0.statistics" => "max"
102 | );
103 | $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey);
104 | $signature = urlencode($signature);
105 | $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";
106 | $http_util = new http_util();
107 | $ret_msg = $http_util->http_get($url);
108 | if ($ret_msg && $this->is_json($ret_msg)) {
109 | $json_ret_msg = json_decode($ret_msg, true);
110 | if ($json_ret_msg['code'] == 0)
111 | return true;
112 | }
113 | return false;
114 | }
115 |
116 | /**
117 | * @param $region
118 | * @param $secret_id
119 | * @param $signature
120 | * @param $data
121 | * @return bool
122 | * 描述:创建指标上报数据
123 | */
124 | public function put_monitor_data($region, $secret_id, $secretKey, $data)
125 | {
126 | $time = time();
127 | $nonce = mt_rand(10000, 99999);
128 | $arr = Array(
129 | "Action" => "PutMonitorData",
130 | "Region" => $region,
131 | "Timestamp" => $time,
132 | "Nonce" => $nonce,
133 | "SecretId" => $secret_id
134 | );
135 | $signature = $this->post_signature($arr, 'receiver.monitor.tencentyun.com/v2/index.php?', $secretKey);
136 |
137 | $params = array(
138 | "Action" => "PutMonitorData",
139 | "Region" => $region,
140 | "Timestamp" => $time,
141 | "Nonce" => $nonce,
142 | "SecretId" => $secret_id,
143 | "Signature"=>$signature,
144 | "Namespace"=>"minaauth",
145 | "Data"=>$data
146 | );
147 | $params_json = json_encode($params);
148 | $http_util = new http_util();
149 | $ret_msg = $http_util->http_post('http://receiver.monitor.tencentyun.com:8080/v2/index.php',$params_json);
150 | if ($ret_msg && $this->is_json($ret_msg)) {
151 | $json_ret_msg = json_decode($ret_msg, true);
152 | if ($json_ret_msg['code'] == 0)
153 | return true;
154 | }
155 | return false;
156 |
157 | }
158 |
159 | /**
160 | * @return bool
161 | * 描述:获取用户组ID
162 | */
163 | public function describe_user_group($region, $secret_id, $secretKey)
164 | {
165 | $time = time();
166 | $nonce = mt_rand(10000, 99999);
167 | $arr = Array(
168 | "Action" => "DescribeUserGroup",
169 | "Region" => $region,
170 | "Timestamp" => $time,
171 | "Nonce" => $nonce,
172 | "SecretId" => $secret_id,
173 | );
174 | $signature = $this->get_signature($arr, 'account.api.qcloud.com/v2/index.php?', $secretKey);
175 |
176 | $url = "https://account.api.qcloud.com/v2/index.php?Action=DescribeUserGroup&Region=$region&Timestamp=$time&Nonce=$nonce&SecretId=$secret_id&Signature=$signature";
177 | $http_util = new http_util();
178 | $ret_msg = $http_util->http_get($url);
179 | if ($ret_msg && $this->is_json($ret_msg)) {
180 | $json_ret_msg = json_decode($ret_msg, true);
181 | if (isset($json_ret_msg['data']['groupSet'][0]['groupId']))
182 | return $json_ret_msg['data']['groupSet'][0]['groupId'];
183 | }
184 | return false;
185 | }
186 |
187 | /**
188 | * @param $region
189 | * @param $secret_id
190 | * @param $signature
191 | * @param $metric_name
192 | * @param $metric_cname
193 | * @return bool
194 | * 描述:创建告警规则
195 | */
196 | public function create_alarm_rule($region, $secret_id, $secretKey, $metric_name)
197 | {
198 | $time = time();
199 | $nonce = mt_rand(10000, 99999);
200 | $receivers_id = $this->describe_user_group($region, $secret_id, $secretKey);
201 | $arr = Array(
202 | "Action" => "CreateAlarmRule",
203 | "Region" => $region,
204 | "Timestamp" => $time,
205 | "Nonce" => $nonce,
206 | "SecretId" => $secret_id,
207 | "namespace"=>"minaauth",
208 | "metricName"=>$metric_name,
209 | "dimensionNames.0"=>"ip",
210 | "operatorType"=>"<",
211 | "threshold"=>95,
212 | "period"=>300,
213 | "statistics"=>"max",
214 | "constancy"=>2,
215 | "receiversId"=>$receivers_id
216 | );
217 | $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey);
218 | if ($receivers_id) {
219 | $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";
220 | $http_util = new http_util();
221 | $ret_msg = $http_util->http_get($url);
222 | if ($ret_msg && $this->is_json($ret_msg)) {
223 | $json_ret_msg = json_decode($ret_msg, true);
224 | if (isset($json_ret_msg['data']['alarmRuleId']))
225 | return $json_ret_msg['data']['alarmRuleId'];
226 | }
227 | }
228 |
229 | return false;
230 | }
231 |
232 | /**
233 | * @param $region
234 | * @param $secret_id
235 | * @param $signature
236 | * @param $metric_name
237 | * @param $ip
238 | * @param $metric_name_value
239 | * @return bool
240 | * 描述:绑定告警规则和对象
241 | */
242 | public function bind_alarm_rule_objects($region, $secret_id, $secretKey, $metric_name, $ip)
243 | {
244 | $time = time();
245 | $nonce = mt_rand(10000, 99999);
246 | $alarmRule_id = $this->create_alarm_rule($region, $secret_id, $secretKey, $metric_name);
247 | $arr = Array(
248 | "Action" => "BindAlarmRuleObjects",
249 | "Region" => $region,
250 | "Timestamp" => $time,
251 | "Nonce" => $nonce,
252 | "SecretId" => $secret_id,
253 | "alarmRuleId" => $alarmRule_id,
254 | "dimensions.0.name"=>"ip",
255 | "dimensions.0.value"=>$ip
256 | );
257 | $signature = $this->get_signature($arr, 'monitor.api.qcloud.com/v2/index.php?', $secretKey);
258 |
259 | if ($alarmRule_id) {
260 | $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";
261 | $http_util = new http_util();
262 | $ret_msg = $http_util->http_get($url);
263 | if ($ret_msg && $this->is_json($ret_msg)) {
264 | $json_ret_msg = json_decode($ret_msg, true);
265 | if ($json_ret_msg['code'] == 0)
266 | return true;
267 | }
268 | }
269 | return false;
270 | }
271 |
272 | public function is_json($str)
273 | {
274 | json_decode($str);
275 | return (json_last_error() == JSON_ERROR_NONE);
276 | }
277 |
278 | /**
279 | * @param $arr
280 | * @param $get_url
281 | * @param $secretKey
282 | * @return bool|string
283 | * 描述:生成签名
284 | */
285 | public function get_signature($arr, $get_url, $secretKey)
286 | {
287 | $sort_arr = ksort($arr);
288 | if ($sort_arr) {
289 | $sort_json = json_encode($arr);
290 | $sort_json = $this->wipe_illegal_char($sort_json);
291 | $str_sig = 'GET' . $get_url . $sort_json;
292 | $sign_str = base64_encode(hash_hmac('sha1', $str_sig, $secretKey, true));
293 | return $sign_str;
294 | }
295 | return false;
296 | }
297 |
298 | public function post_signature($arr, $get_url, $secretKey)
299 | {
300 | $sort_arr = ksort($arr);
301 | if ($sort_arr) {
302 | $sort_json = json_encode($arr);
303 | $sort_json = $this->wipe_illegal_char($sort_json);
304 | $str_sig = 'POST' . $get_url . $sort_json;
305 | $sign_str = base64_encode(hash_hmac('sha1', $str_sig, $secretKey, true));
306 | return $sign_str;
307 | }
308 | return false;
309 | }
310 |
311 | private function wipe_illegal_char($str)
312 | {
313 | $tmp_begin = -1;
314 | $tmp_end = -1;
315 | $str_tmp = "";
316 | for ($i = 0; $i < strlen($str); $i++) {
317 | if ($str[$i] == "[") {
318 | if ($tmp_begin == -1)
319 | $tmp_begin = $i;
320 | }
321 | if ($str[$i] == "]") {
322 | if ($tmp_end == -1)
323 | $tmp_end = $i;
324 | }
325 | }
326 | for ($j = 0; $j < strlen($str); $j++) {
327 | $str_tmp[$j] = $str[$j];
328 | if ($tmp_begin != -1 && $tmp_end != -1) {
329 | if ($j < $tmp_begin || $j > $tmp_end) {
330 | if ($str_tmp[$j] == ",")
331 | $str_tmp[$j] = "&";
332 | if ($str_tmp[$j] == "_")
333 | $str_tmp[$j] = ".";
334 | if ($str_tmp[$j] == "\"")
335 | $str_tmp[$j] = "";
336 | if ($str_tmp[$j] == "{")
337 | $str_tmp[$j] = "";
338 | if ($str_tmp[$j] == "}")
339 | $str_tmp[$j] = "";
340 | if ($str_tmp[$j] == ":")
341 | $str_tmp[$j] = "=";
342 | }
343 | } else {
344 | if ($str_tmp[$j] == ",")
345 | $str_tmp[$j] = "&";
346 | if ($str_tmp[$j] == "_")
347 | $str_tmp[$j] = ".";
348 | if ($str_tmp[$j] == "\"")
349 | $str_tmp[$j] = "";
350 | if ($str_tmp[$j] == "{")
351 | $str_tmp[$j] = "";
352 | if ($str_tmp[$j] == "}")
353 | $str_tmp[$j] = "";
354 | if ($str_tmp[$j] == ":")
355 | $str_tmp[$j] = "=";
356 | }
357 | }
358 | return implode($str_tmp);
359 | }
360 | }
--------------------------------------------------------------------------------
/application/controllers/qcloud/minaauth/Auth.php:
--------------------------------------------------------------------------------
1 | select_cappinfo();
35 | if (empty($cappinfo_data) || ($cappinfo_data == false)) {
36 | $ret['returnCode'] = return_code::MA_NO_APPID;
37 | $ret['returnMessage'] = 'NO_APPID';
38 | $ret['returnData'] = '';
39 | } else {
40 | $appid = $cappinfo_data['appid'];
41 | $secret = $cappinfo_data['secret'];
42 | $ip = $cappinfo_data['ip'];
43 | $qcloud_appid = $cappinfo_data['qcloud_appid'];
44 | $login_duration = $cappinfo_data['login_duration'];
45 | $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
46 | $http_util = new http_util();
47 | $return_message = $http_util->http_get($url);
48 | if ($return_message!=false) {
49 | $json_message = json_decode($return_message, true);
50 | if (isset($json_message['openid']) && isset($json_message['session_key']) && isset($json_message['expires_in'])) {
51 | $uuid = md5((time()-mt_rand(1, 10000)) . mt_rand(1, 1000000));//生成UUID
52 | $skey = md5(time() . mt_rand(1, 1000000));//生成skey
53 | $create_time = date('Y-m-d H:i:s',time());
54 | $last_visit_time = date('Y-m-d H:i:s',time());
55 | $openid = $json_message['openid'];
56 | $session_key = $json_message['session_key'];
57 | $errCode = 0;
58 | $user_info = false;
59 | //兼容旧的解密算法
60 | if($iv == "old"){
61 | $decrypt_data = new decrypt_data();
62 | $user_info = $decrypt_data->aes128cbc_Decrypt($encrypt_data, $session_key);
63 | log_message("INFO","userinfo:".$user_info);
64 | $user_info = base64_encode($user_info);
65 | }else{
66 | $pc = new WXBizDataCrypt($appid, $session_key);
67 | $errCode = $pc->decryptData($encrypt_data, $iv, $user_info);
68 | $user_info = base64_encode($user_info);
69 | }
70 | if ($user_info === false || $errCode !== 0) {
71 | $ret['returnCode'] = return_code::MA_DECRYPT_ERR;
72 | $ret['returnMessage'] = 'DECRYPT_FAIL';
73 | $ret['returnData'] = '';
74 | } else {
75 | $params = array(
76 | "uuid" => $uuid,
77 | "skey" => $skey,
78 | "create_time" => $create_time,
79 | "last_visit_time" => $last_visit_time,
80 | "openid" => $openid,
81 | "session_key" => $session_key,
82 | "user_info" => $user_info,
83 | "login_duration" => $login_duration
84 | );
85 |
86 | $csessioninfo_service = new Csessioninfo_Service();
87 | $change_result = $csessioninfo_service->change_csessioninfo($params);
88 | if ($change_result === true) {
89 | $id = $csessioninfo_service->get_id_csessioninfo($openid);
90 | $arr_result['id'] = $id;
91 | $arr_result['skey'] = $skey;
92 | $arr_result['user_info'] = json_decode(base64_decode($user_info));
93 | $arr_result['duration'] = $json_message['expires_in'];
94 | $ret['returnCode'] = return_code::MA_OK;
95 | $ret['returnMessage'] = 'NEW_SESSION_SUCCESS';
96 | $ret['returnData'] = $arr_result;
97 | } else if ($change_result === false) {
98 | $ret['returnCode'] = return_code::MA_CHANGE_SESSION_ERR;
99 | $ret['returnMessage'] = 'CHANGE_SESSION_ERR';
100 | $ret['returnData'] = '';
101 | } else {
102 | $arr_result['id'] = $change_result;
103 | $arr_result['skey'] = $skey;
104 | $arr_result['user_info'] = json_decode(base64_decode($user_info));
105 | $arr_result['duration'] = $json_message['expires_in'];
106 | $ret['returnCode'] = return_code::MA_OK;
107 | $ret['returnMessage'] = 'UPDATE_SESSION_SUCCESS';
108 | $ret['returnData'] = $arr_result;
109 | }
110 | }
111 | } else if (isset($json_message['errcode']) && isset($json_message['errmsg'])) {
112 | $ret['returnCode'] = return_code::MA_WEIXIN_CODE_ERR;
113 | $ret['returnMessage'] = 'WEIXIN_CODE_ERR';
114 | $ret['returnData'] = '';
115 | } else {
116 | $ret['returnCode'] = return_code::MA_WEIXIN_RETURN_ERR;
117 | $ret['returnMessage'] = 'WEIXIN_RETURN_ERR';
118 | $ret['returnData'] = '';
119 | }
120 | } else {
121 | $ret['returnCode'] = return_code::MA_WEIXIN_NET_ERR;
122 | $ret['returnMessage'] = 'WEIXIN_NET_ERR';
123 | $ret['returnData'] = '';
124 | }
125 |
126 | /**
127 | * 上报数据部分
128 | */
129 | $report_data = new ready_for_report_data();
130 |
131 | $arr_report_data = array(
132 | "ip"=>$ip,
133 | "appid"=>$qcloud_appid,
134 | "login_count"=>0,
135 | "login_sucess"=>0,
136 | "auth_count"=>0,
137 | "auth_sucess"=>0
138 | );
139 |
140 | if($report_data->check_data()){
141 | $report_data->ready_data("login_count");
142 | }else{
143 | $arr_report_data['login_count']=1;
144 | $report_data->write_report_data(json_encode($arr_report_data));
145 | }
146 | if($ret['returnCode']==0){
147 | if($report_data->check_data()){
148 | $report_data->ready_data("login_sucess");
149 | }else{
150 | $arr_report_data['login_count']=1;
151 | $arr_report_data['login_sucess']=1;
152 | $report_data->write_report_data(json_encode($arr_report_data));
153 | }
154 | }
155 | }
156 | return $ret;
157 | }
158 |
159 | /**
160 | * @param $id
161 | * @param $skey
162 | * @return bool
163 | * 描述:登录态验证
164 | */
165 | public function auth($id, $skey)
166 | {
167 | //根据Id和skey 在cSessionInfo中进行鉴权,返回鉴权失败和密钥过期
168 | $cappinfo_service = new Cappinfo_Service();
169 | $cappinfo_data = $cappinfo_service->select_cappinfo();
170 | if (empty($cappinfo_data) || ($cappinfo_data == false)) {
171 | $ret['returnCode'] = return_code::MA_NO_APPID;
172 | $ret['returnMessage'] = 'NO_APPID';
173 | $ret['returnData'] = '';
174 | } else {
175 | $login_duration = $cappinfo_data['login_duration'];
176 | $session_duration = $cappinfo_data['session_duration'];
177 | $ip = $cappinfo_data['ip'];
178 | $qcloud_appid = $cappinfo_data['qcloud_appid'];
179 |
180 | $params = array(
181 | "uuid" => $id,
182 | "skey" => $skey,
183 | "login_duration" => $login_duration,
184 | "session_duration" => $session_duration
185 | );
186 |
187 | $csessioninfo_service = new Csessioninfo_Service();
188 | $auth_result = $csessioninfo_service->check_session_for_auth($params);
189 | if ($auth_result!==false) {
190 | $arr_result['user_info'] = json_decode(base64_decode($auth_result));
191 | $ret['returnCode'] = return_code::MA_OK;
192 | $ret['returnMessage'] = 'AUTH_SUCCESS';
193 | $ret['returnData'] = $arr_result;
194 | } else {
195 | $ret['returnCode'] = return_code::MA_AUTH_ERR;
196 | $ret['returnMessage'] = 'AUTH_FAIL';
197 | $ret['returnData'] = '';
198 | }
199 |
200 | /**
201 | * 上报数据部分
202 | */
203 | $report_data = new ready_for_report_data();
204 |
205 | $arr_report_data = array(
206 | "ip"=>$ip,
207 | "appid"=>$qcloud_appid,
208 | "login_count"=>0,
209 | "login_sucess"=>0,
210 | "auth_count"=>0,
211 | "auth_sucess"=>0
212 | );
213 |
214 | if($report_data->check_data()){
215 | $report_data->ready_data("auth_count");
216 | }else{
217 | $arr_report_data['auth_count']=1;
218 | $report_data->write_report_data(json_encode($arr_report_data));
219 | }
220 | if($ret['returnCode']==0){
221 | if($report_data->check_data()){
222 | $report_data->ready_data("auth_sucess");
223 | }else{
224 | $arr_report_data['auth_count']=1;
225 | $arr_report_data['auth_sucess']=1;
226 | $report_data->write_report_data(json_encode($arr_report_data));
227 | }
228 | }
229 |
230 | }
231 | return $ret;
232 | }
233 |
234 | /**
235 | * @param $id
236 | * @param $skey
237 | * @param $encrypt_data
238 | * @return bool|string
239 | * 描述:解密数据
240 | */
241 | public function decrypt($id, $skey, $encrypt_data)
242 | {
243 | //1、根据id和skey获取session_key。
244 | //2、session_key获取成功则正常解密,可能解密失败。
245 | //3、获取不成功则解密失败。
246 | $csessioninfo_service = new Csessioninfo_Service();
247 | $params = array(
248 | "id" => $id,
249 | "skey" => $skey
250 | );
251 | $result = $csessioninfo_service->select_csessioninfo($params);
252 | if ($result !== false && count($result) != 0 && isset($result['session_key'])) {
253 | $session_key = $result['session_key'];
254 | $decrypt_data = new decrypt_data();
255 | $data = $decrypt_data->aes128cbc_Decrypt($encrypt_data, $session_key);
256 | if ($data !== false) {
257 | $ret['returnCode'] = return_code::MA_OK;
258 | $ret['returnMessage'] = 'DECRYPT_SUCCESS';
259 | $ret['returnData'] = $data;
260 | } else {
261 | $ret['returnCode'] = return_code::MA_DECRYPT_ERR;
262 | $ret['returnMessage'] = 'GET_SESSION_KEY_SUCCESS_BUT_DECRYPT_FAIL';
263 | $ret['returnData'] = '';
264 | }
265 | } else {
266 | $ret['returnCode'] = return_code::MA_DECRYPT_ERR;
267 | $ret['returnMessage'] = 'GET_SESSION_KEY_FAIL';
268 | $ret['returnData'] = '';
269 | }
270 | return $ret;
271 | }
272 |
273 | public function init_data($appid,$secret,$qcloud_appid,$ip,$cdb_ip,$cdb_port,$cdb_user_name,$cdb_pass_wd){
274 | $init_db = new init_db();
275 | $params_db = array(
276 | "cdb_ip"=>$cdb_ip,
277 | "cdb_port"=>$cdb_port,
278 | "cdb_user_name" => $cdb_user_name,
279 | "cdb_pass_wd" => $cdb_pass_wd
280 | );
281 | if($init_db->init_db_config($params_db)){
282 | if($init_db->init_db_table()){
283 | $cappinfo_service = new Cappinfo_Service();
284 | $cappinfo_data = $cappinfo_service->select_cappinfo();
285 | $params = array(
286 | "appid"=>$appid,
287 | "secret"=>$secret,
288 | "qcloud_appid"=>$qcloud_appid,
289 | "ip"=>$ip
290 | );
291 |
292 | if(empty($cappinfo_data)){
293 | if($cappinfo_service->insert_cappinfo($params))
294 | {
295 | $ret['returnCode'] = return_code::MA_OK;
296 | $ret['returnMessage'] = 'INIT_APPINFO_SUCCESS';
297 | $ret['returnData'] = '';
298 | }else{
299 | $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR;
300 | $ret['returnMessage'] = 'INIT_APPINFO_FAIL';
301 | $ret['returnData'] = '';
302 | }
303 | }else if($cappinfo_data != false){
304 | $cappinfo_service->delete_cappinfo();
305 | if($cappinfo_service->insert_cappinfo($params))
306 | {
307 | $ret['returnCode'] = return_code::MA_OK;
308 | $ret['returnMessage'] = 'INIT_APPINFO_SUCCESS';
309 | $ret['returnData'] = '';
310 | }else{
311 | $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR;
312 | $ret['returnMessage'] = 'INIT_APPINFO_FAIL';
313 | $ret['returnData'] = '';
314 | }
315 | }else{
316 | $ret['returnCode'] = return_code::MA_MYSQL_ERR;
317 | $ret['returnMessage'] = 'MYSQL_ERR';
318 | $ret['returnData'] = '';
319 | }
320 | }
321 | else{
322 | $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR;
323 | $ret['returnMessage'] = 'INIT_APPINFO_FAIL';
324 | $ret['returnData'] = '';
325 | }
326 |
327 | }else{
328 | $ret['returnCode'] = return_code::MA_INIT_APPINFO_ERR;
329 | $ret['returnMessage'] = 'INIT_APPINFO_FAIL';
330 | $ret['returnData'] = '';
331 | }
332 | return $ret;
333 | }
334 |
335 | }
--------------------------------------------------------------------------------