예제 #1
0
def application(env, start_response):
    try:
        request = Request(env)
        response = router.dispatch(request)
        if not response or not isinstance(response, Response):
            raise HTTPError(Status.INTERNAL_SERVER_ERROR,
                            message='Unable to respond')
        else:
            _logger.info('{} {} {}'.format(request.method, request.path,
                                           response.status_string))
    except HTTPError as http_error:
        response = JsonResponse({'message': http_error.message},
                                status_code=http_error.status_code,
                                status_message=http_error.status_message)
        _logger.error('{} {} {}: message={}'.format(
            env.get('REQUEST_METHOD', ''), env.get('PATH_INFO', ''),
            response.status_string, http_error.message))
    except Exception as error:
        response = JsonResponse(
            {
                'message':
                'Internal server error, please contact server administrator'
            },
            status_code=500)
        _logger.error('{0} {1}'.format(env.get('PATH_INFO', ''),
                                       response.status_string))
        _logger.exception(error, exc_info=True)
    if response is not None:
        start_response(response.status_string, response.headers_as_tuples())
        for chunk in response:
            yield chunk
예제 #2
0
def auth_view(request: Request):
    if request.method == 'POST':
        # Create new token
        return JsonResponse(
            {'token': create_access_token(User.create_anonymous())})
    if request.method == 'DELETE':
        # TODO: Implement
        raise HTTPError(Status.NOT_IMPLEMENTED)
예제 #3
0
def private_view(request):
    user = get_user_from_request(request)
    return JsonResponse({
        'message': 'private section',
        'user': {
            'role': user.role,
            'id': user.id
        }
    })
예제 #4
0
def tokens_response(user: User, status_code=200):
    return JsonResponse(
        {
            'access_token': create_access_token(user),
            'access_token_expiration': config.JWT_ACCESS_EXPIRATION_SECONDS,
            'refresh_token': create_refresh_token(user),
            'refresh_token_expiration': config.JWT_REFRESH_EXPIRATION_SECONDS,
        },
        status_code=status_code)
예제 #5
0
def test_results(request: Request, id: str):
    result_id = ObjectId(id)
    result = results_db.find_one({'_id': result_id})
    if not result:
        raise HTTPError(Status.NOT_FOUND)
    fields = ['state', 'created', 'processed', 'user', 'test', 'data']
    data = {k: v for k, v in result.items() if k in fields}
    data['id'] = str(result_id)
    data['user'] = str(data['user'])

    created = data.get('created', None)
    if created and isinstance(created, datetime.datetime):
        data['created'] = created.isoformat()

    processed = data.get('processed', None)
    if created and isinstance(processed, datetime.datetime):
        data['processed'] = processed.isoformat()

    return JsonResponse(data)
예제 #6
0
def verify_email_view(request: Request):
    token = request.data.get('token', None)
    if token is not None:
        user = get_user_from_token(token[0], kind='email')
        existing_user = db_users.find_one({'_id': bson.ObjectId(user.id)})
        if not existing_user:
            raise HTTPError(Status.BAD_REQUEST)

        # If verified already
        if existing_user.get('verified', False):
            raise HTTPError(Status.BAD_REQUEST, 'Token was already used')

        db_users.update_one({'_id': bson.ObjectId(user.id)},
                            {'$set': {
                                'verified': True
                            }})
        return JsonResponse(
            {'message': 'Your email has been verified successfully!'})
    raise HTTPError(Status.BAD_REQUEST)
예제 #7
0
def upload_view(request):
    print(request.data)
    return JsonResponse({'message': 'upload test'})
예제 #8
0
def get_param_view(request, id):
    return JsonResponse({'message': 'test', 'id': id})
예제 #9
0
def user_view(request):
    user = get_user_from_request(request)
    return JsonResponse({'id': user.id, 'role': user.role})
예제 #10
0
def home_view(request: Request):
    return JsonResponse({'message': 'Hello'})
