def register_device(): current_app.logger.debug("Authenticating...") remote_ip = request.environ.get("HTTP_X_REAL_IP", request.remote_addr) current_app.logger.debug( "Input from '%s' on '%s': '%s'", remote_ip, request.environ.get("HTTP_ORIGIN", ""), request.json ) if request.json["registration_code"]: user = ( db.session.query(User) .filter_by(registration_code=hash_code(request.json["registration_code"].upper())) .first() ) if user: if user.registration_expiry and dt.now(tzlocal()) > user.registration_expiry: return make_response( jsonify({"error": "Failed to register device", "reason": "Expired registration code"}), 400 ) user.registration_code = None db.session.commit() token = {"ip": remote_ip, "origin": request.environ["HTTP_ORIGIN"], "user_id": user.id} return jsonify({"device_token": jwt.encode(token, os.environ.get("SECRET"), algorithm="HS256")}) else: return make_response(jsonify({"error": "Failed to register device", "reason": "User not found"}), 400) return make_response(jsonify({"error": "Failed to register device", "reason": "Missing registration code"}), 400)
def get_user_by_access_code(self, code) -> Boolean: db_session = self.get_database_session() users = db_session.query(User).all() db_session.close() code_hash = hash_code(code) self._logger.debug("User access code %s/%s in %s", code, code_hash, [u.fourkey_code for u in users]) return next(filter(lambda u: u.fourkey_code == code_hash, users), None)
def get_card_by_number(self, number) -> Card: db_session = self.get_database_session() users = db_session.query(User).all() cards = [] for user in users: cards.extend(user.cards) db_session.close() card_hash = hash_code(number) self._logger.debug("Card %s/%s in %s", number, card_hash, [c.code for c in cards]) return next(filter(lambda c: c.code == card_hash, cards), None)
def authenticate(): current_app.logger.debug("Authenticating...") # device token must be valid because of the @registered decorator device_token = jwt.decode(request.json["device_token"], os.environ.get("SECRET"), algorithms="HS256") user = db.session.query(User).get(device_token["user_id"]) if user and user.access_code == hash_code(request.json["access_code"]): return jsonify({ "user_token": generate_user_token(user.id, user.name, user.role, request.environ["HTTP_ORIGIN"]), }) elif not user: return jsonify({"error": f"invalid user id: {device_token['user_id']}"}), 400 return jsonify(False)
#!/usr/bin/env python import argparse import logging from logging import basicConfig from models import hash_code parser = argparse.ArgumentParser(description="Hash text to database format") parser.add_argument("input", help="Input string to hash") args = parser.parse_args() basicConfig(level=logging.INFO, format="%(message)s") logging.info(hash_code(args.input))