def httpauth_login_required(func):
    """
        Put this decorator before your view to check if the user is logged in
        via httpauth and return a JSON 401 error if he/she is not.
    """

    def wrapper(request, *args, **kwargs):
        user = None
        # get the Basic username and password from the request.
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == "basic":
                    username, password = base64.b64decode(
                        auth[1]).decode('utf-8').split(':')
                    # print(username, password)
                    user = authenticate(username=username, password=password)

        if not user or not user.is_active:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json", status=401)
        login(request, user)
        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func) def check_read_httpauth_access(func):
    """
        Call after login decorator.
    """

    def wrapper(request, *args, **kwargs):
        database_name = kwargs.get('database_name', "")
        collection_name = kwargs.get('collection_name', "")
        slug = kwargs.get('slug', "")
        if not database_name or not collection_name:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json")

        try:
            # Check to see if we have a matching record in DB access.
            dac = HTTPAuthReadAPI.objects.get(slug=slug,
                                              database_name=database_name,
                                              collection_name=collection_name)
        except HTTPAuthReadAPI.DoesNotExist:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json")

        dac_groups = dac.groups.all()
        user_groups = request.user.groups.all()

        # allowed groups
        in_group = False
        for dg in dac_groups:
            if dg in user_groups:
                in_group = True

        if not in_group:
            message = "NOT-IN-GROUP: You do not have access to this collection. Please see your system administrator."

            body = {"code": 400,
                    "message": message,
                    "errors": [message, ]}
            return HttpResponse(json.dumps(body, indent=4, ),
                                content_type="application/json")

        # If search keys have been limited...
        if dac.search_keys:
            search_key_list = shlex.split(dac.search_keys)
            for k in request.GET.keys():

                if k not in search_key_list:
                    message = "Search key %s  is not allowed." % (k)
                    body = {"code": 400,
                            "message": k,
                            "errors": [message, ]}

                    return HttpResponse(json.dumps(body, indent=4, ),
                                        content_type="application/json")

        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func) def check_public_ok(func):
    """
        Call after login decorator.
    """

    def wrapper(request, *args, **kwargs):
        default_to_open = getattr(settings, 'DEFAULT_TO_OPEN_READ', False)
        database_name = kwargs.get('database_name', "")
        collection_name = kwargs.get('collection_name', "")
        slug = kwargs.get('slug', "")
        if not default_to_open:
            if not database_name or not collection_name:
                return HttpResponse(unauthorized_json_response(),
                                    content_type="application/json")
            try:
                pub_read_api = PublicReadAPI.objects.get(slug=slug,
                                                         database_name=database_name,
                                                         collection_name=collection_name)
            except PublicReadAPI.DoesNotExist:
                return HttpResponse(unauthorized_json_response(),
                                    content_type="application/json")

            # If search keys have been limited...
            if pub_read_api.search_keys:
                search_key_list = shlex.split(pub_read_api.search_keys)
                for k in request.GET.keys():

                    if k not in search_key_list:
                        message = "Search key %s is not allowed." % (k)

                        body = {"code": 400,
                                "message": k,
                                "errors": [message, ]}

                        return HttpResponse(json.dumps(body, indent=4, ),
                                            content_type="application/json")
        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func) def ipauth_read_verification_required(func):
    """
        Put this decorator before your view to check if the function is coming from an IP on file
    """

    def wrapper(request, *args, **kwargs):

        slug = kwargs.get('slug', "")
        database_name = kwargs.get('database_name', "")
        collection_name = kwargs.get('collection_name', "")
        if not slug:
            return kickout_404("Not found.", content_type="application/json")

        try:
            rip = IPAuthReadAPI.objects.get(slug=slug, database_name=database_name,
                                            collection_name=collection_name)
            ip = get_client_ip(request)
            if ip not in rip.allowable_ips() and "0.0.0.0" not in rip.allowable_ips():
                msg = "The IP %s is not authorized to make the API call." % (
                    ip)
                return kickout_401(msg)

        except IPAuthReadAPI.DoesNotExist:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json")

        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func) def custom_ipauth_read_verification_required(func):
    """
        Put this decorator before your view to check if the function is coming from an IP on file
    """

    def wrapper(request, *args, **kwargs):

        slug = kwargs.get('slug', "")
        if not slug:
            return kickout_404("Not found.", content_type="application/json")

        try:
            rip = CustomIPAuthReadAPI.objects.get(slug=slug)
            ip = get_client_ip(request)
            if ip not in rip.allowable_ips() and "0.0.0.0" not in rip.allowable_ips():
                msg = "The IP %s is not authorized to make the API call." % (
                    ip)
                return kickout_401(msg)

        except CustomIPAuthReadAPI.DoesNotExist:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json")

        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func) def build_keys(request, database_name, collection_name):
    """Perform the map/reduce to refresh the keys form.
       The display the custom report screen"""
    build_keys_with_mapreduce(database_name, collection_name)
    messages.success(request, _("Successfully completed MapReduce operation. "
                                "Key collection built."))
    return HttpResponseRedirect(reverse("djmongo_show_dbs")) def simple_search(request, database_name, collection_name, slug, output_type,
                  skip=0, limit=getattr(settings, 'MONGO_LIMIT', 200),
                  sort=None, return_keys=(),
                  query={}):

    if output_type == "ndjson":
        return search_ndjson(request, database_name, collection_name,
                             skip=skip, limit=limit,
                             sort=sort, return_keys=return_keys,
                             query=query)

    if output_type == "json":
        return search_json(request, database_name, collection_name,
                           skip=skip, limit=limit,
                           sort=sort, return_keys=return_keys,
                           query=query)

    if output_type == "html":
        return search_html(request, database_name, collection_name,
                           skip=skip, limit=limit,
                           sort=sort, return_keys=return_keys,
                           query=query)

    if output_type == "csv":
        return search_csv(request, database_name, collection_name,
                          skip=skip, limit=limit,
                          sort=sort, return_keys=return_keys,
                          query=query)

    if output_type in ("dat", "tsv", "txt"):
        return search_csv(request, database_name, collection_name,
                          delimiter="\t",
                          extension=output_type,
                          skip=skip, limit=limit,
                          sort=sort, return_keys=return_keys,
                          query=query)

    raise Http404 def run_custom_public_read_api_by_slug(
    request,
    slug,
    output_format=None,
    skip=0,
    sort=None,
    limit=getattr(
        settings,
        'MONGO_LIMIT',
        200)):
    error = False
    response_dict = {}
    ss = get_object_or_404(CustomPublicReadAPI, slug=slug)

    query = ss.query
    type_mapper = json.loads(ss.type_mapper)
    type_mapper_keys = type_mapper.keys()
    # if a GET param matches, then replace it

    for k, v in request.GET.items():
        print(k, v)
        if "---" in k:
            query = query.replace(k, v)
        else:
            print("fail")
        print("QUERY", query)

        if k in query:
            if k not in type_mapper_keys:
                quoted_value = '"%s"' % (v)
            else:
                if type_mapper[k] == "number":
                    quoted_value = '%s' % (v)
                if type_mapper[k] == "boolean":
                    if v in ('true', 'True', 'TRUE', 'T', 'Y' '1'):
                        quoted_value = 'true'
                    if v in ('false', 'False', 'F', 'FALSE', 'N', '0'):
                        quoted_value = 'false'
            query = query.replace(k, quoted_value)

    try:
        query = json.loads(query)
        if ss.sort:
                # print ss.sort
            sort = json.loads(ss.sort)

    except ValueError:
        response_dict = {}
        response_dict['num_results'] = 0
        response_dict['code'] = 400
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response_dict['message'] = "Your query was not valid JSON."
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response, content_type="application/json")

    if output_format:
        if output_format not in ("json", "ndjson", "csv", "txt", "html"):
            response_dict[
                'message'] = "The output format must be json, ndjson, csv, txt, or html."
            error = True
        else:
            ss.output_format = output_format
    try:
        skip = int(skip)
    except ValueError:
        response_dict['message'] = "Skip must be an integer."
        error = True
    try:
        limit = int(limit)

    except ValueError:
        response_dict['message'] = "Limit must be an integer."
        error = True
    if error:
        response_dict['num_results'] = 0
        response_dict['code'] = 400
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response,
                            content_type="application/json")

    # setup the list of keys for return if specified.
    key_list = ()
    if ss.return_keys:
        key_list = shlex.split(ss.return_keys)
    # print ss.query, ss.database_name, ss.collection_name

    if ss.output_format == "json":
        return search_json(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "ndjson":
        return search_ndjson(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "html":
        return search_html(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "csv":
        return search_csv(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "txt":
        return search_csv(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            delimiter="\t",
            return_keys=key_list)

    # these next line "should" never execute.
    response_dict = {}
    response_dict['num_results'] = 0
    response_dict['code'] = 500
    response_dict['type'] = "Error"
    response_dict['results'] = []
    response_dict['message'] = "Something has gone wrong." + \
        response_dict['message']
    response = json.dumps(response_dict, indent=4)
    return HttpResponse(response, content_type="application/json") def run_custom_httpauth_read_api_by_slug(
    request,
    slug,
    output_format=None,
    skip=0,
    sort=None,
    limit=getattr(
        settings,
        'MONGO_LIMIT',
        200)):
    error = False
    response_dict = {}
    ss = get_object_or_404(CustomHTTPAuthReadAPI, slug=slug)

    if not request.user.is_authenticated():
        response_dict = {}
        response_dict['num_results'] = 0
        response_dict['code'] = 401
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response_dict['message'] = "Not Found. Perhaps you need to log in?"
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response, content_type="application/json")
    # If a group is defined check that user is in the a group.
    elif ss.group:
        if not request.user.groups.filter(name__in=[ss.group, ]).exists():
            response_dict = {}
            response_dict['num_results'] = 0
            response_dict['code'] = 401
            response_dict['type'] = "Error"
            response_dict['results'] = []
            response_dict[
                'message'] = "You do not have permission to run this search."
            response = json.dumps(response_dict, indent=4)
            return HttpResponse(response, content_type="application/json")

    # All okay, so run the query
    query = ss.query
    type_mapper = json.loads(ss.type_mapper)
    type_mapper_keys = type_mapper.keys()
    # if a GET param matches, then replace it

    for k, v in request.GET.items():
        if k in query:
            if k not in type_mapper_keys:
                quoted_value = '"%s"' % (v)
            else:
                if type_mapper[k] == "number":
                    quoted_value = '%s' % (v)
                if type_mapper[k] == "boolean":
                    if v in ('true', 'True', 'TRUE', 'T', 'Y' '1'):
                        quoted_value = 'true'
                    if v in ('false', 'False', 'F', 'FALSE', 'N', '0'):
                        quoted_value = 'false'
            query = query.replace(k, quoted_value)

    try:
        query = json.loads(query)
        if ss.sort:
                # print ss.sort
            sort = json.loads(ss.sort)

    except ValueError:
        response_dict = {}
        response_dict['num_results'] = 0
        response_dict['code'] = 400
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response_dict['message'] = "Your query was not valid JSON."
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response, content_type="application/json")

    if output_format:
        if output_format not in ("json", "ndjson", "csv", "txt", "html"):
            response_dict[
                'message'] = "The output format must be json, ndjson, csv, txt, or html."
            error = True
        else:
            ss.output_format = output_format
    try:
        skip = int(skip)
    except ValueError:
        response_dict['message'] = "Skip must be an integer."
        error = True
    try:
        limit = int(limit)

    except ValueError:
        response_dict['message'] = "Limit must be an integer."
        error = True
    if error:
        response_dict['num_results'] = 0
        response_dict['code'] = 400
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response,
                            content_type="application/json")

    # setup the list of keys for return if specified.
    key_list = ()
    if ss.return_keys:
        key_list = shlex.split(ss.return_keys)
    # print ss.query, ss.database_name, ss.collection_name

    if ss.output_format == "json":
        return search_json(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "html":
        return search_html(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "csv":
        return search_csv(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    # these next line "should" never execute.
    response_dict = {}
    response_dict['num_results'] = 0
    response_dict['code'] = 500
    response_dict['type'] = "Error"
    response_dict['results'] = []
    response_dict['message'] = "Something has gone wrong." + \
        response_dict['message']
    response = json.dumps(response_dict, indent=4)
    return HttpResponse(response, content_type="application/json") def run_custom_ipauth_read_api_by_slug(
    request,
    slug,
    output_format=None,
    skip=0,
    sort=None,
    limit=getattr(
        settings,
        'MONGO_LIMIT',
        200)):
    error = False
    response_dict = {}
    ss = get_object_or_404(CustomIPAuthReadAPI, slug=slug)

    query = ss.query
    type_mapper = json.loads(ss.type_mapper)
    type_mapper_keys = type_mapper.keys()
    # if a GET param matches, then replace it

    for k, v in request.GET.items():
        if k in query:
            if k not in type_mapper_keys:
                quoted_value = '"%s"' % (v)
            else:
                if type_mapper[k] == "number":
                    quoted_value = '%s' % (v)
                if type_mapper[k] == "boolean":
                    if v in ('true', 'True', 'TRUE', 'T', 'Y' '1'):
                        quoted_value = 'true'
                    if v in ('false', 'False', 'F', 'FALSE', 'N', '0'):
                        quoted_value = 'false'
            query = query.replace(k, quoted_value)

    try:
        query = json.loads(query)
        if ss.sort:
                # print ss.sort
            sort = json.loads(ss.sort)

    except ValueError:
        response_dict = {}
        response_dict['num_results'] = 0
        response_dict['code'] = 400
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response_dict['message'] = "Your query was not valid JSON."
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response, content_type="application/json")

    if output_format:
        if output_format not in ("json", "ndjson", "csv", "txt", "html"):
            response_dict[
                'message'] = "The output format must be json, ndjson, csv, txt, or html."
            error = True
        else:
            ss.output_format = output_format
    try:
        skip = int(skip)
    except ValueError:
        response_dict['message'] = "Skip must be an integer."
        error = True
    try:
        limit = int(limit)

    except ValueError:
        response_dict['message'] = "Limit must be an integer."
        error = True
    if error:
        response_dict['num_results'] = 0
        response_dict['code'] = 400
        response_dict['type'] = "Error"
        response_dict['results'] = []
        response = json.dumps(response_dict, indent=4)
        return HttpResponse(response,
                            content_type="application/json")

    # setup the list of keys for return if specified.
    key_list = ()
    if ss.return_keys:
        key_list = shlex.split(ss.return_keys)
    # print ss.query, ss.database_name, ss.collection_name

    if ss.output_format == "json":
        return search_json(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "html":
        return search_html(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            sort=sort,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    if ss.output_format == "csv":
        return search_csv(
            request,
            database_name=ss.database_name,
            collection_name=ss.collection_name,
            query=query,
            skip=int(skip),
            limit=int(
                ss.default_limit),
            return_keys=key_list)

    # these next line "should" never execute.
    response_dict = {}
    response_dict['num_results'] = 0
    response_dict['code'] = 500
    response_dict['type'] = "Error"
    response_dict['results'] = []
    response_dict['message'] = "Something has gone wrong." + \
        response_dict['message']
    response = json.dumps(response_dict, indent=4)
    return HttpResponse(response, content_type="application/json") def create_simple_api(request, auth_type, database_name, collection_name):

    if auth_type == "public":
        return create_simple_public_read_api(
            request, database_name, collection_name)

    if auth_type == "httpauth":
        return create_simple_httpauth_read_api(
            request, database_name, collection_name)

    if auth_type == "ipauth":
        return create_simple_ipauth_read_api(
            request, database_name, collection_name)

    if auth_type == "oauth2":
        return create_simple_oauth2_read_api(
            request, database_name, collection_name)

    # else
    raise Http404 def create_custom_api(request, auth_type, database_name, collection_name,
                      skip=0, limit=getattr(settings, 'MONGO_LIMIT', 200),
                      return_keys=()):
    if auth_type == "public":
        return create_custom_public_read_api(
            request,
            database_name,
            collection_name,
            skip=skip,
            limit=limit,
            return_keys=return_keys)

    if auth_type == "httpauth":
        return create_custom_httpauth_read_api(
            request,
            database_name,
            collection_name,
            skip=skip,
            limit=limit,
            return_keys=return_keys)

    if auth_type == "ipauth":
        return create_custom_ipauth_read_api(
            request,
            database_name,
            collection_name,
            skip=skip,
            limit=limit,
            return_keys=return_keys)

    if auth_type == "oauth2":
        return create_custom_oauth2_read_api(
            request,
            database_name,
            collection_name,
            skip=skip,
            limit=limit,
            return_keys=return_keys)

    # else
    raise Http404 def edit_custom_httpauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    name = _("Edit Macro Basic HTTP Authentication Read API")
    ss = get_object_or_404(CustomHTTPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = CustomHTTPAuthReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save(commit=False)
            ss.user = request.user
            ss.save()
            messages.success(
                request, _("API edited."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })

    # this is a GET
    context = {'name': name,
               'form': CustomHTTPAuthReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_custom_public_read_api(request, database_name, collection_name, slug):
    name = _("Edit Macro Read API with No Authentication (Public)")
    ss = get_object_or_404(CustomPublicReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = CustomPublicReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save()
            messages.success(request, _("Simple Read API Saved."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })
    # this is a GET
    context = {'name': name,
               'form': CustomPublicReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_custom_ipauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    print(database_name, collection_name, slug)
    name = _("Edit Macro Read API with IP-Based Authentication")
    ss = get_object_or_404(CustomIPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = CustomIPAuthReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save(commit=False)
            ss.user = request.user
            ss.save()
            messages.success(
                request, _("API updated."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })
    # this is a GET
    context = {'name': name,
               'form': CustomIPAuthReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_custom_oauth2_read_api(
        request,
        database_name,
        collection_name,
        slug):
    name = _("Edit Macro Read API with OAuth2 Authentication")
    ss = get_object_or_404(CustomOAuth2ReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = CustomOAuth2ReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save(commit=False)
            ss.user = request.user
            ss.save()
            messages.success(
                request, _("API updated."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })
    # this is a GET
    context = {'name': name,
               'form': CustomOAuth2ReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_simple_httpauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    name = _("Edit Simple Read API with Basic Auth")
    ss = get_object_or_404(HTTPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = HTTPAuthReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save()
            messages.success(request, _("Simple Read API Saved."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })

    # this is a GET
    context = {'name': name,
               'form': HTTPAuthReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_simple_public_read_api(request, database_name, collection_name, slug):
    name = _("Edit Read API with No Authentication (Public)")
    ss = get_object_or_404(PublicReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = PublicReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save()
            messages.success(request, _("Simple Read API Saved."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })

    # this is a GET
    context = {'name': name,
               'form': PublicReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_simple_ipauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    name = _("Edit Read API with IP-Based Authentication")
    ss = get_object_or_404(IPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = IPAuthReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save()
            messages.success(request, _("Simple Read API Saved."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })

    # this is a GET
    context = {'name': name,
               'form': IPAuthReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_simple_oauth2_read_api(
        request,
        database_name,
        collection_name,
        slug):
    name = _("Edit Read API with OAuth2 Authentication")
    ss = get_object_or_404(OAuth2ReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)

    if request.method == 'POST':
        form = OAuth2ReadAPIForm(request.POST, instance=ss)
        if form.is_valid():
            ss = form.save()
            messages.success(request, _("API saved."))
            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(ss.database_name,
                              ss.collection_name)))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name,
                           })

    # this is a GET
    context = {'name': name,
               'form': OAuth2ReadAPIForm(instance=ss)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def delete_custom_httpauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete CustomHTTPAuthReadAPI"""
    ss = get_object_or_404(CustomHTTPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_custom_public_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete CustomPublicReadAPI"""
    ss = get_object_or_404(CustomPublicReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_custom_ipauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete CustomIPAuthReadAPI"""
    ss = get_object_or_404(CustomIPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_custom_oauth2_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete CustomOAuth2ReadAPI"""
    ss = get_object_or_404(CustomOAuth2ReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_simple_httpauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete Simple PublicReadAPI"""
    ss = get_object_or_404(HTTPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_simple_public_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete Simple PublicReadAPI"""
    ss = get_object_or_404(PublicReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_simple_oauth2_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete Simple PublicReadAPI"""
    ss = get_object_or_404(IPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name))) def delete_simple_ipauth_read_api(
        request,
        database_name,
        collection_name,
        slug):
    """Delete Simple IP Read API"""
    ss = get_object_or_404(IPAuthReadAPI, database_name=database_name,
                           collection_name=collection_name, slug=slug)
    ss.delete()
    messages.success(request, _("API deleted."))
    return HttpResponseRedirect(
        reverse('djmongo_show_apis',
                args=(ss.database_name, ss.collection_name)))
from django.contrib.auth.decorators import login_required
from django.conf.urls import url
from ..decorators import httpauth_login_required
from ..decorators import (check_read_httpauth_access,
                          check_public_ok,
                          ipauth_read_verification_required,
                          custom_ipauth_read_verification_required)
from .views.run import (build_keys, simple_search, run_custom_public_read_api_by_slug,
                        run_custom_httpauth_read_api_by_slug,
                        run_custom_ipauth_read_api_by_slug)
from .views.ced import create_simple_api, create_custom_api
from .views.ced import (edit_custom_httpauth_read_api, edit_custom_public_read_api,
                        edit_custom_ipauth_read_api, edit_custom_oauth2_read_api)
from .views.ced import (edit_simple_httpauth_read_api, edit_simple_public_read_api,
                        edit_simple_ipauth_read_api, edit_simple_oauth2_read_api)
from .views.ced import (delete_custom_httpauth_read_api, delete_custom_public_read_api,
                        delete_custom_ipauth_read_api, delete_custom_oauth2_read_api)
from .views.ced import (delete_simple_httpauth_read_api, delete_simple_public_read_api,
                        delete_simple_oauth2_read_api, delete_simple_ipauth_read_api)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4





urlpatterns = [
    # Run Read APIs ------------------------

    url(r'^api/public/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^.]+).(?P<output_type>[^/]+)$',
        check_public_ok(simple_search), name="djmongo_api_public_simple_search"),

    url(r'^api/httpauth/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^.]+).(?P<output_type>[^/]+)$',
        httpauth_login_required(check_read_httpauth_access(simple_search)),
        name="djmongo_api_httpauth_simple_search"),

    url(r'^api/ipauth/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^.]+).(?P<output_type>[^/]+)$',
        ipauth_read_verification_required(simple_search),
        name="djmongo_api_ipauth_simple_search"),


    url(r'^api/custom/httpauth/(?P<slug>\S+)$',
        httpauth_login_required(run_custom_httpauth_read_api_by_slug),
        name="djmongo_run_custom_httpauth_read_api_by_slug"),

    url(r'^api/custom/public/(?P<slug>\S+)$',
        run_custom_public_read_api_by_slug,
        name="djmongo_run_custom_public_read_api_by_slug"),

    url(r'^api/custom/ipauth/(?P<slug>\S+)$',
        custom_ipauth_read_verification_required(
            run_custom_ipauth_read_api_by_slug),
        name="djmongo_run_custom_ipauth_read_api_by_slug"),

    # CRUD for Managing APIs

    # Create -------------------------------------
    url(r'^simple/(?P<auth_type>[^/]+)/create-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)$',
        login_required(create_simple_api),
        name="djmongo_create_simple_api"),

    url(r'^custom/(?P<auth_type>[^/]+)/create-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)$',
        login_required(create_custom_api),
        name="djmongo_create_custom_api"),


    # Edit ----------------------------------------
    url(r'^simple/public/edit-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^/]+)$',
        login_required(edit_simple_public_read_api),
        name="djmongo_edit_simple_public_read_api"),

    url(r'^simple/httpauth/edit-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^/]+)$',
        login_required(edit_simple_httpauth_read_api),
        name="djmongo_edit_simple_httpauth_read_api"),

    url(r'^simple/oauth2/edit-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^/]+)$',
        login_required(edit_simple_oauth2_read_api),
        name="djmongo_edit_simple_oauth2_read_api"),

    url(r'^simple/ipauth/edit-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^/]+)$',
        login_required(edit_simple_ipauth_read_api),
        name="djmongo_edit_simple_ipauth_read_api"),


    url(r'^custom/httpauth/edit-api/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>\S+)$',

        login_required(edit_custom_httpauth_read_api),