def auth(username, password): if(redis_users.get(username) != None and redis_users.get(username) == password): return HALResponse(response=document.Document(data={'message': 'OK', 'token': create_token(username, password).decode('utf-8')} ,links=link.Collection(link.Link('publications', 'http://api:5000/publications'))).to_json(), status=200, mimetype="application/hal+json") else: return HALResponse(response=document.Document(data={'message': 'Login failed - wrong credentials'}).to_json(), status=401, mimetype="application/hal+json")
def publications(): token = request.headers.get('Authorization') if token != None and valid(token): payload = decode(token, JWT_SECRET) pubs = redis_files.hget('publications', payload['username']) data = {} status = 200 if request.method == 'GET': if(pubs != None): data = {'pubs': json.dumps(json.loads(pubs))} else: data = {'pubs': json.dumps([])} elif request.method == 'POST': if not ("title" in request.json and "authors" in request.json and "year" in request.json and "publisher" in request.json): return HALResponse(response=document.Document(data={'message': 'Error - not all information provided'}).to_json(), status=400, mimetype="application/hal+json") pub_id = str(uuid4()) title = request.json['title'] authors = request.json['authors'] year = request.json['year'] publisher = request.json['publisher'] new_pub_json = json.dumps({"pub_id" : pub_id, "title": title, "authors": authors, "year": year, "publisher": publisher}) pubs_json_array = [] if pubs != None: pubs_json_array = json.loads(pubs) pubs_json_array.append(json.loads(new_pub_json)) else: pubs_json_array.append(json.loads(new_pub_json)) redis_files.hset('publications', payload['username'], json.dumps(pubs_json_array)) pubs = redis_files.hget('publications', payload['username']) data = {'message': 'Publication added'} status = 201 api_links=link.Collection() if pubs: for pub in json.loads(pubs): l = link.Link(pub['pub_id'], 'http://api:5000/publications/' + pub['pub_id']) l.name = "get_update_or_delete_pub" api_links.append(l) l = link.Link(pub['pub_id'], 'http://api:5000/publications/' + pub['pub_id'] + '/files') l.name = "upload_or_get_files" api_links.append(l) return HALResponse(response=document.Document(data=data ,links=api_links).to_json(), status=status, mimetype="application/hal+json") else: return HALResponse(response=document.Document(data={'message': 'Invalid token - please try again'}).to_json(), status=401, mimetype="application/hal+json")
def post_or_get_publication_files(pid): token = request.headers.get('Authorization') or request.args('token') if token != None and valid(token): payload = decode(token, JWT_SECRET) status = 200 if request.method == 'POST': f = request.files.get('file') if f is None or f.filename == '': return HALResponse(response=document.Document(data={'message': 'Error - no file provided'}).to_json(), status=400, mimetype="application/hal+json") fid, content_type = str(uuid4()), f.content_type redis_files.hset(pid, fid, f.filename) redis_files.hset("files", fid, f.read()) redis_files.hset("content_types", fid, content_type) f.close() data = {'message': 'File uploaded'} status = 201 elif request.method == 'GET': files = redis_files.hgetall(pid) if files != None: data = {'files': json.dumps(files)} else: data = {'files': json.dumps([])} files = redis_files.hgetall(pid) api_links=link.Collection() for pub_file in files: l = link.Link(pub_file, 'http://api:5000/publications/' + pid + '/files/' + pub_file) l.name = "download_or_delete_file" api_links.append(l) return HALResponse(response=document.Document(data=data ,links=api_links).to_json(), status=status, mimetype="application/hal+json") else: return HALResponse(response=document.Document(data={'message': 'Invalid token - please try again'}).to_json(), status=401, mimetype="application/hal+json")
def test_returns_document_with_hal_document(self): app = Flask(__name__) with app.test_request_context(): d = document.Document() r = HALResponse.force_type(d, {}) expected = json.dumps({'_links': {'self': {'href': '/'}}}) assert isinstance(r, Response) assert r.headers['Content-Type'] == 'application/hal+json' assert r.data.decode("utf-8") == expected
def add_to_dashboard(): token = get_token() if(token == None): return "Blad autoryzacji", 401 login = token["login"] result = check_origin(request.origin) if(not result): return "Brak dostepu", 403 r = get_db() package_id = uuid.uuid4() receiver = request.json.get('receiver') post_id = request.json.get('postId') size = request.json.get('size') if( receiver == "" or post_id == "" or size == "" ): return "Pola nie moga byc puste", 422 try: r.hset((str)(package_id), "receiver", receiver) r.hset((str)(package_id), "post_id", post_id) r.hset((str)(package_id), "size", size) r.hset((str)(package_id), "status", "waiting") r.rpush(login, (str)(package_id)) except ConnectionError: return "Blad serwera", 503 links = link.Collection( link.Link("delete", "/sender/dashboard/" + (str)(package_id)), link.Link("update", "/sender/dashboard/" + (str)(package_id)) ) package_info = { "packageId": (str)(package_id), "receiver": receiver, "postId": post_id, "size": size, "status": "waiting" } headers = { "Access-Control-Allow-Origin": request.origin } return HALResponse(response=Document( embedded={"newPackage": Embedded(data=package_info, links=links)}).to_json(), headers=headers, content_type="application/hal+json")
def download_or_delete_publication_file(pid, fid): token = request.headers.get('Authorization') if token != None and valid(token): payload = decode(token, JWT_SECRET) if request.method == 'GET': file_name = redis_files.hget(pid, fid) file_to_download = redis_files.hget("files", fid) file_content_type = redis_files.hget("content_types", fid) if file_name is None or file_to_download is None or file_content_type is None: return HALResponse(response=document.Document(data={'message': 'File does not exist'}).to_json(), status=404, mimetype="application/hal+json") return send_file(io.BytesIO(file_to_download.encode('ISO-8859-1')), mimetype=file_content_type, attachment_filename=file_name, as_attachment=True) elif request.method == 'DELETE': redis_files.hdel("files", fid) redis_files.hdel("content_types", fid) redis_files.hdel(pid, fid) return HALResponse(response=document.Document(data={'message': 'File deleted'}).to_json(), status=200, mimetype="application/hal+json") else: return HALResponse(response=document.Document(data={'message': 'Invalid token - please try again'}).to_json(), status=401, mimetype="application/hal+json")
def get_update_or_delete_publication(pid): token = request.headers.get('Authorization') if token != None and valid(token): payload = decode(token, JWT_SECRET) pubs = redis_files.hget('publications', payload['username']) if pubs != None: pubs_json_array = json.loads(pubs) user_pub = None for pub_json in pubs_json_array: if pub_json['pub_id'] == pid: user_pub = pub_json break if pubs == None or user_pub == None: return HALResponse(response=document.Document(data={'message': 'Error - please try again'}).to_json(), status=404, mimetype="application/hal+json") if request.method == 'GET': return HALResponse(response=document.Document(data={'publication': json.dumps(user_pub)}).to_json(), status=200, mimetype="application/hal+json") elif request.method == 'DELETE': pubs_json_array.remove(user_pub) redis_files.hset('publications', payload['username'], json.dumps(pubs_json_array)) fids = redis_files.hgetall(pid) for fid in fids: redis_files.hdel("files", fid) redis_files.hdel("content_types", fid) redis_files.delete(pid) return HALResponse(response=document.Document(data={'message': 'Publication deleted'}).to_json(), status=200, mimetype="application/hal+json") elif request.method == 'PUT': if not ("title" in request.json and "authors" in request.json and "year" in request.json and "publisher" in request.json): return HALResponse(response=document.Document(data={'message': 'Error - not all information provided'}).to_json(), status=400, mimetype="application/hal+json") pubs_json_array.remove(user_pub) pub_id = user_pub['pub_id'] title = request.json['title'] authors = request.json['authors'] year = request.json['year'] publisher = request.json['publisher'] new_pub_json = json.dumps({"pub_id" : pub_id, "title": title, "authors": authors, "year": year, "publisher": publisher}) pubs_json_array.append(json.loads(new_pub_json)) redis_files.hset('publications', payload['username'], json.dumps(pubs_json_array)) return HALResponse(response=document.Document(data={'message': 'Publication updated'}).to_json(), status=200, mimetype="application/hal+json") else: return HALResponse(response=document.Document(data={'message': 'Invalid token - please try again'}).to_json(), status=401, mimetype="application/hal+json")
def test_returns_document_with_hal_document(self): app = Flask(__name__) with app.test_request_context(): d = document.Document() r = HALResponse.force_type(d, {}) expected = json.dumps({ '_links': { 'self': { 'href': '/' } } }) assert isinstance(r, Response) assert r.headers['Content-Type'] == 'application/hal+json' assert r.data.decode("utf-8") == expected
def show_dashboard(): token = get_token() if(token == None): return "Blad autoryzacji", 401 login = token["login"] result = check_origin(request.origin) if(not result): return "Brak dostepu", 403 r = get_db() try: if(login != "courier"): packages_number = r.llen(login) packages = r.lrange(login, 0, packages_number - 1) else: packages = [] keys = r.keys() for key in keys: if(r.type(key) == b"hash"): packages.append(key) except ConnectionError: return "Blad serwera", 503 decoded_packages = [p.decode() for p in packages] dashboard = {} i = 1 try: for dp in decoded_packages: receiver = r.hget(dp, "receiver").decode() post_id = r.hget(dp, "post_id").decode() size = r.hget(dp, "size").decode() status = r.hget(dp, "status").decode() package_name = "package" + (str)(i) dashboard[package_name] = Embedded( data={ "packageId": dp, "receiver": receiver, "postId": post_id, "size": size, "status": status }, links=link.Collection( link.Link("delete", "/sender/dashboard/" + (str)(dp)), link.Link("update", "/sender/dashboard/" + (str)(dp)) ) ) i = i + 1 except ConnectionError: return "Blad serwera", 503 headers = { "Access-Control-Allow-Origin": request.origin } return HALResponse(response=Document( data={"name": "dashboard"}, embedded=dashboard).to_json(), headers=headers, content_type="application/hal+json")
def test_returns_standard_response(self): r = HALResponse.force_type(Response('foo'), {}) assert isinstance(r, Response) assert r.headers['Content-Type'] == 'text/html; charset=utf-8' assert r.data.decode("utf-8") == 'foo'
def login_user(): if('username' in request.json and 'password' in request.json): return auth(request.json['username'], request.json['password']) else: return HALResponse(response=document.Document(data={'message': 'Error - please try again'}).to_json(), status=404, mimetype="application/hal+json")