예제 #11
0
def load_tests_view(request: Request):
    """ Utility view for loading the tests (ADMIN only) """
    load_tests()
    return JsonResponse(tests)
예제 #12
0
def test_results_submission(request: Request, uri: str):
    """ 1. Authorized person submits a POST request via:
            - multipart
            - urlencoded form-data
            - plain/text
            - queryset
        containing keys and values for a specific set of fields
        listed in 'inputs' section in test configuration.
        2. All necessary fields are saved to the config.TESTS_RESULTS_PATH/{results_id} path
            2.1 If field do not fulfill the requirements - the request is rejected
        3. Processing runs (if required/possible) asynchronously
            3.1. If processing is successful results.json is produced containing 'outputs'
            3.2. Outputs are stored in the database
        4. {result_id} is returned while processing is still going
    """
    user = get_user_from_request(request)
    if not user or not user.id or user.role == Roles.UNAUTHORIZED:
        raise HTTPError(Status.UNAUTHORIZED)

    test = tests.get(uri, None)
    if not test:
        raise HTTPError(Status.NOT_FOUND)

    inputs = test.get('inputs', None)
    if not inputs:
        raise HTTPError(Status.INTERNAL_SERVER_ERROR,
                        message='Test is improperly configured')

    # Check inputs
    for name, input_desc in inputs.items():
        # if the field is required and not present - raise an error
        if input_desc.get('required', True) and name not in request.data:
            raise HTTPError(
                Status.INTERNAL_SERVER_ERROR,
                message='{0} field required but there is none'.format(name))

    # Create new results entry
    results_id = ObjectId()

    # Location to store results: RESULTS_PATH/<test_id>/<results_id>
    results_dir = os.path.join(config.TESTS_RESULTS_DIR, test.get('id'),
                               str(results_id))
    os.makedirs(results_dir)

    # Save json object to RESULTS_RAW_FILE
    inputs_obj = {
        '_fields': inputs,
        '_test_id': test.get('id'),
        '_user_id': user.id,
        '_results_id': str(results_id),
        '_created': datetime.datetime.utcnow().isoformat(),
        '_results': config.TESTS_RESULTS_FILE
    }
    for name, input_desc in inputs.items():
        value = request.data.get(name, None)
        if not value:
            continue
        if input_desc.get('type') == 'file':
            # TODO: save file from request
            inputs_obj[name] = input_desc.get('filename', name + '.dat')
        else:
            inputs_obj[name] = value

    # Output all RAW inputs for processing to the corresponding file
    with open(os.path.join(results_dir, config.TESTS_RESULTS_RAW_FILE),
              'w',
              encoding='utf-8') as fp:
        json.dump(inputs_obj, fp)

    # TODO: If no processing specified - do 'COPY PROCESSING'
    test_processing_desc = test.get('processing', None)
    if not test_processing_desc:
        # TODO: implement bypassing in tests
        raise HTTPError(Status.NOT_IMPLEMENTED)

    # Save result (raw one)
    result = TestResult(id=results_id,
                        user=ObjectId(user.id),
                        directory=results_dir,
                        test=test.get('id'),
                        raw_file=config.TESTS_RESULTS_RAW_FILE,
                        output_file=config.TESTS_RESULTS_FILE)
    result.save()

    # Initiate processing of raw results
    __process_and_save_async(result_id=results_id,
                             test=test,
                             result_dir=result.directory,
                             raw_file_name=result.raw_file,
                             output_file_name=result.output_file)

    # Return valid result id
    return JsonResponse({'results_id': str(results_id)},
                        status_code=Status.ACCEPTED)
예제 #13
0
def test_details_view(request: Request, uri: str):
    test = tests.get(uri, None)
    if not test:
        raise HTTPError(Status.NOT_FOUND)

    return JsonResponse(_test_to_view(test))
예제 #14
0
def tests_list_view(request: Request):
    return JsonResponse([_test_to_view(v) for v in tests.values()])