added access control to wechat message in api and admin

pull/90/head
13621160019@163.com 2021-12-05 12:37:42 +08:00
parent 65565a5351
commit 996f7066e1
8 changed files with 192 additions and 197 deletions

View File

@ -1,7 +1,14 @@
'use strict'; 'use strict';
app.controller('WechatMessageController', function($scope, $timeout,$translate, WechatMessageAnalysisService, toaster, SweetAlert) { app.controller('WechatMessageController', function(
$scope,
$window,
$timeout,
$translate,
WechatMessageAnalysisService,
toaster,
SweetAlert) {
$scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
$scope.$on('handleBroadcastWechatMessageOptionChanged', function (event, data) { $scope.$on('handleBroadcastWechatMessageOptionChanged', function (event, data) {
if (angular.isDefined(data.load)) { if (angular.isDefined(data.load)) {
$scope.tabledata = []; $scope.tabledata = [];
@ -31,7 +38,8 @@ app.controller('WechatMessageController', function($scope, $timeout,$translate,
}, },
function(isConfirm) { function(isConfirm) {
if (isConfirm) { if (isConfirm) {
WechatMessageAnalysisService.deleteWechatMessage(wechatmessage, function (response) { let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
WechatMessageAnalysisService.deleteWechatMessage(wechatmessage, headers, function (response) {
if (angular.isDefined(response.status) && response.status === 204) { if (angular.isDefined(response.status) && response.status === 204) {
toaster.pop({ toaster.pop({
type: "success", type: "success",
@ -51,6 +59,7 @@ app.controller('WechatMessageController', function($scope, $timeout,$translate,
} }
}); });
} }
}); }
);
}; };
}); });

View File

@ -1,7 +1,11 @@
'use strict'; 'use strict';
app.controller('WechatMessageOptionController', function($scope, $timeout, app.controller('WechatMessageOptionController', function(
$scope,
$window,
$timeout,
WechatMessageAnalysisService) { WechatMessageAnalysisService) {
$scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
$scope.daterange = { $scope.daterange = {
startDate: moment().subtract(7,'days'), startDate: moment().subtract(7,'days'),
endDate: moment() endDate: moment()
@ -36,7 +40,8 @@ app.controller('WechatMessageOptionController', function($scope, $timeout,
load: true, load: true,
period:$scope.currentPeriod period:$scope.currentPeriod
}); });
WechatMessageAnalysisService.getAnalysisResult(query, function (response) { let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
WechatMessageAnalysisService.getAnalysisResult(query, headers, function (response) {
if (angular.isDefined(response.status) && response.status === 200) { if (angular.isDefined(response.status) && response.status === 200) {
$scope.$emit('handleEmitWechatMessageOptionChanged', response.data); $scope.$emit('handleEmitWechatMessageOptionChanged', response.data);
} }

View File

@ -1,11 +1,8 @@
'use strict'; 'use strict';
app.factory('WechatMessageAnalysisService', function($http) { app.factory('WechatMessageAnalysisService', function($http) {
return { return {
getAnalysisResult: function(query, headers, callback) {
getAnalysisResult: function(query,callback) { $http.get(getAPI()+"wechatmessages"+"/from/"+query.datestart+"/to/"+query.dateend, {headers})
var base="wechatmessages";
var url=base+"/from/"+query.datestart+"/to/"+query.dateend;
$http.get(getAPI()+url)
.then(function (response) { .then(function (response) {
callback(response); callback(response);
}, function (response) { }, function (response) {
@ -13,8 +10,8 @@ app.factory('WechatMessageAnalysisService', function($http) {
}); });
}, },
deleteWechatMessage: function(wechatmessage, callback) { deleteWechatMessage: function(wechatmessage, headers, callback) {
$http.delete(getAPI()+'wechatmessages/'+wechatmessage.id) $http.delete(getAPI()+'wechatmessages/'+wechatmessage.id, {headers})
.then(function (response) { .then(function (response) {
callback(response); callback(response);
}, function (response) { }, function (response) {

View File

@ -7389,7 +7389,7 @@
}, },
{ {
"key": "Token", "key": "Token",
"value": "c6f5fa938c0e228d06e1f3adb3ef1eac319e1167e6ff0cb7fd5d928e83da5764ddb66e29204e0f4e6aa407ded3702b15be67a435c4825dc722b6047010398714", "value": "14f2bb7378e6926c20b54bd48bd8618e4d78ece1f1658c946a7257eaa97d3149ecd6407a62a39f0f3a6ef6b65f19d63894f297ad5a58d7b597a547f8b8e2898c",
"type": "text", "type": "text",
"description": "Login to get a valid token" "description": "Login to get a valid token"
} }
@ -8178,21 +8178,34 @@
"name": "Wechat Message", "name": "Wechat Message",
"item": [ "item": [
{ {
"name": "GET Wechat Messages from Startdate to Enddate", "name": "GET Wechat Messages by Date Range",
"request": { "request": {
"method": "GET", "method": "GET",
"header": [], "header": [
{
"key": "User-UUID",
"value": "dcdb67d1-6116-4987-916f-6fc6cf2bc0e4",
"type": "text",
"description": "Any admin users' UUID"
},
{
"key": "Token",
"value": "14f2bb7378e6926c20b54bd48bd8618e4d78ece1f1658c946a7257eaa97d3149ecd6407a62a39f0f3a6ef6b65f19d63894f297ad5a58d7b597a547f8b8e2898c",
"type": "text",
"description": "Login to get a valid token"
}
],
"url": { "url": {
"raw": "{{base_url}}/wechatmessages/from/2020-04-01/to/2020-05-01", "raw": "{{base_url}}/wechatmessages/from/2021-12-01/to/2021-12-31",
"host": [ "host": [
"{{base_url}}" "{{base_url}}"
], ],
"path": [ "path": [
"wechatmessages", "wechatmessages",
"from", "from",
"2020-04-01", "2021-12-01",
"to", "to",
"2020-05-01" "2021-12-31"
], ],
"query": [ "query": [
{ {
@ -8209,7 +8222,20 @@
"name": "GET a Wechat Message by ID", "name": "GET a Wechat Message by ID",
"request": { "request": {
"method": "GET", "method": "GET",
"header": [], "header": [
{
"key": "User-UUID",
"value": "dcdb67d1-6116-4987-916f-6fc6cf2bc0e4",
"type": "text",
"description": "Any admin users' UUID"
},
{
"key": "Token",
"value": "14f2bb7378e6926c20b54bd48bd8618e4d78ece1f1658c946a7257eaa97d3149ecd6407a62a39f0f3a6ef6b65f19d63894f297ad5a58d7b597a547f8b8e2898c",
"type": "text",
"description": "Login to get a valid token"
}
],
"url": { "url": {
"raw": "{{base_url}}/wechatmessages/1", "raw": "{{base_url}}/wechatmessages/1",
"host": [ "host": [
@ -8227,7 +8253,20 @@
"name": "POST Create New Wechat Message TODO", "name": "POST Create New Wechat Message TODO",
"request": { "request": {
"method": "POST", "method": "POST",
"header": [], "header": [
{
"key": "User-UUID",
"value": "dcdb67d1-6116-4987-916f-6fc6cf2bc0e4",
"type": "text",
"description": "Any admin users' UUID"
},
{
"key": "Token",
"value": "c6f5fa938c0e228d06e1f3adb3ef1eac319e1167e6ff0cb7fd5d928e83da5764ddb66e29204e0f4e6aa407ded3702b15be67a435c4825dc722b6047010398714",
"type": "text",
"description": "Login to get a valid token"
}
],
"url": { "url": {
"raw": "{{base_url}}/wechatmessages", "raw": "{{base_url}}/wechatmessages",
"host": [ "host": [
@ -8244,7 +8283,20 @@
"name": "PUT Update a Wechat Message TODO", "name": "PUT Update a Wechat Message TODO",
"request": { "request": {
"method": "PUT", "method": "PUT",
"header": [], "header": [
{
"key": "User-UUID",
"value": "dcdb67d1-6116-4987-916f-6fc6cf2bc0e4",
"type": "text",
"description": "Any admin users' UUID"
},
{
"key": "Token",
"value": "c6f5fa938c0e228d06e1f3adb3ef1eac319e1167e6ff0cb7fd5d928e83da5764ddb66e29204e0f4e6aa407ded3702b15be67a435c4825dc722b6047010398714",
"type": "text",
"description": "Login to get a valid token"
}
],
"url": { "url": {
"raw": "{{base_url}}/wechatmessages/1", "raw": "{{base_url}}/wechatmessages/1",
"host": [ "host": [
@ -8262,7 +8314,20 @@
"name": "DELETE a Wechat Message by ID", "name": "DELETE a Wechat Message by ID",
"request": { "request": {
"method": "DELETE", "method": "DELETE",
"header": [], "header": [
{
"key": "User-UUID",
"value": "dcdb67d1-6116-4987-916f-6fc6cf2bc0e4",
"type": "text",
"description": "Any admin users' UUID"
},
{
"key": "Token",
"value": "14f2bb7378e6926c20b54bd48bd8618e4d78ece1f1658c946a7257eaa97d3149ecd6407a62a39f0f3a6ef6b65f19d63894f297ad5a58d7b597a547f8b8e2898c",
"type": "text",
"description": "Login to get a valid token"
}
],
"url": { "url": {
"raw": "{{base_url}}/wechatmessages/2", "raw": "{{base_url}}/wechatmessages/2",
"host": [ "host": [

View File

@ -2114,11 +2114,11 @@ Result in JSON
| acknowledge_code| string | Recipient reply with Acknowledge code to acknowledge | | acknowledge_code| string | Recipient reply with Acknowledge code to acknowledge |
| status | string | Status ('new', 'sent', 'acknowledged', 'timeout'| | status | string | Status ('new', 'sent', 'acknowledged', 'timeout'|
```bash ```bash
curl -i -X GET {{base_url}}/wechatmessages/{id} curl -i -H "User-UUID: 793f1bb4-6e25-4242-8cdc-2f662b25484f" -H "Token: GET-TOKEN-AFTER-LOGIN" -X GET {{base_url}}/wechatmessages/{id}
``` ```
* GET Wechat Messages from Startdate to Enddate * GET Wechat Messages from Startdate to Enddate
```bash ```bash
curl -i -X GET {{base_url}}/wechatmessages/from/{startdate}/to/{enddate} curl -i -H "User-UUID: 793f1bb4-6e25-4242-8cdc-2f662b25484f" -H "Token: GET-TOKEN-AFTER-LOGIN" -X GET {{base_url}}/wechatmessages/from/{startdate}/to/{enddate}
``` ```
* DELETE Wechat Message by ID * DELETE Wechat Message by ID
```bash ```bash

View File

@ -1,5 +1,5 @@
import falcon import falcon
import json import simplejson as json
import mysql.connector import mysql.connector
import config import config
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
@ -48,28 +48,22 @@ class EmailMessageCollection:
title='API.BAD_REQUEST', title='API.BAD_REQUEST',
description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME') description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
try: cnx = mysql.connector.connect(**config.myems_fdd_db)
cnx = mysql.connector.connect(**config.myems_fdd_db) cursor = cnx.cursor()
cursor = cnx.cursor()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
try: query = (" SELECT id, recipient_name, recipient_email, "
query = (" SELECT id, recipient_name, recipient_email, " " subject, message, attachment_file_name, "
" subject, message, attachment_file_name, " " created_datetime_utc, scheduled_datetime_utc, status "
" created_datetime_utc, scheduled_datetime_utc, status " " FROM tbl_email_messages "
" FROM tbl_email_messages " " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
" WHERE created_datetime_utc >= %s AND created_datetime_utc < %s " " ORDER BY created_datetime_utc ")
" ORDER BY created_datetime_utc ") cursor.execute(query, (start_datetime_utc, end_datetime_utc))
cursor.execute(query, (start_datetime_utc, end_datetime_utc)) rows = cursor.fetchall()
rows = cursor.fetchall()
if cursor: if cursor:
cursor.close() cursor.close()
if cnx: if cnx:
cnx.disconnect() cnx.disconnect()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
result = list() result = list()
if rows is not None and len(rows) > 0: if rows is not None and len(rows) > 0:
@ -106,31 +100,21 @@ class EmailMessageItem:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_EMAIL_MESSAGE_ID') description='API.INVALID_EMAIL_MESSAGE_ID')
try: cnx = mysql.connector.connect(**config.myems_fdd_db)
cnx = mysql.connector.connect(**config.myems_fdd_db) cursor = cnx.cursor()
cursor = cnx.cursor()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
try: query = (" SELECT id, recipient_name, recipient_email, "
query = (" SELECT id, recipient_name, recipient_email, " " subject, message, attachment_file_name, "
" subject, message, attachment_file_name, " " created_datetime_utc, scheduled_datetime_utc, status "
" created_datetime_utc, scheduled_datetime_utc, status " " FROM tbl_email_messages "
" FROM tbl_email_messages " " WHERE id = %s ")
" WHERE id = %s ") cursor.execute(query, (id_,))
cursor.execute(query, (id_,)) row = cursor.fetchone()
row = cursor.fetchone()
if cursor: if cursor:
cursor.close() cursor.close()
if cnx: if cnx:
cnx.disconnect() cnx.disconnect()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
if row is None: if row is None:
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
@ -156,29 +140,13 @@ class EmailMessageItem:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_EMAIL_MESSAGE_ID') description='API.INVALID_EMAIL_MESSAGE_ID')
cnx = None cnx = mysql.connector.connect(**config.myems_fdd_db)
cursor = None cursor = cnx.cursor()
try:
cnx = mysql.connector.connect(**config.myems_fdd_db)
cursor = cnx.cursor()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
try: cursor.execute(" SELECT id "
cursor.execute(" SELECT id " " FROM tbl_email_messages "
" FROM tbl_email_messages " " WHERE id = %s ", (id_,))
" WHERE id = %s ", (id_,)) row = cursor.fetchone()
row = cursor.fetchone()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
if row is None: if row is None:
if cursor: if cursor:
@ -188,19 +156,13 @@ class EmailMessageItem:
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.EMAIL_MESSAGE_NOT_FOUND') description='API.EMAIL_MESSAGE_NOT_FOUND')
try: cursor.execute(" DELETE FROM tbl_email_messages WHERE id = %s ", (id_,))
cursor.execute(" DELETE FROM tbl_email_messages WHERE id = %s ", (id_,)) cnx.commit()
cnx.commit()
if cursor: if cursor:
cursor.close() cursor.close()
if cnx: if cnx:
cnx.disconnect() cnx.disconnect()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
resp.status = falcon.HTTP_204 resp.status = falcon.HTTP_204

View File

@ -1,5 +1,5 @@
import falcon import falcon
import json import simplejson as json
import mysql.connector import mysql.connector
import config import config
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
@ -47,27 +47,21 @@ class TextMessageCollection:
raise falcon.HTTPError(falcon.HTTP_400, raise falcon.HTTPError(falcon.HTTP_400,
title='API.BAD_REQUEST', title='API.BAD_REQUEST',
description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME') description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
try: cnx = mysql.connector.connect(**config.myems_fdd_db)
cnx = mysql.connector.connect(**config.myems_fdd_db) cursor = cnx.cursor()
cursor = cnx.cursor()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
try: query = (" SELECT id, recipient_name, recipient_mobile, "
query = (" SELECT id, recipient_name, recipient_mobile, " " message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status "
" message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status " " FROM tbl_text_messages_outbox "
" FROM tbl_text_messages_outbox " " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
" WHERE created_datetime_utc >= %s AND created_datetime_utc < %s " " ORDER BY created_datetime_utc DESC ")
" ORDER BY created_datetime_utc ") cursor.execute(query, (start_datetime_utc, end_datetime_utc))
cursor.execute(query, (start_datetime_utc, end_datetime_utc)) rows = cursor.fetchall()
rows = cursor.fetchall()
if cursor: if cursor:
cursor.close() cursor.close()
if cnx: if cnx:
cnx.disconnect() cnx.disconnect()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
result = list() result = list()
if rows is not None and len(rows) > 0: if rows is not None and len(rows) > 0:
@ -77,8 +71,7 @@ class TextMessageCollection:
"recipient_mobile": row[2], "recipient_mobile": row[2],
"message": row[3], "message": row[3],
"created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None, "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
"scheduled_datetime": row[5].timestamp() * 1000 if isinstance(row[5], datetime) "scheduled_datetime": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
else None,
"acknowledge_code": row[6], "acknowledge_code": row[6],
"status": row[7]} "status": row[7]}
result.append(meta_result) result.append(meta_result)
@ -103,31 +96,20 @@ class TextMessageItem:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_TEXT_MESSAGE_ID') description='API.INVALID_TEXT_MESSAGE_ID')
try: cnx = mysql.connector.connect(**config.myems_fdd_db)
cnx = mysql.connector.connect(**config.myems_fdd_db) cursor = cnx.cursor()
cursor = cnx.cursor()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
try: query = (" SELECT id, recipient_name, recipient_mobile, "
query = (" SELECT id, recipient_name, recipient_mobile, " " message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status "
" message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status " " FROM tbl_text_messages_outbox "
" FROM tbl_text_messages_outbox " " WHERE id = %s ")
" WHERE id = %s ") cursor.execute(query, (id_,))
cursor.execute(query, (id_,)) row = cursor.fetchone()
row = cursor.fetchone()
if cursor: if cursor:
cursor.close() cursor.close()
if cnx: if cnx:
cnx.disconnect() cnx.disconnect()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
if row is None: if row is None:
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
@ -152,27 +134,11 @@ class TextMessageItem:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_TEXT_MESSAGE_ID') description='API.INVALID_TEXT_MESSAGE_ID')
cnx = None cnx = mysql.connector.connect(**config.myems_fdd_db)
cursor = None cursor = cnx.cursor()
try:
cnx = mysql.connector.connect(**config.myems_fdd_db)
cursor = cnx.cursor()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
try: cursor.execute(" SELECT id FROM tbl_text_messages_outbox WHERE id = %s ", (id_,))
cursor.execute(" SELECT id FROM tbl_text_messages_outbox WHERE id = %s ", (id_,)) row = cursor.fetchone()
row = cursor.fetchone()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
if row is None: if row is None:
if cursor: if cursor:
@ -182,15 +148,8 @@ class TextMessageItem:
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.TEXT_MESSAGE_NOT_FOUND') description='API.TEXT_MESSAGE_NOT_FOUND')
try: cursor.execute(" DELETE FROM tbl_text_messages_outbox WHERE id = %s ", (id_,))
cursor.execute(" DELETE FROM tbl_text_messages_outbox WHERE id = %s ", (id_,)) cnx.commit()
cnx.commit()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.DATABASE_ERROR', description=str(e))
if cursor: if cursor:
cursor.close() cursor.close()
@ -198,4 +157,3 @@ class TextMessageItem:
cnx.disconnect() cnx.disconnect()
resp.status = falcon.HTTP_204 resp.status = falcon.HTTP_204

View File

@ -1,12 +1,16 @@
import falcon import falcon
import json import simplejson as json
import mysql.connector import mysql.connector
import config import config
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from core.useractivity import user_logger from core.useractivity import user_logger, access_control
class WechatMessageCollection(object): class WechatMessageCollection(object):
@staticmethod
def __init__():
""""Initializes WechatMessageCollection"""
pass
@staticmethod @staticmethod
def on_options(req, resp, startdate, enddate): def on_options(req, resp, startdate, enddate):
@ -14,6 +18,7 @@ class WechatMessageCollection(object):
@staticmethod @staticmethod
def on_get(req, resp, startdate, enddate): def on_get(req, resp, startdate, enddate):
access_control(req)
try: try:
start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d') start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d')
except Exception: except Exception:
@ -42,7 +47,6 @@ class WechatMessageCollection(object):
raise falcon.HTTPError(falcon.HTTP_400, raise falcon.HTTPError(falcon.HTTP_400,
title='API.BAD_REQUEST', title='API.BAD_REQUEST',
description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME') description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
cnx = mysql.connector.connect(**config.myems_fdd_db) cnx = mysql.connector.connect(**config.myems_fdd_db)
cursor = cnx.cursor() cursor = cnx.cursor()
@ -51,7 +55,7 @@ class WechatMessageCollection(object):
" acknowledge_code, status " " acknowledge_code, status "
" FROM tbl_wechat_messages_outbox " " FROM tbl_wechat_messages_outbox "
" WHERE created_datetime_utc >= %s AND created_datetime_utc < %s " " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
" ORDER BY id DESC ") " ORDER BY created_datetime_utc DESC ")
cursor.execute(query, (start_datetime_utc, end_datetime_utc)) cursor.execute(query, (start_datetime_utc, end_datetime_utc))
rows = cursor.fetchall() rows = cursor.fetchall()
@ -68,11 +72,12 @@ class WechatMessageCollection(object):
"recipient_openid": row[2], "recipient_openid": row[2],
"message_template_id": row[3], "message_template_id": row[3],
"message_data": row[4], "message_data": row[4],
"created_datetime_utc": row[5].timestamp() * 1000 if row[5] else None, "created_datetime_utc": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
"scheduled_datetime_utc": row[6].timestamp() * 1000 if row[6] else None, "scheduled_datetime_utc": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
"acknowledge_code": row[7], "acknowledge_code": row[7],
"status": row[8]} "status": row[8]}
result.append(meta_result) result.append(meta_result)
resp.text = json.dumps(result) resp.text = json.dumps(result)
@ -88,6 +93,7 @@ class WechatMessageItem:
@staticmethod @staticmethod
def on_get(req, resp, id_): def on_get(req, resp, id_):
access_control(req)
if not id_.isdigit() or int(id_) <= 0: if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_WECHAT_MESSAGE_ID') description='API.INVALID_WECHAT_MESSAGE_ID')
@ -117,8 +123,8 @@ class WechatMessageItem:
"recipient_openid": row[2], "recipient_openid": row[2],
"recipient_template_id": row[3], "recipient_template_id": row[3],
"message_data": row[4], "message_data": row[4],
"created_datetime_utc": row[5].timestamp() * 1000 if row[5] else None, "created_datetime_utc": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
"scheduled_datetime_utc": row[6].timestamp() * 1000 if row[6] else None, "scheduled_datetime_utc": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
"acknowledge_code": row[7], "acknowledge_code": row[7],
"status": row[8]} "status": row[8]}
@ -127,6 +133,7 @@ class WechatMessageItem:
@staticmethod @staticmethod
@user_logger @user_logger
def on_delete(req, resp, id_): def on_delete(req, resp, id_):
access_control(req)
if not id_.isdigit() or int(id_) <= 0: if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_WECHAT_MESSAGE_ID') description='API.INVALID_WECHAT_MESSAGE_ID')
@ -147,16 +154,8 @@ class WechatMessageItem:
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.WECHAT_MESSAGE_NOT_FOUND') description='API.WECHAT_MESSAGE_NOT_FOUND')
try: cursor.execute(" DELETE FROM tbl_wechat_messages_outbox WHERE id = %s ", (id_,))
cursor.execute(" DELETE FROM tbl_wechat_messages_outbox WHERE id = %s ", (id_,)) cnx.commit()
cnx.commit()
except Exception as e:
if cursor:
cursor.close()
if cnx:
cnx.disconnect()
raise falcon.HTTPError(falcon.HTTP_500, title='API.ERROR',
description='API.DATABASE_ERROR')
if cursor: if cursor:
cursor.close() cursor.close()