示例#1
0
def register_public_key_server(request):

    if request.method == "POST":
        form = RegisteredDevicePublicKeyForm(request.user, data=request.POST)
        if form.is_valid():
            form.save()
            zone_id = form.data["zone"]

            callback_url = form.cleaned_data.get("callback_url", None)
            if callback_url:
                # New style: go directly to the origin page, which will force a sync to occur (no reason to ping refresh)
                #   This is better for the current force_job
                return HttpResponseRedirect(callback_url)
            else:
                # Old style, for clients that don't send a callback url
                messages.success(
                    request,
                    _("The device's public key has been successfully registered. You may now close this window."),
                )
                return HttpResponseRedirect(reverse("zone_management", kwargs={"zone_id": zone_id}))

    else:
        # This is hackish--we now create default organizations and zones for users, based on their
        #   registration information.  For previous users, however, we don't.  And we don't
        #   give any links / instructions for creating zones when they get here.
        # So, rather than block them, let's create an org and zone for them, so that
        #   at least they can proceed directly.
        if request.user.organization_set.count() == 0:
            # Localizing central-only import
            from central.models import Organization

            org = Organization(name="Your organization", owner=request.user)
            org.save()
            org.add_member(request.user)
            org.save()
        if not sum([org.zones.count() for org in request.user.organization_set.all()]):
            org = request.user.organization_set.all()[0]
            zone = Zone(name="Default zone")
            zone.save()
            org.add_zone(zone)

        # callback_url: 0.10.3 and higher (distributed server)
        # prev: 0.10.3 and higher (central server)
        #
        # Note: can't use referer, because this breaks if the user is redirected
        #   to the central server login page--gets confusing.
        form = RegisteredDevicePublicKeyForm(
            request.user, callback_url=request.REQUEST.get("callback_url") or request.REQUEST.get("prev")
        )
    return {"form": form}
 def setUp(self):
     super(OrganizationManagementTestCase, self).setUp()
     self.user = User(username=self.USER_EMAIL, email=self.USER_EMAIL)
     self.user.set_password(self.USER_PASSWORD)
     self.user.save()
     self.org = Organization(name=self.ORG_NAME, owner=self.user)
     self.org.save()
     self.org.add_member(self.user)
     self.org.save()
