Add auth to sensors API

This commit is contained in:
Tanner Collin 2022-10-03 21:51:22 +00:00
parent 94f023f70c
commit c618a24126
2 changed files with 42 additions and 5 deletions

45
main.py
View File

@ -14,6 +14,7 @@ import settings
import asyncio import asyncio
import json import json
import time import time
import requests
from aiohttp import web, ClientSession, ClientError from aiohttp import web, ClientSession, ClientError
from asyncio_mqtt import Client from asyncio_mqtt import Client
from datetime import datetime, timedelta from datetime import datetime, timedelta
@ -28,6 +29,15 @@ sensors_client = InfluxDBClient('localhost', 8086, database='sensors1' if PROD e
solar_client = InfluxDBClient('localhost', 8086, database='solar2') solar_client = InfluxDBClient('localhost', 8086, database='solar2')
PORT = 6903 if PROD else 6904 PORT = 6903 if PROD else 6904
def controller_message(message):
payload = dict(home=message)
r = requests.post('https://tbot.tannercollin.com/message', data=payload, timeout=10)
if r.status_code == 200:
return True
else:
logging.exception('Unable to communicate with controller! Message: ' + message)
return False
class Sensors(): class Sensors():
sensors = [] sensors = []
@ -391,9 +401,14 @@ async def history(request):
async def latest(request): async def latest(request):
result = dict() result = dict()
api_key = request.rel_url.query.get('api_key', '')
authed = api_key == settings.SENSORS_API_KEY
for sensor in sensors: for sensor in sensors:
if sensor.type_ in ['solar', 'owntracks']: if sensor.type_ in ['solar']:
continue
if not authed and sensor.type_ in ['owntracks']:
continue continue
q = 'select * from {} where "name" = \'{}\' order by desc limit 1'.format(sensor.type_, sensor.name) q = 'select * from {} where "name" = \'{}\' order by desc limit 1'.format(sensor.type_, sensor.name)
@ -410,6 +425,26 @@ async def latest(request):
async def index(request): async def index(request):
return web.Response(text='hello world', content_type='text/html') return web.Response(text='hello world', content_type='text/html')
async def run_webserver():
#web.run_app(app, port=PORT, loop=loop)
logging.info('Starting webserver on port: %s', PORT)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '0.0.0.0', PORT)
await site.start()
while True: await asyncio.sleep(10)
def task_died(future):
if os.environ.get('SHELL'):
logging.error('Sensors server task died!')
else:
logging.error('Sensors server task died! Waiting 60s and exiting...')
controller_message('Sensors server task died! Waiting 60s and exiting...')
time.sleep(60)
exit()
if __name__ == '__main__': if __name__ == '__main__':
app.router.add_get('/', index) app.router.add_get('/', index)
app.router.add_post('/owntracks', owntracks) app.router.add_post('/owntracks', owntracks)
@ -429,6 +464,8 @@ if __name__ == '__main__':
sensors.add(SolarSensor('solar', 'Solar')) sensors.add(SolarSensor('solar', 'Solar'))
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
loop.create_task(poll_sensors()) loop.create_task(poll_sensors()).add_done_callback(task_died)
loop.create_task(fetch_mqtt()) loop.create_task(fetch_mqtt()).add_done_callback(task_died)
web.run_app(app, port=PORT, loop=loop) loop.create_task(run_webserver()).add_done_callback(task_died)
loop.run_forever()

View File

@ -1 +1 @@
THERMOSTAT_IP = '' SENSORS_API_KEY = ''