Пример #1
0
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")
Пример #2
0
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")
Пример #3
0
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")
Пример #4
0
 def get(self):
     cursor = connection.cursor()
     cursor.execute('show databases')
     databases = list(map(lambda x: x[0], cursor.fetchall()))
     links = list()
     for database in databases:
         links.append(link.Link(database, f'/mysql/database/{database}'))
     return Document(data={
         'databases': databases
     },
                     links=link.Collection(*links)).to_dict()
Пример #5
0
def test_should_append_embedded_document():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        document = Document(
            embedded={
                'orders': Embedded(
                    embedded={'details': Embedded(
                        data={'details': {}}
                    )},
                    links=link.Collection(
                        link.Link('foo', 'www.foo.com'),
                        link.Link('boo', 'www.boo.com')
                    ),
                    data={'total': 30},
                )
            },
            data={'currentlyProcessing': 14}
        )
        expected = {
            '_links': {
                'self': {
                    'href': flask.request.path
                }
            },
            '_embedded': {
                'orders': {
                    '_links': {
                        'foo': {'href': 'www.foo.com'},
                        'boo': {'href': 'www.boo.com'}
                    },
                    '_embedded': {
                        'details': {'details': {}}
                    },
                    'total': 30,
                }
            },
            'currentlyProcessing': 14
        }
        assert expected == document.to_dict()
Пример #6
0
 def get(self, database_name, table_name):
     try:
         connection.select_db(database_name)
         cursor = connection.cursor()
         cursor.execute(f'describe {table_name}')
         result = cursor.fetchall()
         return Document(
             data={
                 'rows': list(result)
             },
             links=link.Collection(
                 link.Link(
                     'row',
                     f'/mysql/database/{database_name}/table/{table_name}/row'
                 ))).to_dict()
     except Exception as e:
         raise InvalidUsage(str(e), 400)
Пример #7
0
 def get(self, database_name):
     try:
         connection.select_db(database_name)
         cursor = connection.cursor()
         cursor.execute('show tables')
         tables = list(map(lambda x: x[0], cursor.fetchall()))
         links = list()
         for table_name in tables:
             links.append(
                 link.Link(
                     table_name,
                     f'/mysql/database/{database_name}/table/{table_name}'))
         return Document(data={
             'tables': tables
         },
                         links=link.Collection(*links)).to_dict()
     except Exception as e:
         raise InvalidUsage(str(e), 400)
Пример #8
0
 def get(self, database_name):
     try:
         cursor = connection.cursor()
         cursor.execute('show databases')
         databases = list(map(lambda x: x[0], cursor.fetchall()))
         if database_name in databases:
             return Document(
                 data={
                     'message': f'Database {database_name} exists'
                 },
                 links=link.Collection(
                     link.Link('table',
                               f'/mysql/database/{database_name}/table')
                 )).to_dict()
         else:
             raise ValueError(f'Database {database_name} does not exist')
     except Exception as e:
         raise InvalidUsage(str(e), 400)
Пример #9
0
def search(term):
    search_results = search_wiki(term)
    collection = link.Collection()

    for result in search_results['query']['pages'].values():
        collection.append(link.Link(result['title'], result['fullurl']))
    
    response = document.Document(
        embedded={
            "results": document.Embedded(
                links=collection
            )    
        },
        data={
            "term": term,
        },
    )

    return response.to_json()
Пример #10
0
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")
Пример #11
0
 def get(self):
     return Document(links=link.Collection(
         link.Link('database', '/mysql/database'))).to_dict()
Пример #12
0
def test_document_link_as_list_is_converted_to_collection():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        document = Document(links=[link.Link('foo', 'www.foo.com')])
        assert isinstance(document.links, link.Collection)
        assert 2 == len(document.links)
Пример #13
0
def test_should_raise_exception_when_links_are_not_in_collection():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        with pytest.raises(TypeError):
            Document(links=link.Link('foo', 'www.foo.com'))
Пример #14
0
def test_data_in_embedded_can_be_array_of_documents():
    app = flask.Flask(__name__)
    with app.test_request_context('/entity/231'):
        document = Document(
            embedded={
                'order': Embedded(
                    data=[
                        Embedded(
                            data={
                                'total': 30.00,
                                'currency': 'USD',
                                'status': 'shipped'
                            },
                            links=link.Collection(
                                link.Link('foo', 'www.foo30.com'),
                                link.Link('boo', 'www.boo30.com')
                            ),
                        ),
                        Embedded(
                            data={
                                'total': 20.00,
                                'currency': 'USD',
                                'status': 'processing'
                            },
                            links=link.Collection(
                                link.Link('foo', 'www.foo20.com'),
                                link.Link('boo', 'www.boo20.com')
                            ),
                        )
                    ]
                )
            },
            data={
                'currentlyProcessing': 14
            }
        )
        expected = {
            'currentlyProcessing': 14,
            '_links': {'self': {'href': '/entity/231'}},
            '_embedded': {
                'order': [
                    {
                        '_links': {
                            'foo': {'href': 'www.foo30.com'},
                            'boo': {'href': 'www.boo30.com'}
                        },
                        'total': 30.00,
                        'currency': 'USD',
                        'status': 'shipped'
                    },
                    {
                        '_links': {
                            'foo': {'href': 'www.foo20.com'},
                            'boo': {'href': 'www.boo20.com'}
                        },
                        'total': 20.00,
                        'currency': 'USD',
                        'status': 'processing'
                    }
                ]
            }
        }
        assert expected == document.to_dict()
Пример #15
0
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")