示例#3
0
def download_kalite(request, *args, **kwargs):
    """
    A request to download KA Lite, either without zone info, or with it.
    If with it, then we have to make sure it's OK for this user.

    This endpoint is also set up to deal with platform, locale, and version,
    though right now only direct URLs would set this (not via the download wizard).
    """

    # Parse args
    zone = get_object_or_None(Zone, id=kwargs.get('zone_id', None))
    platform = kwargs.get("platform", "all")
    locale = kwargs.get("locale", "en")
    version = kwargs.get("version", kalite.VERSION)
    if version == "latest":
        version = kalite.VERSION

    # Make sure this user has permission to admin this zone
    if zone and not request.user.is_authenticated():
        raise PermissionDenied(_("Requires authentication"))
    elif zone:
        zone_orgs = Organization.from_zone(zone)
        if not zone_orgs or not set([org.id for org in zone_orgs]).intersection(set(get_or_create_user_profile(request.user).get_organizations().keys())):
            raise PermissionDenied(_("You are not authorized to access this zone information."))

    # Generate the zip file.  Pre-specify the zip filename,
    #   as we won't know the output location otherwise.
    zip_file = tempfile.mkstemp()[1]
    call_command(
        "package_for_download",
        file=zip_file,
        central_server=get_central_server_host(request),
        **kwargs
    )

    # Build the outgoing filename."
    user_facing_filename = "kalite"
    for val in [platform, locale, kalite.VERSION, zone.name if zone else None]:
        user_facing_filename +=  ("-%s" % val) if val not in [None, "", "all"] else ""
    user_facing_filename += ".zip"

    # Stream it back to the user
    zh = open(zip_file,"rb")
    response = HttpResponse(content=zh, mimetype='application/zip', content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="%s"' % user_facing_filename

    # Not sure if we could remove the zip file here; possibly not,
    #   if it's a streaming response or byte-range reesponse
    return response
class OrganizationManagementTestCase(KALiteCentralBrowserTestCase):
    USER_EMAIL = "*****@*****.**"
    USER_PASSWORD = "******"
    ORG_NAME = "test org"
    ZONE_NAME = "test zone"
    FACILITY_NAME = "test facility"

    def setUp(self):
        super(OrganizationManagementTestCase, self).setUp()
        self.user = User(username=self.USER_EMAIL, email=self.USER_EMAIL)
        self.user.set_password(self.USER_PASSWORD)
        self.user.save()
        self.org = Organization(name=self.ORG_NAME, owner=self.user)
        self.org.save()
        self.org.add_member(self.user)
        self.org.save()
示例#5
0
文件: auth.py 项目: Eleonore9/ka-lite
    def wrapper_fn_central(request, *args, **kwargs):
        """
        The check for distributed servers already exists (require_login), so just use that below.
        All this nuance is for the central server only.
        """
        # inline import, to avoid unnecessary dependency on central server module
        #    on the distributed server.
        from central.models import Organization

        logged_in_user = request.user
        assert not logged_in_user.is_anonymous(), "Wrapped by login_required!"

        # Take care of superusers (Django admins).
        if logged_in_user.is_superuser:
            return handler(request, *args, **kwargs)


        # Objects we're looking to verify
        org = None; org_id      = kwargs.get("org_id", None)
        zone = None; zone_id     = kwargs.get("zone_id", None)
        facility = facility_from_request(request=request, *args, **kwargs)
        device = None; device_id   = kwargs.get("device_id", None)
        user = get_user_from_request(request=request, *args, **kwargs)

        # Validate user through facility
        if user:
            if not facility:
                facility = user.facility

        # Validate device through zone
        if device_id:
            device = get_object_or_404(Device, pk=device_id)
            if not zone_id:
                zone = device.get_zone()
                if not zone:
                    raise PermissionDenied("You requested device information for a device without a zone.  Only super users can do this!")
                zone_id = zone.pk

        # Validate device through zone
        if facility:
            if not zone_id:
                zone = facility.get_zone()
                if not zone:
                    raise PermissionDenied("You requested facility information for a facility with no zone.  Only super users can do this!")
                zone_id = zone.pk

        # Validate zone through org
        if zone_id and zone_id != "new":
            zone = get_object_or_404(Zone, pk=zone_id)
            if not org_id:
                # Have to check if any orgs are accessible to this user.
                for org in Organization.from_zone(zone):
                    if org.is_member(logged_in_user):
                        return handler(request, *args, **kwargs)
                raise PermissionDenied("You requested information from an organization that you're not authorized on.")

        if org_id and org_id != "new":
            org = get_object_or_404(Organization, pk=org_id)
            if not org.is_member(logged_in_user):
                raise PermissionDenied("You requested information from an organization that you're not authorized on.")
            elif zone_id and zone and org.zones.filter(pk=zone.pk).count() == 0:
                raise PermissionDenied("This organization does not have permissions for this zone.")

        # Made it through, we're safe!
        return handler(request, *args, **kwargs)
示例#6
0
    def wrapper_fn_central(request, *args, **kwargs):
        """
        The check for distributed servers already exists (require_login), so just use that below.
        All this nuance is for the central server only.
        """
        # inline import, to avoid unnecessary dependency on central server module
        #    on the distributed server.
        from central.models import Organization

        logged_in_user = request.user
        assert not logged_in_user.is_anonymous(), "Wrapped by login_required!"

        # Take care of superusers (Django admins).
        if logged_in_user.is_superuser:
            return handler(request, *args, **kwargs)

        # Objects we're looking to verify
        org = None
        org_id = kwargs.get("org_id", None)
        zone = None
        zone_id = kwargs.get("zone_id", None)
        facility = facility_from_request(request=request, *args, **kwargs)
        device = None
        device_id = kwargs.get("device_id", None)
        user = get_user_from_request(request=request, *args, **kwargs)

        # Validate user through facility
        if user:
            if not facility:
                facility = user.facility

        # Validate device through zone
        if device_id:
            device = get_object_or_404(Device, pk=device_id)
            if not zone_id:
                zone = device.get_zone()
                if not zone:
                    raise PermissionDenied(
                        _("You requested device information for a device without a zone.  Only super users can do this!"
                          ))
                zone_id = zone.pk

        # Validate device through zone
        if facility:
            if not zone_id:
                zone = facility.get_zone()
                if not zone:
                    raise PermissionDenied(
                        _("You requested facility information for a facility with no zone.  Only super users can do this!"
                          ))
                zone_id = zone.pk

        # Validate zone through org
        if zone_id and zone_id != "new":
            zone = get_object_or_404(Zone, pk=zone_id)
            if not org_id:
                # Have to check if any orgs are accessible to this user.
                for org in Organization.from_zone(zone):
                    if org.is_member(logged_in_user):
                        return handler(request, *args, **kwargs)
                raise PermissionDenied(
                    _("You requested information from an organization that you're not authorized on."
                      ))

        if org_id and org_id != "new":
            org = get_object_or_404(Organization, pk=org_id)
            if not org.is_member(logged_in_user):
                raise PermissionDenied(
                    _("You requested information from an organization that you're not authorized on."
                      ))
            elif zone_id and zone and org.zones.filter(
                    pk=zone.pk).count() == 0:
                raise PermissionDenied(
                    _("This organization does not have permissions for this zone."
                      ))

        # Made it through, we're safe!
        return handler(request, *args, **kwargs)