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 run_public_delete_api(request, database_name, collection_name, slug, output_type):
    pass def run_httpauth_delete_api(request, database_name, collection_name, slug, output_type):
    pass def run_ipauth_delete_api(request, database_name, collection_name, slug, output_type):
    pass def create_delete_api(request, auth_type, database_name, collection_name):

    if auth_type not in model_map.keys():
        raise Http404

    mymodel = model_map[auth_type]['model']
    myform = model_map[auth_type]['form']
    name = "Create a %s" % (model_map[auth_type]['name'])

    if request.method == 'POST':
        form = myform(request.POST)
        if form.is_valid():
            form.save()
            messages.success(
                request, _("The %s was created." % (name)))

            return HttpResponseRedirect(
                reverse('djmongo_show_apis',
                        args=(database_name,
                              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
    idata = {'database_name': database_name,
             'collection_name': collection_name}
    context = {'name': name,
               'form': form(initial=idata)
               }
    return render(request, 'djmongo/console/generic/bootstrapform.html',
                  context) def edit_delete_api(request, auth_type, database_name, collection_name, slug):
    pass def delete_delete_api(request, auth_type, database_name, collection_name, slug):
    pass
from django.contrib.auth.decorators import login_required
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 django.conf.urls import url
from .views.run import (run_public_delete_api,
                        run_httpauth_delete_api,
                        run_ipauth_delete_api)
from .views.ced import (create_delete_api, edit_delete_api, delete_delete_api)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4


urlpatterns = [

    # DELETE APIs ------------------------

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

    url(r'^api/httpauth/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^.]+).(?P<output_type>[^/]+)$',

        httpauth_login_required(check_read_httpauth_access(run_httpauth_delete_api)),