from functools import wraps
from flask import Flask
from flask import render_template, send_from_directory, request, Response, redirect, url_for
import json, time, subprocess
app = Flask(__name__)
def check_auth(username, password):
admin_list = []
with open('admin.json', 'r') as admin:
admin_list = json.load(admin)
for user in admin_list:
if username == user['username']:
return password == user['password']
def authenticate():
return Response('Could not verify access level. Please retry', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.route('/')
def index():
return '{"onFire": false}\nGo to status.'
@app.route('/status')
@requires_auth
def status():
return render_template('status.html')
@app.route('/open/')
@requires_auth
def users(what):
if what == "fridge":
subprocess.call("/home/pi/ELAB-RFID-I2C/RPi/i2c_challenge 0x20", shell=True)
elif what == "tools":
subprocess.call("/home/pi/ELAB-RFID-I2C/RPi/i2c_challenge 0x30", shell=True)
print 'opened', what
return redirect(url_for('status'))
@app.route('/gethistory')
@requires_auth
def getHistory():
return send_from_directory('.', 'history.json')
@app.route('/getcardinfo/')
@requires_auth
def getCardInfo(cardID):
return send_from_directory('cards', cardID + '.json')
@app.route('/addcard///')
@requires_auth
def addCard(cardID, name, authCode):
authCode = int(authCode)
data = {}
data["name"] = name
if authCode == 0:
data["fridge"] = False
data["secretTools"] = False
elif authCode == 1:
data["fridge"] = True
data["secretTools"] = False
elif authCode == 2:
data["fridge"] = False
data["secretTools"] = True
elif authCode == 3:
data["fridge"] = True
data["secretTools"] = True
else:
return '{"status" : "error_unknownAuthCode"}'
with open('cards/' + cardID + '.json', 'w') as outfile:
json.dump(data, outfile)
history = []
with open('history.json', 'r') as history_in:
history = json.load(history_in)
for event in history:
if event["cardID"] == cardID:
event["name"] = name
with open('history.json', 'w') as history_out:
json.dump(history, history_out)
return '{"status": "ok"}'
def epochFormat(timestamp):
timeObject = time.localtime(timestamp)
timeString = str(timeObject.tm_year) + '/' + str(timeObject.tm_mon) + '/' + str(timeObject.tm_mday) + ' - '
if timeObject.tm_hour < 10:
timeString = timeString + '0'
timeString = timeString + str(timeObject.tm_hour) + ":"
if timeObject.tm_min < 10:
timeString = timeString + '0'
timeString = timeString + str(timeObject.tm_min) + ":"
if timeObject.tm_sec < 10:
timeString = timeString + '0'
timeString = timeString + str(timeObject.tm_sec)
return timeString