def get(self, id, timestamp): ''' :param id, timestamp: ''' direction_db = g.con.get_direction(id, timestamp) if not direction_db: return create_error_response(404, "No direction data found", 'There is no direction data on device id %s with timestamp %s' % (id, timestamp), 'Direction') #create collection of links links = Collection( Self(), Link('device', '/wind/api/device/' + id + '/'), Link('list', '/wind/api/device/' + id + '/directions/'), Link('all-batteries', '/wind/api/device/' + id + '/batteries/') ) #links to dict l = links.to_dict() #combine links and speed to one dict dump = dict(list(l.items()) + list(direction_db.items())) #return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def get(self, id, timestamp): ''' :param id, timestamp: ''' speed_db = g.con.get_speed(id, timestamp) if not speed_db: return create_error_response(404, "No speed found", 'There is no speed data on device id %s with timestamp %s' % (id, timestamp), 'Speed') #create collection of links links = Collection( Self(), Link('device', '/wind/api/device/' + id + '/'), Link('list', '/wind/api/device/' + id + '/speeds/'), Link('temperatures-all', '/wind/api/device/' + id + '/temperatures/') ) #links to dict l = links.to_dict() #combine links and speed to one dict dump = dict(list(l.items()) + list(speed_db.items())) #return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def get(self, id): ''' Get device with given id from db :param id ''' device_db = g.con.get_device(id) if not device_db: return create_error_response(404, "No device found", 'There is no device info on given device id %s' % id, 'Device') #create collection of links links = Collection( Self(), Link('list', '/wind/api/devices/'), Link('data:speeds-all', request.path + '/speeds/') ) #links to dict l = links.to_dict() #combine links and speed to one dict to be returned in response #dump = dict(list(device_db.items()) + list(l.items())) dump = dict(list(l.items()) + list(device_db.items())) #return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def get(self, id): ''' get all battery values on device :param id: ''' batteries_db = g.con.get_batteries(id) if not batteries_db: return create_error_response(404, "No batteries found", 'There is no batteries data on given device id %s' % id, 'Batteries') # create collection of links links = Collection( Self(), Link('device', '/wind/api/device/' + id + '/'), Link('battery', '/wind/api/device/' + id + '/battery/{timestamp}') ) # links to dict l = links.to_dict() # combine links and speed to one dict dump = l dump.update({'items': batteries_db}) # return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def getFiles(): auth = request.headers['Authorization'].split(':') if not authenticated(auth): return 'Wrong authorization data', 400 response = requests.get('http://pdf:5000/files') fileList = [] data = response.json() for k, v in data.items(): fileShort = document.Document(data={ 'id': k, 'name': v }, links=[ Link('download', 'service/files/' + str(v), type='GET'), Link('delete', 'service/files/' + str(v), type='DELETE') ]) #pubList.append(pubShort.to_json()) fileList.append(fileShort.to_dict()) resp = {key: value for key, value in enumerate(fileList)} return json.dumps(resp)
def delete_label(lid): errors = [] links = [] links.append(Link("labels", "/sender/dashboard", type="GET")) links.append(Link("label:new", "/labels", type="POST")) login = g.authorization.get("usr") if login is None: errors.append("Musisz się zalogować") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 if not db.hexists(f"label:{lid}", "id"): errors.append("Taka etykieta nie istnieje") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 if login != db.hget(f"label:{lid}", "sender").decode(): errors.append("To nie Twoja etykieta") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 if db.hexists(f"package:{lid}", "id"): errors.append("Nie możesz usunąć tej etykiety") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 db.delete(f"label:{lid}") document = Document(links=links) return document.to_json(), 200
def get_labels_by_sender(): if g.authorization is None: return create_message_response("Unauthorized", 401) username = g.authorization.get('sub') keys = db.keys(pattern='label*') data = [] label_json = {} for key in keys: sender = db.hget(key, "sender").decode() if username == sender or g.authorization.get('role') == 'courier': label_id = key.decode().split(":")[1] link = Link('self', '/labels/' + label_id) addressee = db.hget(key, "addressee").decode() size = db.hget(key, "size").decode() po_box_id = db.hget(key, "POBoxId").decode() sent = db.hget(key, "sent").decode() label_json = { "id": label_id, "sender": sender, "addressee": addressee, "size": size, "poBox": po_box_id, "sent": sent, } data.append(Embedded(data=label_json, links=[link])) links = [Link('self', '/labels/{id}', templated=True)] document = Document(embedded={'data': Embedded(data=data)}, links=links) return document.to_json()
def get(self, id, timestamp): ''' :param id, timestamp: ''' battery_db = g.con.get_battery(id, timestamp) if not battery_db: return create_error_response(404, "No battery data found", 'There is no battery data on device id %s with timestamp %s' % (id, timestamp), 'Battery') #create collection of links links = Collection( Self(), Link('device', '/wind/api/device/' + id + '/'), Link('list', '/wind/api/device/' + id + '/batteries/') # last one, no links to other resources except device and collection ) #links to dict l = links.to_dict() #combine links and speed to one dict dump = dict(list(l.items()) + list(battery_db.items())) #return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def get(self, id): ''' get all speeds params: id ''' #extract speeds from db speeds_db = g.con.get_speeds(id) if not speeds_db: return create_error_response(404, "No speeds found", 'There is no speeds data on given device id %s' % id, 'Speeds') # create collection of links links = Collection( Self(), Link('device', '/wind/api/device/' + id + '/'), Link('speed', '/wind/api/device/' + id + '/speed/{timestamp}') ) # links to dict l = links.to_dict() # combine links and speed to one dict dump = l dump.update({'items': speeds_db}) # return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def add_package(): links = [] errors = [] login = g.authorization.get("usr") if login is None or login != "Courier": errors.append("Brak autoryzacji") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 label_id = request.json['label_id'] if label_id is None: errors.append("Brak etykiety") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 links = [] links.append(Link("packages", "/pacakges", type="GET")) links.append(Link("find", "/pacakges/{id}", templated=True, type="GET")) if not is_database_available(): errors.append("Błąd połączenia z bazą danych") document = Document(data={"errors": errors}, links=links) return document.to_json(), 500 if not db.hexists(f"label:{label_id}", "id"): errors.append("Taka etykieta nie istnieje") document = Document(data={"errors": errors}, links=links) return document.to_json(), 404 status = db.hget(f"package:{label_id}", "status") if status is not None: errors.append("Istnieje paczka utworzona z tej etykiety") document = Document(data={"errors": errors}, links=links) return document.to_json(), 404 label = { "id": db.hget(f"label:{label_id}", "id").decode(), "name": db.hget(f"label:{label_id}", "name").decode(), "delivery_id": db.hget(f"label:{label_id}", "delivery_id").decode(), "size": db.hget(f"label:{label_id}", "size").decode(), "sender": db.hget(f"label:{label_id}", "sender").decode() } success = create_package(label) if not success: errors.append("Błąd tworzenia etykiety") document = Document(data={"errors": errors}, links=links) return document.to_json(), 500 document = Document(links=links) return document.to_json(), 200 document = Document(links=links) return document.to_json(), 200
def test_to_json(self): l = Link('foo', '/foo', foo='foo', name='foo') expected = json.dumps({'foo': { 'href': '/foo', 'name': 'foo', }}) assert l.to_json() == expected
def registration(): form_values = request.json errors = [] if form_values is None: return {"error": "Brak JSON"} firstname = form_values.get("firstname") lastname = form_values.get("lastname") adress = form_values.get("adress") email = form_values.get("mail") login = form_values.get("login") password = form_values.get("password") password2 = form_values.get("password2") links = [] links.append(Link("login", "/sender/login")) links.append(Link("register", "/sender/register")) if not is_database_available(): errors.append("Błąd połączenia z bazą danych") document = Document(data={"errors": errors}, links=links) return document.to_json(), 500 if not firstname: errors.append("Brak imienia") if not lastname: errors.append("Brak nazwiska") if not adress: errors.append("Brak adresu") if not email: errors.append("Brak maila") if not login: errors.append("Brak loginu") if not password: errors.append("Brak hasła") if password != password2: errors.append("Hasła nie są takie same") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 if email and login and password and firstname and lastname and adress: if is_user(login): errors.append("Taka nazwa użytkownika istnieje") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 else: document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 success = save_user(firstname, lastname, login, email, password, adress) if not success: errors.append("Wystąpił błąd podczas rejestracji. Spróbuj później") document = Document(data={"errors": errors}, links=links) return document.to_json(), 500 document = Document(links=links) return document.to_json(), 200
def update_package(pid): errors = [] links = [] labels = {} links.append(Link("packages", "/pacakges", type="GET")) links.append(Link("package:new", "/pacakges", type="POST")) links.append(Link("find", "/pacakges/{id}", templated=True, type="GET")) login = g.authorization.get("usr") if login is None or login != "Courier": errors.append("Brak autoryzacji") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 package_id = request.json['package_id'] if package_id is None: errors.append("Brak Id paczki") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 if not is_database_available(): errors.append("Błąd połączenia z bazą danych") document = Document(data={"errors": errors}, links=links) return document.to_json(), 500 if not db.hexists(f"package:{package_id}", "id"): errors.append("Taka paczka nie istnieje") document = Document(data={"errors": errors}, links=links) return document.to_json(), 404 status = db.hget(f"package:{package_id}", "status").decode() if status == "Odebrana": errors.append( "Ta paczka została odebrana. Nie możesz zmienić jej statusu") document = Document(data={"errors": errors}, links=links) return document.to_json(), 404 sender = db.hget(f"package:{package_id}", "sender").decode() if status == "W drodze": db.hset(f"package:{package_id}", "status", "Dostarczona") db.lpush( f"notifications:{sender}", f"Paczka o numerze id {package_id} zmieniła status na 'Dostarczona'" ) elif status == "Dostarczona": db.hset(f"package:{package_id}", "status", "Odebrana") db.lpush( f"notifications:{sender}", f"Paczka o numerze id {package_id} zmieniła status na 'Odebrana'") document = Document(data=labels, links=links) return document.to_json(), 200
def test_to_json(self): l = Link('foo', '/foo', foo='foo', name='foo') expected = json.dumps({ 'foo': { 'href': '/foo', 'name': 'foo', } }) assert l.to_json() == expected
def test_to_dict(self): l = Link('foo', '/foo', foo='foo', name='foo') expected = { 'foo': { 'href': '/foo', 'name': 'foo', } } assert l.to_dict() == expected
def index(): links = [] if g.authorization.get("usr") is None: links.append(Link("login", "/sender/login")) links.append(Link("register", "/sender/register")) document = Document(data={}, links=links) return document.to_json(), 200 links.append(Link("login", "/sender/login", type="POST")) links.append(Link("registration", "/sender/register", type="POST")) document = Document(data={}, links=links) return document.to_json(), 200
def test_to_json_repeat_relation(self): c = Collection(Link('foo', '/foo'), Link('foo', '/bar')) expected = json.dumps( {'_links': { 'foo': [{ 'href': '/foo' }, { 'href': '/bar' }] }}) assert c.to_json() == expected
def root(): if request.method == 'OPTIONS': return allowed_methods(['GET']) links = [ Link('auth', '/auth'), Link('labels', '/sender'), Link('packages', '/packages') ] # if g.authorization is None: # links.append(Link('test', '/test')) document = Document(data={}, links=links) return document.to_json()
def get_labels(): data = {} links = [] labels = [] errors = [] is_not_send = request.headers.get('is_not_send') if is_not_send == "True": is_not_send = True else: is_not_send = False login = g.authorization.get("usr") if login is None or login != "Courier": errors.append("Brak autoryzacji") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 for key in db.scan_iter("label:*"): status = db.hget(f"package:{db.hget(key, 'id').decode()}", "status") if status is None: status = "Utworzona" else: status = status.decode() label = {} label = { "id": db.hget(key, "id").decode(), "name": db.hget(key, "name").decode(), "delivery_id": db.hget(key, "delivery_id").decode(), "size": db.hget(key, "size").decode(), "status": status, "sender": db.hget(key, "sender").decode() } if is_not_send: if (status == "Utworzona"): labels.append(label) else: labels.append(label) for label in labels: links.append(Link("label:" + (label["id"]), "/labels/" + label["id"])) data["labels"] = labels links.append(Link("find", "/label/{id}", templated=True)) document = Document(data=data, links=links) return document.to_json(), 200
def test_to_json(self): c = Collection(Link('foo', '/foo'), Link('bar', '/bar')) expected = json.dumps( {'_links': { 'foo': { 'href': '/foo' }, 'bar': { 'href': '/bar' } }}) assert c.to_json() == expected
def dashboard(): data = {} links = [] labels = [] errors = [] login = g.authorization.get("usr") links.append(Link("find", "/labels/{id}", templated=True)) links.append(Link("label:new", "/labels", type="POST")) if login is None: errors.append("Brak autoryzacji") document = Document(data={"errors": errors}, links=links) return document.to_json(), 401 for key in db.scan_iter("label:*"): if db.hget(key, "sender").decode() == login: status = db.hget(f"package:{db.hget(key, 'id').decode()}", "status") if status is None: status = "Utworzona" else: status = status.decode() label = {} label = { "id": db.hget(key, "id").decode(), "name": db.hget(key, "name").decode(), "delivery_id": db.hget(key, "delivery_id").decode(), "size": db.hget(key, "size").decode(), "status": status } labels.append(label) items = [] for label in labels: item_links = [] link_info = Link("info", "/labels/" + label["id"], type="GET") item_links.append(link_info) if label["status"] == "Utworzona": link_delete = Link("delete", "/labels/" + label["id"], type="DELETE") item_links.append(link_delete) items.append(Embedded(data=label, links=item_links)) document = Document(embedded={'labels': Embedded(data=items)}, links=links) return document.to_json(), 200
def login(): form_values = request.json if form_values is None: return {"error": "Brak JSON"} login = form_values.get("login") password = form_values.get("password") auth0 = form_values.get("auth0") links = [] errors = [] links.append(Link("login", "/sender/login", type="POST")) links.append(Link("registration", "/sender/register", type="POST")) if not is_database_available(): errors.append("Błąd połączenia z bazą danych") document = Document(data={"errors": errors}, links=links) return document.to_json(), 500 if auth0 is None: if not login or not password: errors.append("Brak loginu lub hasła") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 if not verify_user(login, password): errors.append("Błędny login lub hasło") document = Document(data={"errors": errors}, links=links) return document.to_json(), 400 links = [] data = {} links.append(Link("labels", "/sender/dashboard", type="GET")) links.append(Link("label:new", "/labels", type="POST")) if not db.hexists(f"user:{login}", "auth0"): db.hset(f"user:{login}", "auth0", "True") db.hset(f"user:{login}", "name", form_values.get("name")) db.hset(f"user:{login}", "email", form_values.get("email")) payload = { "exp": datetime.utcnow() + timedelta(seconds=JWT_TIME), "usr": login } token = encode(payload, JWT_SECRET, algorithm='HS256') data["status"] = "logged" data["token"] = token document = Document(data=data, links=links) return document.to_json(), 200
def test_to_dict(self): c = Collection(Link('foo', '/foo'), Link('bar', '/bar')) expected = { '_links': { 'foo': { 'href': '/foo' }, 'bar': { 'href': '/bar' } } } assert c.to_dict() == expected
def change_status(id): if g.username != COURIER_NAME: return error("Unauthorized", "Brak dostępu.", 401) json_data = request.json if not json_data: return error("No JSON provided", "Niepoprawne żądanie, brak zawartości JSON.") status = json_data.get("status") if status not in ["label", "in transit", "delivered", "collected"]: return error("Invalid status type", "Nieprawidłowy status paczki.") package = "package:" + id if not db.hexists(package, "status"): return error("Package not found", "Nie znaleziono paczki o danym identyfikatorze.") if status != db.hget(package, "status"): sender = db.hget(package, "sender") recipient = db.hget(package, "recipient") box_id = db.hget(package, "box_id") db.publish( f"user:{sender}", f"Nowy status paczki dla adresata '{recipient}', nadanej do skrytki numer {box_id}!\nOdśwież stronę, aby zobaczyć zmiany." ) db.hset(package, "status", status) links = [Link("packages", "/courier/packages")] document = Document(data={"package": db.hgetall(package)}, links=links) return document.to_json()
def delete_sender_package(username, id): if username != g.get("username") or g.get("username") == COURIER_NAME: return error("Unauthorized", "Brak dostępu.", 401) is_package_sender = db.sismember(f"user_packages:{username}", f"package:{id}") if not db.hget(f"package:{id}", "recipient"): return error("Package not found", "Nie znaleziono paczki") if not is_package_sender: return error("Unauthorized", "Brak dostępu.", 401) if not db.hget(f"package:{id}", "status") == "label": return error("Package in transit cannot be deleted", "Nie można usunąć, paczka jest już w drodze.") db.srem(f"user_packages:{username}", f"package:{id}") db.delete(f"package:{id}") log("Deleted package: " + id + " from sender: " + username) links = [Link("package:create", "/sender/" + g.username + "/packages")] document = Document(data={"status": "ok"}, links=links) return document.to_json()
def get(self): ''' Get all devices available ''' devices_db = g.con.get_devices() if not devices_db: return create_error_response(404, "No devices found", 'There is no devices in DB', 'Devices') # create collection of links links = Collection( Self(), Link('device', '/wind/api/device/{id}') ) # links to dict l = links.to_dict() # combine links and speed to one dict and add items where the actual values are dump = l dump.update({'items': devices_db}) # return Response return Response(json.dumps(dump), 200, mimetype=JSONHAL)
def version_detail(name): version = Version.objects.get(version=name) links = [Link(rel, url) for (rel, url) in version.binaries.items()] return Document(data={ 'version': version.version }, links=Collection(*links)).to_dict()
def add_user(): if request.method == 'OPTIONS': return allowed_methods(['POST']) firstname = request.json.get('firstname') lastname = request.json.get('lastname') username = request.json.get('username') password = request.json.get('password') email = request.json.get('email') address = request.json.get('address') pl = 'ąćęłńóśźż' PL = 'ĄĆĘŁŃÓŚŹŻ' if not re.compile(f'[A-Z{PL}][a-z{pl}]+').match(firstname): return create_message_response("Invalid firstname", 400) if not re.compile(f'[A-Z{PL}][a-z{pl}]+').match(lastname): return create_message_response("Invalid lastname", 400) if not re.compile('[a-z]{3,12}').match(username): return create_message_response("Invalid username", 400) if not re.compile('.{8,}').match(password.strip()): return create_message_response("Invalid password", 400) if not re.compile( '(?:[A-Za-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&\'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[A-Za-z0-9-]*[A-Za-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\\])' ).match(email.strip()): return create_message_response("Invalid email", 400) if address is None: return create_message_response("Empty address", 400) if user_exists(username): return create_message_response("Username already exists", 400) if not save_user(username, firstname, lastname, address, password, email): return create_message_response("An error occurred", 500) links = [Link('next', '/auth/login')] data = {'message': 'Account created'} document = Document(data=data, links=links) return document.to_json()
def add_label(): if g.authorization is None: return create_message_response("Unauthorized", 401) sender = g.authorization.get('sub') size = request.json.get('size') addressee = request.json.get('addressee') po_box_id = request.json.get('POBoxId') if addressee is None: return create_message_response("Invalid addressee", 400) if size not in ('XS', 'S', 'M', 'L', 'XL'): return create_message_response("Invalid size", 400) if po_box_id is None: return create_message_response("Invalid PO box id", 400) label_id = uuid.uuid4() db.hset(f"label:{label_id}", "sender", f"{sender}") db.hset(f"label:{label_id}", "addressee", f"{addressee}") db.hset(f"label:{label_id}", "size", f"{size}") db.hset(f"label:{label_id}", "POBoxId", f"{po_box_id}") db.hset(f"label:{label_id}", "sent", "false") data = { "id": str(label_id), "sender": sender, "addressee": addressee, "size": size, "POBoxId": po_box_id, "sent": "false" } links = [Link('self', '/labels/' + str(label_id))] document = Document(data=data, links=links) return document.to_json()
def sender_get_label(label_uuid): if request.method == 'OPTIONS': return allowed_methods(['GET', 'PUT', 'DELETE']) if g.authorization is None: return create_message_response("Unauthorized", 401) if not db.hexists(f"label:{label_uuid}", "size"): return create_message_response("Label not Found", 404) username = g.authorization.get('sub') if not g.authorization.get('role') == 'courier' or db.hget( f"label:{label_uuid}", "sender").decode() == username: return create_message_response("Label not found", 404) receiver = db.hget(f"label:{label_uuid}", "receiver").decode() size = db.hget(f"label:{label_uuid}", "size").decode() po_box_id = db.hget(f"label:{label_uuid}", "POBoxId").decode() sent = db.hget(f"label:{label_uuid}", "sent").decode() data = { "labelId": label_uuid, "username": username, "receiver": receiver, "size": size, "POBoxId": po_box_id, "sent": sent } links = [Link('self', '/labels/' + label_uuid)] document = Document(data=data, links=links) return document.to_json()
def package_create(): if g.authorization is None or g.authorization.get('role') != 'courier': return create_message_response("Unauthorized", 401) label_id = request.json.get('labelId') if not db.hexists(f"label:{label_id}", "size"): return create_message_response("Label not Found", 404) if not db.hget(f"label:{label_id}", "sent").decode() == 'false': return create_message_response("Label already sent", 400) db.hset(f"label:{label_id}", "sent", 'true') package_id = str(uuid.uuid4()) db.hset(f"package:{package_id}", "packageId", f"{package_id}") db.hset(f"package:{package_id}", "labelId", f"{label_id}") db.hset(f"package:{package_id}", "status", "IN_TRANSIT") data = { "packageId": package_id, "labelId": label_id, "status": "IN_TRANSIT" } links = [Link('self', '/packages/{id}', templated=True)] document = Document(embedded={'data': Embedded(data=data)}, links=links) return document.to_json()