-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Please accept my updates into the master branch of xDripAPS #6
Open
renegadeandy
wants to merge
13
commits into
colinlennon:master
Choose a base branch
from
renegadeandy:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
da5c2b6
Added support for second environment variable, header checking, rotat…
ArmyAndy ecc039f
bug fixes and log consolidation
ArmyAndy 9c68982
slight alterations and added boot message
ArmyAndy e261f40
added 2 new logs for get and post
ArmyAndy 93efbc2
bug fix, lower case hashes
ArmyAndy 60e3caa
updated readme
ArmyAndy 732dfde
extra debugging
ArmyAndy d3c4ab3
bugfix
ArmyAndy 76b0203
syntax error update
ArmyAndy 7e4353f
updated readme
ArmyAndy 4186bcd
updated doc
ArmyAndy a4d30e5
Removed log rotations so that we participate soley on openaps logrotate
ArmyAndy 6f1bbad
updated readme formatting
ArmyAndy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,34 @@ | ||
import json | ||
import os | ||
import sqlite3 | ||
import sys | ||
import logging | ||
from flask import Flask, request | ||
from flask_restful import Resource, Api | ||
from logging.handlers import RotatingFileHandler | ||
from datetime import datetime | ||
|
||
# Maximum number of rows to retain - older rows will be deleted to minimise disk usage | ||
MAX_ROWS = 336 | ||
|
||
|
||
|
||
# SQLite3 .db filename | ||
DB_FILE = os.environ['HOME']+ "/.xDripAPS_data/xDripAPS.db" | ||
|
||
app_log = logging.getLogger('root') | ||
app = Flask(__name__) | ||
api = Api(app) | ||
|
||
#Booleans to help us know which authorisation we use runtime will pick one of these during setup | ||
api_secret = True | ||
api_secret_xDripAPS = True | ||
|
||
def create_schema(): | ||
xLog("Creating database at:"+DB_FILE) | ||
if not os.path.exists(os.environ['HOME']+ "/.xDripAPS_data/"): | ||
xLog(".xDripAPS_data folder didn't exist so creating it") | ||
os.makedirs(os.environ['HOME']+ "/.xDripAPS_data/") | ||
|
||
conn = sqlite3.connect(DB_FILE) | ||
qry = """CREATE TABLE entries | ||
(device text, | ||
|
@@ -32,6 +47,13 @@ def create_schema(): | |
conn.close() | ||
|
||
def startup_checks(): | ||
|
||
xLog("Performing xDripAPS startup checks") | ||
|
||
#We are referencing our global variables here | ||
global api_secret | ||
global api_secret_xDripAPS | ||
|
||
# Does .db file exist? | ||
if os.path.isfile(DB_FILE): | ||
# Check for corruption | ||
|
@@ -40,38 +62,83 @@ def startup_checks(): | |
c.execute("PRAGMA integrity_check") | ||
status = str(c.fetchone()[0]) | ||
if status == "ok": | ||
print "Startup checks OK" | ||
xLog("Startup checks OK") | ||
conn.close() | ||
else: | ||
print "Startup checks FAIL" | ||
xLog("Startup checks FAIL") | ||
# Delete corrupt database | ||
print "Deleting corrupt SQLite database file (" + DB_FILE + ")..." | ||
xLog("Deleting corrupt SQLite database file (" + DB_FILE + ")...") | ||
conn.close() | ||
os.remove(DB_FILE) | ||
# re-create database | ||
print "Re-cresting database..." | ||
xLog("Re-cresting database...") | ||
create_schema() | ||
else: | ||
# Database doesn't exist, so create it | ||
xLog("Database doesn't exist yet, so creating it") | ||
create_schema() | ||
|
||
xLog("Checking that environment variables are setup for authorisation") | ||
try: | ||
os.environ['API_SECRET'] | ||
xLog("API_SECRET is set.") | ||
except: | ||
api_secret = False | ||
xLog("API_SECRET is not set.") | ||
try: | ||
os.environ['API_SECRET_xDripAPS'] | ||
xLog("API_SECRET_xDripAPS is set.") | ||
except: | ||
api_secret_xDripAPS = False | ||
xLog("API_SECRET_xDripAPS is not set.") | ||
|
||
if api_secret == False and api_secret_xDripAPS == False: | ||
xLog("Neither API_SECRET or API_SECRET_xDripAPS is set. Please set one and run again!") | ||
sys.exit(1) | ||
|
||
def setup_logging(): | ||
|
||
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s %(message)s') | ||
logFile = '/var/log/openaps/xDripAPS-{:%d-%m-%Y}.log'.format(datetime.now()) | ||
|
||
if not os.path.exists("/var/log/openaps"): | ||
print "/var/log/openaps directory doesn't exist! You should create this before continuing. We won't create this for you, as we expected something else, like an openaps rig to have created this for you already!" | ||
sys.exit(1) | ||
|
||
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=2*1024*1024, | ||
backupCount=2, encoding=None, delay=0) | ||
my_handler.setFormatter(log_formatter) | ||
my_handler.setLevel(logging.INFO) | ||
|
||
app_log = logging.getLogger('root') | ||
app_log.setLevel(logging.INFO) | ||
app_log.addHandler(my_handler) | ||
|
||
xLog("xDrip APS log setup complete, find the log here:"+logFile) | ||
|
||
def xLog(message): | ||
global app_log | ||
print message | ||
app_log.info(message) | ||
return | ||
|
||
class Entries(Resource): | ||
|
||
def get(self): | ||
|
||
# Connect to database | ||
conn = sqlite3.connect(DB_FILE) | ||
# Connect to database | ||
conn = sqlite3.connect(DB_FILE) | ||
|
||
# Housekeeping first | ||
qry = "DELETE FROM entries WHERE ROWID IN " | ||
qry += "(SELECT ROWID FROM entries ORDER BY ROWID DESC LIMIT -1 OFFSET " + str(MAX_ROWS) + ")" | ||
conn.execute(qry) | ||
conn.commit() | ||
# Housekeeping first | ||
qry = "DELETE FROM entries WHERE ROWID IN " | ||
qry += "(SELECT ROWID FROM entries ORDER BY ROWID DESC LIMIT -1 OFFSET " + str(MAX_ROWS) + ")" | ||
conn.execute(qry) | ||
conn.commit() | ||
|
||
# Get count parameter | ||
count = request.args.get('count') | ||
# Get count parameter | ||
count = request.args.get('count') | ||
|
||
# Perform query and return JSON data | ||
# Perform query and return JSON data | ||
qry = "SELECT ROWID as _id, device, date, dateString, sgv, direction, type, filtered, " | ||
qry += "unfiltered, rssi, noise " | ||
qry += "FROM entries ORDER BY date DESC" | ||
|
@@ -84,7 +151,7 @@ def get(self): | |
|
||
for row in cursor: | ||
result_as_dict = { | ||
# '_id' : row[0], | ||
# '_id' : row[0], | ||
'device' : row[1], | ||
'date' : row[2], | ||
'dateString' : row[3], | ||
|
@@ -95,27 +162,39 @@ def get(self): | |
'unfiltered' : row[8], | ||
'rssi' : row[9], | ||
'noise' : row[10], | ||
'glucose' : row[4]} | ||
'glucose' : row[4]} | ||
results_as_dict.append(result_as_dict) | ||
|
||
conn.close() | ||
return results_as_dict | ||
return results_as_dict | ||
|
||
def post(self): | ||
|
||
# Get hashed API secret from request | ||
request_secret_hashed = request.headers['Api_Secret'] | ||
print 'request_secret_hashed : ' + request_secret_hashed | ||
|
||
# Get API_SECRET environment variable | ||
env_secret_hashed = os.environ['API_SECRET'] | ||
|
||
try: | ||
request_secret_hashed = request.headers['Api_Secret'] | ||
xLog('request_secret_hashed : ' + request_secret_hashed) | ||
except: | ||
xLog("Client didn't pass in Api-Secret header") | ||
return 'Client didnt pass in Api-Secret header',500 | ||
|
||
if api_secret: | ||
# Get API_SECRET environment variable | ||
env_secret_hashed = os.environ['API_SECRET'] | ||
xLog("We will authenticate using environment variable API_SECRET") | ||
|
||
elif api_secret_xDripAPS: | ||
#get API_SECRET_xDripAPS environment variable if needed | ||
env_secret_hashed = os.environ['API_SECRET_xDripAPS'] | ||
xLog("We will authenticate using environment variable API_SECRET_xDripAPS") | ||
|
||
# Authentication check | ||
if request_secret_hashed != env_secret_hashed: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @ArmyAndy |
||
print 'Authentication failure!' | ||
print 'API Secret passed in request does not match API_SECRET environment variable' | ||
xLog('Authentication failure!') | ||
xLog('API Secret passed in request does not match your API_SECRET or API_SECRET_xDripAPS environment variable') | ||
return 'Authentication failed!', 401 | ||
|
||
xLog("Authentication successful") | ||
# Get JSON data | ||
json_data = request.get_json(force=True) | ||
|
||
|
@@ -161,15 +240,15 @@ class Test(Resource): | |
def get(self): | ||
# Get hashed API secret from request | ||
request_secret_hashed = request.headers['Api_Secret'] | ||
print 'request_secret_hashed : ' + request_secret_hashed | ||
xLog('request_secret_hashed : ' + request_secret_hashed) | ||
|
||
# Get API_SECRET environment variable | ||
env_secret_hashed = os.environ['API_SECRET'] | ||
|
||
# Authentication check | ||
if request_secret_hashed != env_secret_hashed: | ||
print 'Authentication failure!' | ||
print 'API Secret passed in request does not match API_SECRET environment variable' | ||
xLog('Authentication failure!') | ||
xLog('API Secret passed in request does not match API_SECRET environment variable') | ||
return 'Authentication failed!', 401 | ||
|
||
return {"status": 'ok'} | ||
|
@@ -178,5 +257,6 @@ def get(self): | |
api.add_resource(Test, '/api/v1/experiments/test') | ||
|
||
if __name__ == '__main__': | ||
setup_logging() | ||
startup_checks() | ||
app.run(host='0.0.0.0') |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a bug here -
You compare hash value with non-hash value
request secret is hashed while env_secret_hashed is actually the plain text and not hashed