hanze/muizenval

better utilities + bug-fixes (5218b43ac13da32b7dba101314e437e3c2246d1a)
Repositories

commit 5218b43ac13da32b7dba101314e437e3c2246d1a
parent a86a1ff61afde2db1bc5c128261eb5f70c44b99a
Author: Friedel Schon <[email protected]>
Date:   Thu, 19 May 2022 19:05:32 +0200

better utilities + bug-fixes

Diffstat:
DTODO8--------
Dadd-user.py35-----------------------------------
Mcreate-db.py34++++++++++++++++++++++++++++++++--
Mreadme.md4++--
Mserver/routes.py26+++++++++++++++++++-------
Mserver/site.db0
Mserver/templates/trap.html15++++++---------
Mtest-client.py33+++++++++++++++++++++++++++------
Dtest.py4----
9 files changed, 86 insertions(+), 73 deletions(-)

diff --git a/TODO b/TODO @@ -1,7 +0,0 @@ -- gebruikers management toegevoegd -- muizenval registreren (connect butten) -- (status -> database) - - -VOOR LATER: -- muizenval reconnect -\ No newline at end of file diff --git a/add-user.py b/add-user.py @@ -1,35 +0,0 @@ -from random import randint -from server.app import db, bcrypt -from server.models import User, UserType - -#name = input('Naam? ') -#email = input('E-Mail? ') -#typ = input('Type [admin,manager,technician,catcher,client]? ') - -users = [ - (1, UserType.CLIENT, 'Boer Herman', '[email protected]', 2), - (2, UserType.ADMIN, 'Administrator Ralf', '[email protected]', None), -] - -address = 'Kerklaan 69\n9876XY Groningen' - -hashed_password = bcrypt.generate_password_hash('hallo').decode('utf-8') - -db.create_all() - -for id, typ, name, email, contact in users: - phone = '06-' + str(randint(10000000, 99999999)) - user = User( - id=id, - type=typ, - name=name, - email=email, - password=hashed_password, - phone=phone, - address = address, - contact=contact - ) - db.session.add(user) - -db.session.commit() -print('Added') diff --git a/create-db.py b/create-db.py @@ -1,5 +1,35 @@ -from server.app import db -import server.models +from random import randint +from server.app import db, bcrypt +from server.models import User, UserType + +#name = input('Naam? ') +#email = input('E-Mail? ') +#typ = input('Type [admin,manager,technician,catcher,client]? ') + +users = [ + (1, UserType.CLIENT, 'Boer Herman', '[email protected]', 2), + (2, UserType.ADMIN, 'Administrator Ralf', '[email protected]', None), +] + +address = 'Kerklaan 69\n9876XY Groningen' + +hashed_password = bcrypt.generate_password_hash('hallo').decode('utf-8') db.create_all() + +for id, typ, name, email, contact in users: + phone = '06-' + str(randint(10000000, 99999999)) + user = User( + id=id, + type=typ, + name=name, + email=email, + password=hashed_password, + phone=phone, + address = address, + contact=contact + ) + db.session.add(user) + db.session.commit() +print('Added') diff --git a/readme.md b/readme.md @@ -18,7 +18,7 @@ $ pip3 install flask wtforms flask_sqlalchemy flask-wtf email_validator flask-bc **Is de database leeg? Test-gebruikers toevoegen:** ``` -$ python3 add-user.py +$ python3 create-db.py ``` Volgende gebuikers worden toegevoegd: @@ -34,7 +34,7 @@ $ python3 run-server.py **Geen muizenval bij de hand? Interactieve test-muizenval proberen:** ``` -$ python3 test-client.py +$ python3 test-client.py --help ``` ## Known issues diff --git a/server/routes.py b/server/routes.py @@ -2,6 +2,7 @@ import json import os import secrets from datetime import datetime, timedelta +import string from flask import flash, redirect, render_template, request, url_for, jsonify from flask_login import current_user, login_required, login_user, logout_user @@ -18,11 +19,17 @@ def clean_traps(): db.session.commit() print(f'[*] {i} traps cleaned') +def validate_mac(mac): + return len(mac) == 16 and all(c in string.hexdigits for c in mac) + + @app.route("/api/update_status", methods=['POST', 'GET']) def update_status(): if not request.json: return jsonify({ "error": "invalid-json" }) - trap = Trap.query.filter_by(mac=request.json['mac']).first() + if not validate_mac(request.json['mac']): + return jsonify({ "error": "invalid-mac" }) + trap = Trap.query.filter_by(mac=request.json['mac'].lower()).first() if not trap: return jsonify({ "error": "not-found" }) @@ -38,10 +45,14 @@ def update_status(): def search_connect(): if not request.json: return jsonify({ "error": "invalid-json" }) + if not validate_mac(request.json['mac']): + return jsonify({ "error": "invalid-mac" }) - trap = Trap.query.filter_by(mac=request.json['mac']).first() + mac = request.json['mac'].lower() + + trap = Trap.query.filter_by(mac=mac).first() if not trap: - trap = Trap(mac=request.json['mac']) + trap = Trap(mac=mac) db.session.add(trap) trap.owner = None @@ -172,12 +183,13 @@ def traps(): def trap_connect(): form = ConnectTrapForm() if form.validate_on_submit() and form.mac.data: - trap = Trap.query.filter_by(mac=form.mac.data.replace(':', '').replace(' ', '')).filter(Trap.connect_expired > datetime.utcnow()).first() + trap = Trap.query.filter_by(mac=form.mac.data.replace(':', '').replace(' ', '').lower()).filter(Trap.connect_expired > datetime.utcnow()).first() if not trap: flash('Muizenval niet gevonden', 'danger') return redirect(url_for('trap_connect')) trap.owner = current_user.id + trap.connect_expired = None db.session.commit() flash('Muizenval toegevoegd!', 'success') return redirect(url_for('traps')) @@ -198,17 +210,17 @@ def trap_update(trap_id): db.session.commit() return redirect(url_for('traps')) elif not trap: - flash('Muizeval niet gevonden', 'danger') + flash('Muizenval niet gevonden', 'danger') return redirect(url_for('traps')) elif request.method == 'GET': - form.mac.data = trap.mac + form.mac.data = trap.pretty_mac() form.name.data = trap.name return render_template('updatetrap.html', form=form, trap=trap) @app.route('/trap/<trap_id>/delete') @login_required def trap_delete(trap_id): - trap = Trap.query.filter_by(mac=trap_id).first() + trap = Trap.query.filter_by(mac=trap_id.lower()).first() db.session.delete(trap) db.session.commit() diff --git a/server/site.db b/server/site.db Binary files differ. diff --git a/server/templates/trap.html b/server/templates/trap.html @@ -46,17 +46,14 @@ {% endfor %} <script type="text/javascript"> - function chunkString(str, len) { - const size = Math.ceil(str.length / len) - const r = Array(size) - let offset = 0 + function prettyMAC(str) { + var res = [] - for (let i = 0; i < size; i++) { - r[i] = str.substr(offset, len) - offset += len + for (var i = 0; i < 16; i += 2) { + res.push(str.substr(i, 2).toUpperCase()) } - return r + return res.join(':') } socket.on('trap-change', function (data) { @@ -83,7 +80,7 @@ if (trap.location_lat && trap.location_lon) { L.marker([trap.location_lat, trap.location_lon]) .addTo(map) - .bindPopup(`[${chunkString(trap.mac, 2).join(':')}] ${trap.name || ''}`); + .bindPopup(`[${prettyMAC(trap.mac)}] ${trap.name || ''}`); } } </script> diff --git a/test-client.py b/test-client.py @@ -1,11 +1,32 @@ import requests, random +from optparse import OptionParser -mac = ''.join([ random.choice('0123456789ABCDEF') for _ in range(16) ]) +parser = OptionParser() +parser.add_option('-c', '--connect', action="store_true", help='ready to connect') +parser.add_option('-s', '--status', type="choice", choices=[ "idle", "active" ], help='set status') +parser.add_option('-m', '--mac', type='string', help='mac-address to use, otherwise random') -res = requests.post('http://0.0.0.0:5000/api/search_connect', json={ 'mac': mac }) -print('MAC:', mac) -print('Answer:', res.content) +opt, args = parser.parse_args() +if (opt.connect is None) == (opt.status is None): + print("Error: either '--connect' or '--status' has to be specified") + print() + parser.print_help() + exit() -#mac = '90FD852087386BE9' -#res = requests.post('http://0.0.0.0:5000/api/update_status', json={ 'mac': mac, 'status': False }) +if opt.mac: + mac = opt.mac +else: + mac = ''.join([ random.choice('0123456789ABCDEF') for _ in range(16) ]) + +print('using mac:', mac) + +if opt.connect: + res = requests.post('http://0.0.0.0:5000/api/search_connect', json={ 'mac': mac }) + print('->', res.json()['error']) +elif opt.status == 'idle': + res = requests.post('http://0.0.0.0:5000/api/update_status', json={ 'mac': mac, 'status': False }) + print('->', res.json()['error']) +else: + res = requests.post('http://0.0.0.0:5000/api/update_status', json={ 'mac': mac, 'status': True }) + print('->', res.json()['error']) diff --git a/test.py b/test.py @@ -1,4 +0,0 @@ -code = '9939a3' - -if len(code) != 6 or not code[0:4].isnumeric() or not code[4:6].isalpha(): - print('invalid')