Exemplo n.º 1
0
 def test_check_params_nok_url_no_host(self):
     with app.app_context():
         with self.assertRaises(HTTPException) as http_error:
             check_params(scheme='https',
                          host='service-shortlink.dev.bgdi.ch',
                          url='/?layers=ch.bfe.elektromobilität',
                          base_path='')
             self.assertEqual(http_error.exception.code, 400)
Exemplo n.º 2
0
 def test_check_params_nok_url_empty_string(self):
     with app.app_context():
         with self.assertRaises(HTTPException) as http_error:
             check_params(scheme='https',
                          host='service-shortlink.dev.bgdi.ch',
                          url='',
                          base_path='')
             self.assertEqual(http_error.exception.code, 400)
Exemplo n.º 3
0
 def test_check_params_nok_url_from_non_valid_domains_or_hostname(self):
     with app.app_context():
         with self.assertRaises(HTTPException) as http_error:
             check_params(
                 scheme='https',
                 host='service-shortlink.dev.bgdi.ch',
                 url=
                 'https://www.this.is.quite.invalid.ch/?layers=ch.bfe.elektromobilität',
                 base_path='')
             self.assertEqual(http_error.exception.code, 400)
Exemplo n.º 4
0
 def test_check_params_ok_https(self):
     with app.app_context():
         base_path = check_params(scheme='https',
                                  host='api3.geo.admin.ch',
                                  url='https://map.geo.admin.ch/enclume',
                                  base_path='')
         self.assertEqual(base_path, 'https://s.geo.admin.ch/')
Exemplo n.º 5
0
 def test_check_params_ok_non_standard_host(self):
     with app.app_context():
         base_path = check_params(scheme='https',
                                  host='service-shortlink.dev.bgdi.ch',
                                  url='https://map.geo.admin.ch/enclume',
                                  base_path='')
         self.assertEqual(
             base_path,
             'https://service-shortlink.dev.bgdi.ch/v4/shortlink/shortlinks/'
         )
Exemplo n.º 6
0
def create_shortlink():
    """
    * Quick summary of the function *

    The create_shortlink route's goal is to take an url and create a shortlink to it.
    The only parameter we should receive is the url to be shortened, within the post payload.

    We extract the url to shorten, the request scheme, domain and base path and send them to a
    function to check those parameters. (check_params)

    If those parameters are checked, we create the response to be sent to the user and create the
    shortlink to send back (add_item)

    * Abortions originating in this function *

    Abort with a 400 status code if we do not receive a json in the post payloadg
    Abort with a 403 status code if the Origin header is not set nor one we expect.

    * Abortions originating in functions called from this function *

    Abort with a 400 status code from check_params
    Abort with a 500 status code from add_item

    * Parameters and return values *

    :request: the request must contain a Origin Header, and a json payload with an url field
    :return: a json in response which contains the url which will redirect to the initial url
    """
    logger.debug("Shortlink Creation route entered at %f", time.time())
    if request.headers.get('Origin') is None or not \
            re.match(allowed_domains_pattern, request.headers['Origin']):
        logger.critical("Shortlink Error: Invalid Origin. ( %s )",
                        request.headers.get('Origin', 'No origin given'))
        abort(make_error_msg(403, "Not Allowed"))
    response_headers = base_response_headers
    try:
        url = request.json.get('url', None)
    except AttributeError as err:
        logger.error("No Json Received as parameter : %s", err)
        abort(
            make_error_msg(
                400,
                "This service requires a json to be posted as a payload."))
    except json.decoder.JSONDecodeError:
        logger.error("Invalid Json Received as parameter")
        abort(
            make_error_msg(
                400,
                "The json received was malformed and could not be interpreted as a json."
            ))
    scheme = request.scheme
    domain = request.url_root.replace(
        scheme, '')  # this will return the root url without the scheme
    base_path = request.script_root
    logger.debug(
        "params received are : url: %s, scheme: %s, domain: %s, base_path: %s",
        url, scheme, domain, base_path)
    base_response_url = check_params(scheme, domain, url, base_path)
    table = get_dynamodb_table()
    response = make_response(
        jsonify({
            "shorturl": ''.join(base_response_url + add_item(table, url)),
            'success': True
        }))
    response.headers = response_headers
    response_headers['Access-Control-Allow-Origin'] = request.headers['origin']
    response_headers['Access-Control-Allow-Methods'] = 'POST, OPTION'
    response_headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization,' \
                                                       ' x-requested-with, Origin, Accept'

    logger.info("Shortlink Creation Successful.",
                extra={"response": json.loads(response.get_data())})
    return response