comparison weather_server/server.py @ 3:b42c4bfe57c7

server: Use a "preamble" object in the POST to auth.
author Paul Fisher <paul@pfish.zone>
date Sun, 29 Sep 2019 11:52:48 -0400
parents cda47993a193
children e7c8dcc5fc15
comparison
equal deleted inserted replaced
2:cda47993a193 3:b42c4bfe57c7
1 import bson 1 import bson
2 import flask 2 import flask
3 import hmac
3 4
4 from . import common 5 from . import common
5 from . import locations 6 from . import locations
6 from . import types 7 from . import types
7 8
19 return 'Weather server' 20 return 'Weather server'
20 21
21 @app.route('/_submit', methods=['POST']) 22 @app.route('/_submit', methods=['POST'])
22 def submit(): 23 def submit():
23 req = flask.request 24 req = flask.request
24 target = req.args.get('location')
25 if not target:
26 flask.abort(404)
27 try:
28 target_loc, logger = locs.get(target)
29 except KeyError:
30 flask.abort(404)
31
32 password = req.args.get('password')
33 if password != target_loc.password:
34 flask.abort(401)
35
36 reader = bson.decode_file_iter( 25 reader = bson.decode_file_iter(
37 req.stream, codec_options=common.BSON_OPTIONS) 26 req.stream, codec_options=common.BSON_OPTIONS)
38 entries = [ 27 try:
39 types.Reading.from_now( 28 preamble = next(reader)
40 sample_time=item['sample_time'], 29 loc_name = preamble['location']
41 temp_c=item['temp_c'], 30 password = str(preamble['password'])
42 rh_pct=item['rh_pct'], 31 loc, logger = locs.get(loc_name)
43 ) 32 if not hmac.compare_digest(password, loc.password):
44 for item in reader 33 flask.abort(400)
45 ] 34 entries = [
35 types.Reading.from_now(
36 sample_time=item['sample_time'],
37 temp_c=item['temp_c'],
38 rh_pct=item['rh_pct'],
39 )
40 for item in reader
41 ]
42 except (KeyError, bson.InvalidBSON):
43 flask.abort(400)
46 logger.write_rows(entries) 44 logger.write_rows(entries)
47 return flask.jsonify({'status': 'OK'}) 45 return flask.jsonify({'status': 'OK'})
48 46
49 @app.route('/<location>') 47 @app.route('/<location>')
50 def show(location): 48 def show(location):