Beispiel #1
0
    def by_expiring(self, ids_only=False, omit_guests=False):

        cursor = connection.cursor()
        try:
            cursor.execute(
                """
                SELECT DISTINCT h.mac from hosts h
                    CROSS JOIN notifications n
                    WHERE h.expires > now()
                        AND (h.last_notified IS NULL OR (now() - n.notification) > h.last_notified)
                        AND (h.expires - n.notification) < now()
                        AND UPPER(h.hostname::text) NOT LIKE UPPER('g-%%')
                        AND UPPER(h.hostname::text) NOT LIKE UPPER('%%.guests.usu.edu')
            """
            )
            hosts = [host[0] for host in cursor.fetchall()]
        finally:
            cursor.close()

        if omit_guests is True:
            guest_hostname_prefix = CONFIG.get("GUEST_HOSTNAME_FORMAT")[0]
            guest_hostname_suffix = CONFIG.get("GUEST_HOSTNAME_FORMAT")[1]

            hosts = self.filter(mac__in=hosts).exclude(
                hostname__istartswith=guest_hostname_prefix,
                hostname__iendswith=guest_hostname_suffix,
            )

        if ids_only is False:
            hosts = self.filter(mac__in=hosts)

        return hosts
    def handle(self, *args, **options):

        self.stdout.write("Adding ipam groups to users...")

        ipam_user_group, u_created = Group.objects.get_or_create(
            name=CONFIG.get("USER_GROUP")
        )
        ipam_admin_group, a_created = Group.objects.get_or_create(
            name=CONFIG.get("ADMIN_GROUP")
        )

        # Add Ipam Users
        all_users = (
            User.objects.exclude(groups=ipam_user_group).exclude(pk=-1).distinct()
        )
        super_users = (
            User.objects.exclude(groups=ipam_admin_group)
            .exclude(pk=-1)
            .filter(is_superuser=True)
            .distinct()
        )
        add_user_list = []

        for user in all_users:
            add_user_list.append(UserGroup(user=user, group=ipam_user_group))

        for user in super_users:
            add_user_list.append(UserGroup(user=user, group=ipam_admin_group))

        UserGroup.objects.bulk_create(add_user_list)

        self.stdout.write("IPAM Groups added.")
Beispiel #3
0
    def by_expiring(self, ids_only=False, omit_guests=False):

        cursor = connection.cursor()
        try:
            cursor.execute("""
                SELECT DISTINCT h.mac from hosts h
                    CROSS JOIN notifications n
                    WHERE h.expires > now()
                        AND (h.last_notified IS NULL OR (now() - n.notification) > h.last_notified)
                        AND (h.expires - n.notification) < now()
                        AND UPPER(h.hostname::text) NOT LIKE UPPER('g-%%')
                        AND UPPER(h.hostname::text) NOT LIKE UPPER('%%.guests.usu.edu')
            """)
            hosts = [host[0] for host in cursor.fetchall()]
        finally:
            cursor.close()

        if omit_guests is True:
            guest_hostname_prefix = CONFIG.get('GUEST_HOSTNAME_FORMAT')[0]
            guest_hostname_suffix = CONFIG.get('GUEST_HOSTNAME_FORMAT')[1]

            hosts = self.filter(mac__in=hosts).exclude(
                hostname__istartswith=guest_hostname_prefix,
                hostname__iendswith=guest_hostname_suffix
            )

        if ids_only is False:
            hosts = self.filter(mac__in=hosts)

        return hosts
Beispiel #4
0
    def get(self, request, format=None, **kwargs):
        # see http://peewee.readthedocs.org/en/latest/peewee/database.html#error-2006-mysql-server-has-gone-away
        observium_db.connect()

        if request.query_params.get('buildings', False):
            data = OrderedDict(copy.deepcopy(CONFIG.get('BUILDINGMAP_DATA').get('data')))
        else:
            data = OrderedDict(copy.deepcopy(CONFIG.get('WEATHERMAP_DATA').get('data')))

        all_ports = []
        for k, v in data.items():
            all_ports.extend(v['id'])

        ports = Ports.select(Ports).where(Ports.port << all_ports)

        for port in ports:
            for key, value in data.items():
                for portid in value['id']:
                    if port.port == portid:
                        value['A'] = value.get('A', 0) + port.ifoutoctets_rate * 8
                        value['Z'] = value.get('Z', 0) + port.ifinoctets_rate * 8
                        value['speed'] = value.get('speed', 0) + port.ifspeed if port.ifspeed else 0
                        value['timestamp'] = port.poll_time
                        value['poll_frequency'] = 300

        for key, value in data.items():
            del value['id']

        data["timestamp"] = int(datetime.now().strftime('%s'))

        if not observium_db.is_closed():
            observium_db.close()

        return Response(data, status=status.HTTP_200_OK)
Beispiel #5
0
    def handle(self, *args, **options):

        self.stdout.write("Adding ipam groups to users...")

        ipam_user_group, u_created = Group.objects.get_or_create(
            name=CONFIG.get("USER_GROUP"))
        ipam_admin_group, a_created = Group.objects.get_or_create(
            name=CONFIG.get("ADMIN_GROUP"))

        # Add Ipam Users
        all_users = (User.objects.exclude(groups=ipam_user_group).exclude(
            pk=-1).distinct())
        super_users = (User.objects.exclude(groups=ipam_admin_group).exclude(
            pk=-1).filter(is_superuser=True).distinct())
        add_user_list = []

        for user in all_users:
            add_user_list.append(UserGroup(user=user, group=ipam_user_group))

        for user in super_users:
            add_user_list.append(UserGroup(user=user, group=ipam_admin_group))

        UserGroup.objects.bulk_create(add_user_list)

        self.stdout.write("IPAM Groups added.")
Beispiel #6
0
    def filter_queryset(self, qs):
        # use request parameters to filter queryset
        column_data = self.json_data.get("columns", [])

        try:

            username_search = column_data[1]["search"]["value"].strip()
            fullname_search = column_data[2]["search"]["value"].strip()
            email_search = column_data[3]["search"]["value"].strip()
            staff_search = column_data[4]["search"]["value"].strip()
            super_search = column_data[5]["search"]["value"].strip()
            ipam_admin_search = column_data[6]["search"]["value"].strip()
            source_search = column_data[7]["search"]["value"].strip()
            search = self.json_data.get("search_filter", "").strip()
            search_list = search.strip().split(",") if search else []

            for search_item in search_list:
                search_str = "".join(search_item.split(":")[1:])
                if search_item.startswith("user:"******"group:"):
                    qs = qs.filter(groups__name=search_item[6:])
                elif search_item.startswith("gperm:"):
                    qs = qs.filter(groups__groupobjectpermission__pk=search_item[6:])
                elif search_item.startswith("uperm:"):
                    qs = qs.filter(userobjectpermission__pk=search_item[6:])

            if username_search:
                qs = qs.filter(username__istartswith=username_search)
            if fullname_search:
                qs = qs.filter(
                    Q(first_name__icontains=fullname_search)
                    | Q(last_name__icontains=fullname_search)
                )
            if email_search:
                qs = qs.filter(email__icontains=email_search)
            if staff_search:
                qs = qs.filter(is_staff=True if staff_search == "1" else False)
            if super_search:
                qs = qs.filter(is_superuser=True if super_search == "1" else False)
            if ipam_admin_search:
                if ipam_admin_search == "1":
                    qs = qs.filter(
                        Q(is_superuser=True) | Q(groups__name=CONFIG.get("ADMIN_GROUP"))
                    ).distinct()
                else:
                    qs = qs.filter(is_superuser=False).exclude(
                        groups__name=CONFIG.get("ADMIN_GROUP")
                    )
            if source_search:
                qs = qs.filter(
                    source__name="INTERNAL" if source_search == "1" else "LDAP"
                )

        except (DatabaseError, ValidationError):
            pass

        return qs
Beispiel #7
0
    def filter_queryset(self, qs):
        # use request parameters to filter queryset
        column_data = self.json_data.get("columns", [])

        try:

            username_search = column_data[1]["search"]["value"].strip()
            fullname_search = column_data[2]["search"]["value"].strip()
            email_search = column_data[3]["search"]["value"].strip()
            staff_search = column_data[4]["search"]["value"].strip()
            super_search = column_data[5]["search"]["value"].strip()
            ipam_admin_search = column_data[6]["search"]["value"].strip()
            source_search = column_data[7]["search"]["value"].strip()
            search = self.json_data.get("search_filter", "").strip()
            search_list = search.strip().split(",") if search else []

            for search_item in search_list:
                search_str = "".join(search_item.split(":")[1:])
                if search_item.startswith("user:"******"group:"):
                    qs = qs.filter(groups__name=search_item[6:])
                elif search_item.startswith("gperm:"):
                    qs = qs.filter(
                        groups__groupobjectpermission__pk=search_item[6:])
                elif search_item.startswith("uperm:"):
                    qs = qs.filter(userobjectpermission__pk=search_item[6:])

            if username_search:
                qs = qs.filter(username__istartswith=username_search)
            if fullname_search:
                qs = qs.filter(
                    Q(first_name__icontains=fullname_search)
                    | Q(last_name__icontains=fullname_search))
            if email_search:
                qs = qs.filter(email__icontains=email_search)
            if staff_search:
                qs = qs.filter(is_staff=True if staff_search == "1" else False)
            if super_search:
                qs = qs.filter(
                    is_superuser=True if super_search == "1" else False)
            if ipam_admin_search:
                if ipam_admin_search == "1":
                    qs = qs.filter(
                        Q(is_superuser=True)
                        | Q(groups__name=CONFIG.get("ADMIN_GROUP"))).distinct(
                        )
                else:
                    qs = qs.filter(is_superuser=False).exclude(
                        groups__name=CONFIG.get("ADMIN_GROUP"))
            if source_search:
                qs = qs.filter(source__name="INTERNAL" if source_search ==
                               "1" else "LDAP")

        except (DatabaseError, ValidationError):
            pass

        return qs
Beispiel #8
0
    def post(self, request, format=None, **kwargs):
        serializer = GuestRegisterSerializer(data=request.data)

        if serializer.is_valid():
            hostname_prefix = CONFIG.get('GUEST_HOSTNAME_FORMAT')[0]
            hostname_suffix = CONFIG.get('GUEST_HOSTNAME_FORMAT')[1]
            last_hostname = (Host.objects.filter(hostname__istartswith=hostname_prefix, hostname__iendswith=hostname_suffix)
                .extra(select={'hostname_length': 'length(hostname)'})
                .order_by('-hostname_length', '-hostname')
                .first()
            )
            hostname_index = int(last_hostname.hostname[len(hostname_prefix):last_hostname.hostname.find(hostname_suffix)])
            guest_user = User.objects.get(username__iexact=CONFIG.get('GUEST_USER'))
            user_owner = serializer.valid_ticket.user
            description = serializer.data.get('description')
            name = serializer.data.get('name')
            ticket = serializer.data.get('ticket')
            mac_address = serializer.data.get('mac_address')

            try:
                hostname = '%s%s%s' % (hostname_prefix, hostname_index + 1, hostname_suffix)

                # Check if instance already created.  Bug in DHCP thats registering it twice??
                instance = Host.objects.filter(hostname=hostname, mac=mac_address).first()

                # Add or update host
                Host.objects.add_or_update_host(
                    user=guest_user,
                    hostname=hostname,
                    mac=mac_address,
                    expires=serializer.valid_ticket.ends,
                    description=description if description else 'Name: %s; Ticket used: %s' % (name, ticket),
                    pool=Pool.objects.get(name=CONFIG.get('GUEST_POOL')),
                    user_owners=[user_owner],
                    group_owners=[CONFIG.get('GUEST_GROUP')],
                    instance=instance or None
                )
            except ValidationError as e:
                error_list = []
                if hasattr(e, 'error_dict'):
                    for key, errors in e.message_dict.items():
                        for error in errors:
                            error_list.append(error)
                else:
                    error_list.append(e.message)
                return Response({'non_field_errors': error_list}, status=status.HTTP_400_BAD_REQUEST)

            data = {
                'starts': serializer.valid_ticket.starts,
                'ends': serializer.valid_ticket.ends
            }
            data.update(serializer.data)

            return Response(data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #9
0
def index(request):
    if CONFIG.get("DUO_LOGIN") and not is_duo_authenticated(request):
        return redirect("duo_auth")
    if not request.user.get_full_name() or not request.user.email:
        return redirect("profile")
    else:
        context = {
            "email": CONFIG.get("EMAIL_ADDRESS"),
            "legacy_domain": CONFIG.get("LEGACY_DOAMIN"),
        }
        return AdminSite().index(request, extra_context=context)
Beispiel #10
0
def index(request):
    if CONFIG.get("DUO_LOGIN") and not is_duo_authenticated(request):
        return redirect("duo_auth")
    if not request.user.get_full_name() or not request.user.email:
        return redirect("profile")
    else:
        context = {
            "email": CONFIG.get("EMAIL_ADDRESS"),
            "legacy_domain": CONFIG.get("LEGACY_DOAMIN"),
        }
        return AdminSite().index(request, extra_context=context)
Beispiel #11
0
    def get_context_data(self, **kwargs):
        context = super(HostDetailView, self).get_context_data(**kwargs)
        attributes = []
        attributes += self.object.freeform_attributes.values_list(
            "attribute__description", "value")
        attributes += self.object.structured_attributes.values_list(
            "structured_attribute_value__attribute__description",
            "structured_attribute_value__value",
        )
        context["read_only"] = self.kwargs.get("read_only", False)
        context["attributes"] = attributes
        context["dns_records"] = self.object.get_dns_records()
        context["addresses"] = self.object.addresses.select_related().all()
        context["pools"] = self.object.pools.all()
        context["leased_addresses"] = self.object.leases.select_related(
            "address", "host").all()
        context["user_owners"], context[
            "group_owners"] = self.object.get_owners()
        context["disabled_info"] = Disabled.objects.filter(
            pk=self.object.pk).first()
        context["disabled_website"] = CONFIG.get("DISABLED_HOSTS_WEBSITE")
        context["view_show_users"] = (
            True if self.object.user.has_perm("user.view_user") else False)

        return context
Beispiel #12
0
def login(request, internal=False, **kwargs):
    if CONFIG.get("CAS_LOGIN") and internal is False:
        return cas_login(request, **kwargs)
    else:
        return auth_login_view(
            request, authentication_form=IPAMAuthenticationForm, **kwargs
        )
Beispiel #13
0
    def _get(self, request, format=None, **kwargs):
        if request.query_params.get("buildings", False):
            data = OrderedDict(
                copy.deepcopy(get_buildingmap_data().get("data")))
        else:
            data = OrderedDict(
                copy.deepcopy(CONFIG.get("WEATHERMAP_DATA").get("data")))

        all_ports = []
        for k, v in list(data.items()):
            all_ports.extend(v["id"])

        ports = Ports.select(Ports).where(Ports.port << all_ports)

        for port in ports:
            for key, value in list(data.items()):
                for portid in value["id"]:
                    if port.port == portid:
                        value["A"] = value.get("A",
                                               0) + port.ifoutoctets_rate * 8
                        value["Z"] = value.get("Z",
                                               0) + port.ifinoctets_rate * 8
                        value["speed"] = (value.get("speed", 0) +
                                          port.ifspeed if port.ifspeed else 0)
                        value["timestamp"] = port.poll_time
                        value["poll_frequency"] = 300
                        value["isUp"] = bool(port.ifoperstatus == "up")

        for key, value in list(data.items()):
            del value["id"]

        data["timestamp"] = int(datetime.now().strftime("%s"))

        return Response(data, status=status.HTTP_200_OK)
Beispiel #14
0
def duo_auth(request):
    if is_duo_authenticated(request):
        return redirect("index")

    sig_request = None
    duo_settings = CONFIG.get("DUO_SETTINGS", {})

    if request.POST:
        sig_response = request.POST.get("sig_response", None)
        if sig_response:
            authenticated_username = duo_web.verify_response(
                duo_settings.get("IKEY"),
                duo_settings.get("SKEY"),
                duo_settings.get("AKEY"),
                sig_response,
            )
            if authenticated_username:
                duo_authenticate(request)
                return redirect("admin:index")

    sig_request = duo_web.sign_request(
        duo_settings.get("IKEY"),
        duo_settings.get("SKEY"),
        duo_settings.get("AKEY"),
        request.user.username,
    )

    context = {
        "sig_request": sig_request,
        "host": duo_settings.get("HOST"),
        "post_action": reverse("duo_auth"),
    }
    return render(request, "registration/duo.html", context)
Beispiel #15
0
    def process_request(self, request):
        assert hasattr(
            request, "user"
        ), "The Duo Auth Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."

        duo_exempt_urls = [
            reverse("profile"),
            reverse("password_change"),
            reverse("password_change_done"),
            reverse("duo_auth"),
        ]

        if CONFIG.get("DUO_LOGIN"):
            if request.user.is_authenticated() and not request.session.get(
                "duo_authenticated", False
            ):
                path = request.path.lstrip("/")
                if not any(m.match(path) for m in EXEMPT_URLS):
                    if request.path not in duo_exempt_urls:
                        return redirect("duo_auth")
Beispiel #16
0
def duo_auth(request):
    if is_duo_authenticated(request):
        return redirect("index")

    sig_request = None
    duo_settings = CONFIG.get("DUO_SETTINGS", {})

    if request.POST:
        sig_response = request.POST.get("sig_response", None)
        if sig_response:
            authenticated_username = duo_web.verify_response(
                duo_settings.get("IKEY"),
                duo_settings.get("SKEY"),
                duo_settings.get("AKEY"),
                sig_response,
            )
            if authenticated_username:
                duo_authenticate(request)
                return redirect(request.GET.get("next", "admin:index"))

    sig_request = duo_web.sign_request(
        duo_settings.get("IKEY"),
        duo_settings.get("SKEY"),
        duo_settings.get("AKEY"),
        request.user.username,
    )

    context = {
        "sig_request": sig_request,
        "host": duo_settings.get("HOST"),
        "post_action": f"{reverse('duo_auth')}?next={request.GET.get('next')}",
    }
    return render(request, "registration/duo.html", context)
Beispiel #17
0
    def has_permission(self, request, view):
        if request.user.is_superuser:
            return True

        has_api_group = request.user.groups.filter(name=CONFIG.get("API_USER_GROUP"))
        if has_api_group:
            return True

        return False
Beispiel #18
0
    def has_permission(self, request, view):
        if request.user.is_superuser:
            return True

        has_api_group = request.user.groups.filter(
            name=CONFIG.get("API_USER_GROUP"))
        if has_api_group:
            return True

        return False
    def handle(self, *args, **options):

        self.stdout.write("Adding default permissions to ipam-users group...")

        ipam_user_group, u_created = Group.objects.get_or_create(
            name=CONFIG.get("USER_GROUP"))
        ipam_admin_group, a_created = Group.objects.get_or_create(
            name=CONFIG.get("ADMIN_GROUP"))

        default_perms = CONFIG.get("DEFAULT_PERMISSIONS")

        for app, model in list(default_perms.items()):
            for model, lst in list(model.items()):
                for pk in lst:
                    instance = get_model(app, model).objects.get(pk=pk)
                    assign_perm("add_records_to_%s" % model, ipam_user_group,
                                instance)

        self.stdout.write("Default Permissions added.")
Beispiel #20
0
    def handle(self, *args, **options):

        self.stdout.write('Converting DNS Type Permissions')

        dns_types = DnsType.objects.exclude(min_permissions__name='NONE')
        ipam_user_group = Group.objects.get(name=CONFIG.get('USER_GROUP'))

        for dns_type in dns_types:
            assign_perm('add_records_to_dnstype', ipam_user_group, dns_type)

            self.stdout.write('Permission for %s updated' % dns_type.name)
Beispiel #21
0
def page_error(request, template_name, extra_context=None):
    kitty_dir = (os.path.dirname(os.path.realpath(__file__)) +
                 "/static/core/img/error_cats")
    kitty = random.choice(os.listdir(kitty_dir))
    template = loader.get_template(template_name)
    error_type, error_value, traceback = sys.exc_info()
    context = {
        "request": request,
        "request_path": request.path,
        "kitty": kitty,
        "email": CONFIG.get("EMAIL_ADDRESS"),
        "legacy_domain": CONFIG.get("LEGACY_DOAMIN"),
        "error_type": error_type.__name__,
        "error_value": error_value,
        "traceback": traceback,
    }
    if extra_context:
        context.update(extra_context)
    body = template.render(context, request)
    return HttpResponseNotFound(body, content_type="text/html")
    def handle(self, *args, **options):

        self.stdout.write("Converting DNS Type Permissions")

        dns_types = DnsType.objects.exclude(min_permissions__name="NONE")
        ipam_user_group = Group.objects.get(name=CONFIG.get("USER_GROUP"))

        for dns_type in dns_types:
            assign_perm("add_records_to_dnstype", ipam_user_group, dns_type)

            self.stdout.write("Permission for %s updated" % dns_type.name)
    def handle(self, *args, **options):

        self.stdout.write("Adding default permissions to ipam-users group...")

        ipam_user_group, u_created = Group.objects.get_or_create(
            name=CONFIG.get("USER_GROUP")
        )
        ipam_admin_group, a_created = Group.objects.get_or_create(
            name=CONFIG.get("ADMIN_GROUP")
        )

        default_perms = CONFIG.get("DEFAULT_PERMISSIONS")

        for app, model in default_perms.items():
            for model, lst in model.items():
                for pk in lst:
                    instance = get_model(app, model).objects.get(pk=pk)
                    assign_perm("add_records_to_%s" % model, ipam_user_group, instance)

        self.stdout.write("Default Permissions added.")
Beispiel #24
0
def page_error(request, template_name, extra_context=None):
    kitty_dir = (
        os.path.dirname(os.path.realpath(__file__)) + "/static/core/img/error_cats"
    )
    kitty = random.choice(os.listdir(kitty_dir))
    template = loader.get_template(template_name)
    error_type, error_value, traceback = sys.exc_info()
    context = {
        "request": request,
        "request_path": request.path,
        "kitty": kitty,
        "email": CONFIG.get("EMAIL_ADDRESS"),
        "legacy_domain": CONFIG.get("LEGACY_DOAMIN"),
        "request_path": request.path,
        "error_type": error_type.__name__,
        "error_value": error_value,
        "traceback": traceback,
    }
    if extra_context:
        context.update(extra_context)
    body = template.render(context, request)
    return HttpResponseNotFound(body, content_type="text/html")
Beispiel #25
0
def assign_ipam_groups(sender, instance, created, **kwargs):
    # Nasty hack for django-guardian auto-created user
    if instance.id == settings.ANONYMOUS_USER_ID:
        return
    # Get user group
    ipam_user_group = Group.objects.get_or_create(name=CONFIG.get("USER_GROUP"))[0]
    # Check to make sure Admin Group exists
    # ipam_admin_group = Group.objects.get_or_create(name=settings.IPAM_ADMIN_GROUP)[0]

    # Get user groups
    user_groups = instance.groups.all()

    if ipam_user_group not in user_groups:
        instance.groups.add(ipam_user_group)
Beispiel #26
0
def logout(request, next_page=None, **kwargs):

    backend = request.session.get("_auth_user_backend", "").split(".")[-1]

    if CONFIG.get("CAS_LOGIN") and backend == "IPAMCASBackend":
        cas_logout(request, next_page, **kwargs)

        next_page = next_page or get_redirect_url(request)
        if settings.CAS_LOGOUT_COMPLETELY:
            protocol = get_protocol(request)
            host = request.get_host()
            redirect_url = urllib_parse.urlunparse(
                (protocol, host, next_page, "", "", "")
            )
            client = get_cas_client()
            client.server_url = settings.CAS_SERVER_URL[:-3]
            return HttpResponseRedirect(client.get_logout_url(redirect_url))
        else:
            # This is in most cases pointless if not CAS_RENEW is set. The user will
            # simply be logged in again on next request requiring authorization.
            return HttpResponseRedirect(next_page)
    else:
        next_page = "internal_login" if CONFIG.get("CAS_LOGIN") else "login"
        return auth_logout_view(request, next_page=next_page, **kwargs)
Beispiel #27
0
def assign_ipam_groups(sender, instance, created, **kwargs):
    # Nasty hack for django-guardian auto-created user
    if instance.id == settings.ANONYMOUS_USER_ID:
        return
    # Get user group
    ipam_user_group = Group.objects.get_or_create(
        name=CONFIG.get("USER_GROUP"))[0]
    # Check to make sure Admin Group exists
    # ipam_admin_group = Group.objects.get_or_create(name=settings.IPAM_ADMIN_GROUP)[0]

    # Get user groups
    user_groups = instance.groups.all()

    if ipam_user_group not in user_groups:
        instance.groups.add(ipam_user_group)
Beispiel #28
0
    def get_context_data(self, **kwargs):
        context = super(HostDetailView, self).get_context_data(**kwargs)
        attributes = []
        attributes += self.object.freeform_attributes.values_list('attribute__description', 'value')
        attributes += self.object.structured_attributes.values_list('structured_attribute_value__attribute__description',
                                                                    'structured_attribute_value__value')
        context['read_only'] = self.kwargs.get('read_only', False)
        context['attributes'] = attributes
        context['dns_records'] = self.object.get_dns_records()
        context['addresses'] = self.object.addresses.select_related().all()
        context['pools'] = self.object.pools.all()
        context['leased_addresses'] = self.object.leases.select_related('address', 'host').all()
        context['user_owners'], context['group_owners'] = self.object.get_owners()
        context['disabled_info'] = Disabled.objects.filter(pk=self.object.pk).first()
        context['disabled_website'] = CONFIG.get('DISABLED_HOSTS_WEBSITE')

        return context
Beispiel #29
0
def convert_min_permissions(user=None, username=None):
    user_qs = User.objects.all()
    if user:
        user_qs = user_qs.filter(pk=user.pk)
    elif username:
        user_qs = user_qs.filter(username__iexact=username)

    # Add admins to IPAM admins
    ipam_admin_group = AuthGroup.objects.get(name=CONFIG.get("ADMIN_GROUP"))
    users_ipam_admins = user_qs.filter(min_permissions__name="ADMIN")
    for user in users_ipam_admins:
        user.groups.add(ipam_admin_group)

    # Add DEITY users as super admins
    users_deity = user_qs.filter(min_permissions__name="DEITY")
    for user in users_deity:
        user.is_superadmin = True
        user.save()
Beispiel #30
0
    def get_context_data(self, **kwargs):
        context = super(HostDetailView, self).get_context_data(**kwargs)
        attributes = []
        attributes += self.object.freeform_attributes.values_list(
            "attribute__description", "value"
        )
        attributes += self.object.structured_attributes.values_list(
            "structured_attribute_value__attribute__description",
            "structured_attribute_value__value",
        )
        context["read_only"] = self.kwargs.get("read_only", False)
        context["attributes"] = attributes
        context["dns_records"] = self.object.get_dns_records()
        context["addresses"] = self.object.addresses.select_related().all()
        context["pools"] = self.object.pools.all()
        context["leased_addresses"] = self.object.leases.select_related(
            "address", "host"
        ).all()
        context["user_owners"], context["group_owners"] = self.object.get_owners()
        context["disabled_info"] = Disabled.objects.filter(pk=self.object.pk).first()
        context["disabled_website"] = CONFIG.get("DISABLED_HOSTS_WEBSITE")

        return context
Beispiel #31
0
    def process_request(self, request):
        assert hasattr(request, "user"), "The Duo Auth Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."

        duo_exempt_urls = [
            reverse("profile"),
            reverse("password_change"),
            reverse("password_change_done"),
            reverse("duo_auth"),
        ]

        if CONFIG.get("DUO_LOGIN"):
            if request.user.is_authenticated() and not request.session.get(
                    "duo_authenticated", False):
                path = request.path.lstrip("/")
                if not any(m.match(path) for m in EXEMPT_URLS):
                    if request.path not in duo_exempt_urls:
                        return redirect(
                            f"{reverse('duo_auth')}?next={request.path}")
Beispiel #32
0
def logout(request, next_page=None, **kwargs):

    # backend = request.session.get("_auth_user_backend", "").split(".")[-1]

    # if CONFIG.get("CAS_LOGIN") and backend == "IPAMCASBackend":
    #     cas_logout(request, next_page, **kwargs)

    #     next_page = next_page or get_redirect_url(request)
    #     if settings.CAS_LOGOUT_COMPLETELY:
    #         protocol = get_protocol(request)
    #         host = request.get_host()
    #         redirect_url = urllib_parse.urlunparse(
    #             (protocol, host, next_page, "", "", "")
    #         )
    #         client = get_cas_client()
    #         client.server_url = settings.CAS_SERVER_URL[:-3]
    #         return HttpResponseRedirect(client.get_logout_url(redirect_url))
    #     else:
    #         # This is in most cases pointless if not CAS_RENEW is set. The user will
    #         # simply be logged in again on next request requiring authorization.
    #         return HttpResponseRedirect(next_page)
    # else:
    next_page = "internal_login" if CONFIG.get("CAS_LOGIN") else "login"
    return auth_logout_view(request, next_page=next_page, **kwargs)
Beispiel #33
0
    def init_with_context(self, context):

        self.site_name = get_admin_site_name(context)
        request = context["request"]

        # append intro module
        self.children.append(
            HTMLContentModule(
                "<strong>Welcome to the openIPAM.</strong>",
                html="""
                    <div style="margin: 10px 20px;">
                        <p>
                            We are now using <a href="%(feature_request_link)s" target="_blank">Issues on GitHub</a> to help aid us with features and bugs.
                            Please make an issue on GitHub to give us feedback.
                        </p>
                        <p>Item to consider when using the new interface:</p>
                        <ul id="new-interface-list">
                            <li>Permissions - Do you have all your permissions?</li>
                            <li>Hosts - Do you see all your hosts?</li>
                            <li>DNS Entries - Do you see all DNS Entries?</li>
                        </ul>
                        <p>If you have any questions, please email:  <a href="mailto:%(email)s">%(email)s</a></p>
                    </div>
            """ % {
                    "email":
                    CONFIG.get("EMAIL_ADDRESS"),
                    "feature_request_link":
                    "https://github.com/openipam/django-openipam/issues/",
                },
            ))

        self.children.append(
            HTMLContentModule(
                "Navigation",
                html="""
                <ul>
                    <li><a href="%(url_hosts)s">List Hosts</a></li>
                    <li><a href="%(url_add_hosts)s">Add Host</a></li>
                    <li><a href="%(url_dns)s">DNS Records</a></li>
                </ul>
                <ul>
                    <li style="border-top: 1px solid #e5e5e5;">
                        <a href="%(url_feature_request)s">Feature or Bug?</a>
                    </li>
                    <li><a href="%(url_profile)s">Profile</a></li>
                </ul>
            """ % {
                    "url_hosts": reverse_lazy("list_hosts"),
                    "url_add_hosts": reverse_lazy("add_hosts"),
                    "url_dns": reverse_lazy("list_dns"),
                    "url_feature_request": reverse_lazy("feature_request"),
                    "url_profile": reverse_lazy("profile"),
                },
            ))

        if request.user.is_staff or request.user.is_superuser:
            # append an app list module for "Administration"
            self.children.append(IPAMAppList(_("Administration"), models=()))

        # append recent stats module
        hosts = Host.objects.all()
        hosts_stats = qsstats.QuerySetStats(hosts,
                                            "changed",
                                            aggregate=Count("mac"),
                                            today=datetime.now())
        users = User.objects.all()
        users_stats = qsstats.QuerySetStats(users,
                                            "date_joined",
                                            today=datetime.now())

        hosts_today = cache.get("hosts_today")
        hosts_week = cache.get("hosts_week")
        hosts_month = cache.get("hosts_month")

        if hosts_today is None:
            hosts_today = hosts_stats.this_day()
            cache.set("hosts_today", hosts_today)
        if hosts_week is None:
            hosts_week = hosts_stats.this_week()
            cache.set("hosts_week", hosts_week)
        if hosts_month is None:
            hosts_month = hosts_stats.this_month()
            cache.set("hosts_month", hosts_month)

        users_today = cache.get("users_today")
        users_week = cache.get("users_week")
        users_month = cache.get("users_month")

        if users_today is None:
            users_today = users_stats.this_day()
            cache.set("users_today", users_today)
        if users_week is None:
            users_week = users_stats.this_week()
            cache.set("users_week", users_week)
        if users_month is None:
            users_month = users_stats.this_month()
            cache.set("users_month", users_month)

        self.children.append(
            HTMLContentModule(
                "Recent Stats",
                html="""
                <div style="margin: 10px 20px;" class="well well-sm">
                    <h5>Hosts</h5>
                    <p><strong>%(hosts_today)s</strong> hosts changed today.</p>
                    <p><strong>%(hosts_week)s</strong> hosts changed this week.</p>
                    <p><strong>%(hosts_month)s</strong> hosts changed this month.</p>
                </div>
                <div style="margin: 10px 20px;" class="well well-sm">
                    <h5>Users</h5>
                    <p><strong>%(users_today)s</strong> users joined today.</p>
                    <p><strong>%(users_week)s</strong> users joined this week.</p>
                    <p><strong>%(users_month)s</strong> users joined this month.</p>
                </div>
            """ % {
                    "hosts_today": hosts_today,
                    "hosts_week": hosts_week,
                    "hosts_month": hosts_month,
                    "users_today": users_today,
                    "users_week": users_week,
                    "users_month": users_month,
                },
            ))

        # append a recent actions module
        self.children.append(
            modules.RecentActions(_("Recent Actions"), limit=5))
Beispiel #34
0
    def post(self, request, format=None, **kwargs):
        serializer = GuestRegisterSerializer(data=request.data)

        if serializer.is_valid():
            lock_id = "ipam-guest-register"

            with advisory_lock(lock_id):
                hostname_prefix = CONFIG.get("GUEST_HOSTNAME_FORMAT")[0]
                hostname_suffix = CONFIG.get("GUEST_HOSTNAME_FORMAT")[1]
                last_hostname = (
                    Host.objects.filter(
                        hostname__istartswith=hostname_prefix,
                        hostname__iendswith=hostname_suffix,
                    )
                    .extra(select={"hostname_length": "length(hostname)"})
                    .order_by("-hostname_length", "-hostname")
                    .first()
                )
                hostname_index = int(
                    last_hostname.hostname[
                        len(hostname_prefix) : last_hostname.hostname.find(
                            hostname_suffix
                        )
                    ]
                )
                guest_user = User.objects.get(username__iexact=CONFIG.get("GUEST_USER"))
                user_owner = serializer.valid_ticket.user
                description = serializer.data.get("description")
                name = serializer.data.get("name")
                ticket = serializer.data.get("ticket")
                mac_address = serializer.data.get("mac_address")

                try:
                    hostname = "%s%s%s" % (
                        hostname_prefix,
                        hostname_index + 1,
                        hostname_suffix,
                    )

                    # Check if instance already created.  Bug in DHCP thats registering it twice??
                    instance = Host.objects.filter(
                        hostname=hostname, mac=mac_address
                    ).first()

                    # Add or update host
                    Host.objects.add_or_update_host(
                        user=guest_user,
                        hostname=hostname,
                        mac=mac_address,
                        expires=serializer.valid_ticket.ends,
                        description=description
                        if description
                        else "Name: %s; Ticket used: %s" % (name, ticket),
                        pool=Pool.objects.get(name=CONFIG.get("GUEST_POOL")),
                        user_owners=[user_owner],
                        group_owners=[CONFIG.get("GUEST_GROUP")],
                        instance=instance or None,
                    )
                except ValidationError as e:
                    error_list = []
                    if hasattr(e, "error_dict"):
                        for key, errors in e.message_dict.items():
                            for error in errors:
                                error_list.append(error)
                    else:
                        error_list.append(e.message)
                    return Response(
                        {"non_field_errors": error_list},
                        status=status.HTTP_400_BAD_REQUEST,
                    )

            data = {
                "starts": serializer.valid_ticket.starts,
                "ends": serializer.valid_ticket.ends,
            }
            data.update(serializer.data)

            return Response(data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #35
0
 def has_permission(self, request, view):
     guests_enabled = CONFIG.get("GUESTS_ENABLED", False)
     return guests_enabled
Beispiel #36
0
    def post(self, request, format=None, **kwargs):
        serializer = GuestRegisterSerializer(data=request.data)

        if serializer.is_valid():
            lock_id = "ipam-guest-register"

            with advisory_lock(lock_id):
                hostname_prefix = CONFIG.get("GUEST_HOSTNAME_FORMAT")[0]
                hostname_suffix = CONFIG.get("GUEST_HOSTNAME_FORMAT")[1]
                last_hostname = (Host.objects.filter(
                    hostname__istartswith=hostname_prefix,
                    hostname__iendswith=hostname_suffix,
                ).extra(select={
                    "hostname_length": "length(hostname)"
                }).order_by("-hostname_length", "-hostname").first())
                hostname_index = int(
                    last_hostname.hostname[len(hostname_prefix):last_hostname.
                                           hostname.find(hostname_suffix)])
                guest_user = User.objects.get(
                    username__iexact=CONFIG.get("GUEST_USER"))
                user_owner = serializer.valid_ticket.user
                description = serializer.data.get("description")
                name = serializer.data.get("name")
                ticket = serializer.data.get("ticket")
                mac_address = serializer.data.get("mac_address")

                try:
                    hostname = "%s%s%s" % (
                        hostname_prefix,
                        hostname_index + 1,
                        hostname_suffix,
                    )

                    # Check if instance already created.  Bug in DHCP thats registering it twice??
                    instance = Host.objects.filter(hostname=hostname,
                                                   mac=mac_address).first()

                    # Add or update host
                    Host.objects.add_or_update_host(
                        user=guest_user,
                        hostname=hostname,
                        mac=mac_address,
                        expires=serializer.valid_ticket.ends,
                        description=description if description else
                        "Name: %s; Ticket used: %s" % (name, ticket),
                        pool=Pool.objects.get(name=CONFIG.get("GUEST_POOL")),
                        user_owners=[user_owner],
                        group_owners=[CONFIG.get("GUEST_GROUP")],
                        instance=instance or None,
                    )
                except ValidationError as e:
                    error_list = []
                    if hasattr(e, "error_dict"):
                        for key, errors in list(e.message_dict.items()):
                            for error in errors:
                                error_list.append(error)
                    else:
                        error_list.append(e.message)
                    return Response(
                        {"non_field_errors": error_list},
                        status=status.HTTP_400_BAD_REQUEST,
                    )

            data = {
                "starts": serializer.valid_ticket.starts,
                "ends": serializer.valid_ticket.ends,
            }
            data.update(serializer.data)

            return Response(data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #37
0
    def init_with_context(self, context):
        """
        Use this method if you need to access the request context.
        """

        user = context["request"].user
        admin_sites = admin.site._registry
        hosts_models = filter(
            lambda x: x.__module__ == "openipam.hosts.models", admin_sites
        )
        hosts_models = tuple(
            sorted(
                ["%s.%s" % (model.__module__, model.__name__) for model in hosts_models]
            )
        )

        dns_models = filter(
            lambda x: x.__module__ == "openipam.dns.models", admin_sites
        )
        dns_models = tuple(
            sorted(
                ["%s.%s" % (model.__module__, model.__name__) for model in dns_models]
            )
        )

        network_models = filter(
            lambda x: x.__module__ == "openipam.network.models", admin_sites
        )
        network_models = tuple(
            sorted(
                [
                    "%s.%s" % (model.__module__, model.__name__)
                    for model in network_models
                ]
            )
        )

        if user.is_superuser:
            core_menus = [
                items.ModelList("Hosts", hosts_models),
                items.ModelList("DNS", dns_models),
            ]
        elif user.is_staff:
            host_models = items.ModelList("", ["openipam.hosts.*"])
            dns_models = items.ModelList("", ["openipam.dns.*"])

            host_items = items.MenuItem("Hosts", url=reverse("list_hosts"))
            dns_items = items.MenuItem("DNS", url=reverse("list_dns"))

            if len(dns_models._visible_models(context["request"])) > 1:
                dns_items.children = [
                    items.MenuItem("DNS", url=reverse("list_dns")),
                    items.ModelList(
                        "",
                        ["openipam.dns.*"],
                        exclude=("openipam.dns.models.DnsRecord",),
                    ),
                ]

            if len(host_models._visible_models(context["request"])) > 1:
                host_items.children = [
                    items.MenuItem("Hosts", url=reverse("list_hosts")),
                    items.ModelList(
                        "",
                        models=["openipam.hosts.*"],
                        exclude=("openipam.hosts.models.Host",),
                    ),
                ]

            core_menus = [host_items, dns_items]
        else:
            core_menus = [
                items.MenuItem("Hosts", url=reverse("list_hosts")),
                items.MenuItem("DNS", url=reverse("list_dns")),
            ]

        self.children += [
            items.MenuItem(
                _("Home"),
                reverse("admin:index"),
                icon="glyphicon glyphicon-home icon-white",
            )
        ]

        self.children += core_menus
        self.children.append(items.ModelList("Network", network_models))

        if user.is_superuser:
            self.children.append(
                items.MenuItem(
                    "Admin",
                    children=[
                        items.ModelList(
                            "Users & Groups",
                            [
                                "openipam.user.models.User",
                                "django.contrib.auth.models.Group",
                                "rest_framework.authtoken.models.Token",
                            ],
                        ),
                        items.ModelList(
                            "Permissions",
                            [
                                "django.contrib.auth.models.Permission",
                                "guardian.models.UserObjectPermission",
                                "guardian.models.GroupObjectPermission",
                                "taggit.models.Tag",
                            ],
                        ),
                        items.ModelList(
                            "Logs",
                            [
                                "django.contrib.admin.models.LogEntry",
                                "openipam.log.models.HostLog",
                                "openipam.log.models.EmailLog",
                                "openipam.log.models.DnsRecordsLog",
                                "openipam.log.models.AddressLog",
                                "openipam.log.models.UserLog",
                            ],
                        ),
                        items.ModelList(
                            "Feature Requests", ["openipam.core.models.FeatureRequest"]
                        ),
                    ],
                    # icon='icon-user icon-white'
                )
            )

        elif user.is_staff:
            user_apps = items.AppList(
                "", exclude=("openipam.hosts.*", "openipam.dns.*")
            )
            user_apps.init_with_context(context)

            if user_apps.children:
                self.children.append(
                    items.MenuItem(
                        "Admin",
                        children=[
                            items.AppList(
                                "", exclude=("openipam.hosts.*", "openipam.dns.*")
                            )
                        ],
                    )
                )

        if user.is_ipamadmin or user.groups.filter(
            name=CONFIG.get("REPORT_USER_GROUP")
        ):
            self.children.append(
                IPAMMenuItem("Reports", url=reverse("reports_dashboard"))
            )

        return super(IPAMMenu, self).init_with_context(context)
Beispiel #38
0
def buildingmap_config(request):
    data = copy.deepcopy(CONFIG.get('BUILDINGMAP_DATA').get('config'))

    return Response(data)
    def handle(self, *args, **options):
        test = options["test"]
        count = options["count"]
        noasync = options["noasync"]
        connection = None
        if test:
            connection = get_connection(
                backend="django.core.mail.backends.console.EmailBackend"
            )

        self.stdout.write("Sending Notifications...")

        from_address = CONFIG.get("NOTIFICATION_EMAIL_ADDRESS")

        dynamic_subject = (
            "[USU:Important] Your USU device registrations are about to expire"
        )
        dynamic_msg = """%(name)s (%(username)s),

The following device registrations are going to expire soon.

If you would like to continue using the USU network for another year:

1. If you are on the USU network, you can log in at https://bluezone.usu.edu/ . However, if you are
   not on the USU network you must first connect your device to the network using VPN
   and then go to https://bluezone.usu.edu/ and login.
2. Click "Renew" next to the following devices:

%(rows)s

Instructions on using the VPN server may be found at http://it.usu.edu/vpn.

If you have any questions, please contact the IT Service Desk.

Remember: never give your password to anyone, including USU employees.

--
IT Service Desk

Fall & Spring Hours
Mon-Thurs: 8:00am-8:00pm
Friday: 8:00am-6:00pm
Saturday: 10:00am-3:00pm

Summer Hours
Mon-Fri: 8:00am-6:00pm
Saturday: Closed

Contact us at:
Phone: 797-HELP (4357)
Toll Free: 877-878-8325
Email: [email protected]
http://usu.service-now.com (Issue Tracking System)


        """

        static_subject = "[USU:Important] openIPAM Host Renewal Notice"
        static_msg = """%(name)s (%(username)s),

The following device registrations are going to expire soon.

To renew your servers and clients for another year:

1. If you are on the USU network, you can log in at https://openipam.usu.edu/ . However, if you are
   not on the USU network you must first connect your device to the network using VPN
   and then go to https://openipam.usu.edu/ and login.
2. Click on the "Hosts" tab in the upper left to view hosts.
3. Click "Show Mine" to view your hosts.  You can sort your hosts by expiration date if you wish.
4. Check the boxes next to those hosts you wish to renew.
5. Select the "Choose an action" drop down and then select "Renew selected hosts" followed by the "Go" button.

Instructions on using the VPN server may be found at http://it.usu.edu/vpn.

Remember: help us keep up-to-date data. Don't renew hosts you don't need.

%(rows)s

If you have any questions, please contact the IT Service Desk.

--
IT Service Desk

Fall & Spring Hours
Mon-Thurs: 8:00am-8:00pm
Friday: 8:00am-6:00pm
Saturday: 10:00am-3:00pm

Summer Hours
Mon-Fri: 8:00am-6:00pm
Saturday: Closed

Contact us at:
Phone: 797-HELP (4357)
Toll Free: 877-878-8325
Email: [email protected]
http://usu.service-now.com (Issue Tracking System)


        """

        row_heading = "Hostname:                                MAC:                  Expiring in:   Description:"
        row_fmt = "%(hostname)-40s %(mac)-22s %(days)3s days      %(description)s"

        # Get list of people who need to be notified.
        host_qs = Host.objects.prefetch_related("pools").by_expiring(omit_guests=True)

        users_to_notify = {}
        messages = []
        bad_users = []

        for host in host_qs:
            host_users = host.get_owners(users_only=True)

            for user in host_users:
                if user not in users_to_notify:
                    users_to_notify[user] = {"static": [], "dynamic": []}
                if host.is_static:
                    users_to_notify[user]["static"].append(host)
                else:
                    users_to_notify[user]["dynamic"].append(host)

        for user, host_types in users_to_notify.items():
            if not user.email:
                e_user = populate_user_from_ldap(user=user)
            else:
                e_user = user
            if e_user and e_user.email:
                mesg_type = "static" if host_types.get("static") else "dynamic"
                row_hosts = []
                for host_type, hosts in host_types.items():
                    for host in hosts:
                        row_hosts.append(
                            row_fmt
                            % {
                                "hostname": host.hostname,
                                "mac": host.mac,
                                "days": host.expire_days,
                                "description": host.description,
                            }
                        )
                messages.append(
                    (
                        locals()["%s_subject" % mesg_type],
                        locals()["%s_msg" % mesg_type]
                        % {
                            "name": e_user.get_full_name(),
                            "username": e_user.username,
                            "rows": "%s\n%s" % (row_heading, "\n".join(row_hosts)),
                        },
                        from_address,
                        [e_user.email],
                    )
                )
            else:
                bad_users.append(user.username)

        if not count:
            if noasync:
                for message in messages:
                    self.stdout.write("Sending email to %s..." % ",".join(message[3]))
                    send_mail(*message, fail_silently=False, connection=connection)
            else:
                send_mass_mail(messages, fail_silently=False, connection=connection)

            if not test:
                host_qs.update(last_notified=timezone.now())

        self.stdout.write(
            "%s Notifications have been sent for %s hosts"
            % (len(messages), len(host_qs))
        )
        self.stdout.write("%s users have no email address." % len(bad_users))
        self.stdout.write("\n".join(bad_users))
Beispiel #40
0
 def get_context_data(self, **kwargs):
     context = super(HostUpdateView, self).get_context_data(**kwargs)
     context["disabled_info"] = Disabled.objects.filter(pk=self.object.pk).first()
     context["disabled_website"] = CONFIG.get("DISABLED_HOSTS_WEBSITE")
     return context
Beispiel #41
0
    def init_with_context(self, context):
        """
        Use this method if you need to access the request context.
        """

        user = context['request'].user
        admin_sites = admin.site._registry
        hosts_models = filter(lambda x: x.__module__ == 'openipam.hosts.models', admin_sites)
        hosts_models = tuple(sorted(['%s.%s' % (model.__module__, model.__name__) for model in hosts_models]))

        dns_models = filter(lambda x: x.__module__ == 'openipam.dns.models', admin_sites)
        dns_models = tuple(sorted(['%s.%s' % (model.__module__, model.__name__) for model in dns_models]))

        network_models = filter(lambda x: x.__module__ == 'openipam.network.models', admin_sites)
        network_models = tuple(sorted(['%s.%s' % (model.__module__, model.__name__) for model in network_models]))

        if user.is_superuser:
            core_menus = [
                items.ModelList('Hosts', hosts_models),
                items.ModelList('DNS', dns_models),
            ]
        elif user.is_staff:
            host_models = items.ModelList('', ['openipam.hosts.*'])
            dns_models = items.ModelList('', ['openipam.dns.*'])

            host_items = items.MenuItem('Hosts', url=reverse('list_hosts'))
            dns_items = items.MenuItem('DNS', url=reverse('list_dns'))

            if len(dns_models._visible_models(context['request'])) > 1:
                dns_items.children = [
                    items.MenuItem('DNS', url=reverse('list_dns')),
                    items.ModelList('', ['openipam.dns.*'], exclude=('openipam.dns.models.DnsRecord',)),
                ]

            if len(host_models._visible_models(context['request'])) > 1:
                host_items.children = [
                    items.MenuItem('Hosts', url=reverse('list_hosts')),
                    items.ModelList('', models=['openipam.hosts.*'], exclude=('openipam.hosts.models.Host',)),
                ]

            core_menus = [
                host_items,
                dns_items,
            ]
        else:
            core_menus = [
                items.MenuItem('Hosts', url=reverse('list_hosts')),
                items.MenuItem('DNS', url=reverse('list_dns')),
            ]

        self.children += [
            items.MenuItem(
                _('Home'),
                reverse('admin:index'),
                icon='glyphicon glyphicon-home icon-white'
            ),
        ]

        self.children += core_menus
        self.children.append(items.ModelList('Network', network_models))

        if user.is_superuser:
            self.children.append(
                items.MenuItem('Admin',
                    children=[
                        items.ModelList('Users & Groups',
                            [
                                'openipam.user.models.User',
                                'django.contrib.auth.models.Group',
                                'rest_framework.authtoken.models.Token',
                            ]
                        ),
                        items.ModelList('Permissions',
                            [
                                'django.contrib.auth.models.Permission',
                                'guardian.models.UserObjectPermission',
                                'guardian.models.GroupObjectPermission',
                                'taggit.models.Tag',
                            ]
                        ),
                        items.ModelList('Logs',
                            [
                                'django.contrib.admin.models.LogEntry',
                                'openipam.log.models.HostLog',
                                'openipam.log.models.EmailLog'
                            ]
                        ),
                        items.ModelList('Feature Requests',
                            [
                                'openipam.core.models.FeatureRequest'
                            ]
                        ),
                    ],
                    #icon='icon-user icon-white'
                )
            )

        elif user.is_staff:
            user_apps = items.AppList(
                '',
                exclude=(
                    'openipam.hosts.*',
                    'openipam.dns.*',
                )
            )
            user_apps.init_with_context(context)

            if user_apps.children:
                self.children.append(
                    items.MenuItem('Admin',
                        children=[
                            items.AppList(
                                '',
                                exclude=(
                                    'openipam.hosts.*',
                                    'openipam.dns.*',
                                )
                            )
                        ]
                    )
                )

        if user.is_ipamadmin or user.groups.filter(name=CONFIG.get('REPORT_USER_GROUP')):
            self.children.append(
                IPAMMenuItem('Reports', url=reverse('reports_dashboard'))
            )

        return super(IPAMMenu, self).init_with_context(context)
Beispiel #42
0
 def get_context_data(self, **kwargs):
     context = super(HostUpdateView, self).get_context_data(**kwargs)
     context["disabled_info"] = Disabled.objects.filter(
         pk=self.object.pk).first()
     context["disabled_website"] = CONFIG.get("DISABLED_HOSTS_WEBSITE")
     return context
Beispiel #43
0
    def init_with_context(self, context):
        """
        Use this method if you need to access the request context.
        """

        user = context["request"].user
        admin_sites = admin.site._registry
        hosts_models = [
            x for x in admin_sites if x.__module__ == "openipam.hosts.models"
        ]
        hosts_models = tuple(
            sorted([
                "%s.%s" % (model.__module__, model.__name__)
                for model in hosts_models
            ]))

        dns_models = [
            x for x in admin_sites if x.__module__ == "openipam.dns.models"
        ]
        dns_models = tuple(
            sorted([
                "%s.%s" % (model.__module__, model.__name__)
                for model in dns_models
            ]))

        network_models = [
            x for x in admin_sites if x.__module__ == "openipam.network.models"
        ]
        network_models = tuple(
            sorted([
                "%s.%s" % (model.__module__, model.__name__)
                for model in network_models
            ]))

        if user.is_superuser:
            core_menus = [
                items.ModelList("Hosts", hosts_models),
                items.ModelList("DNS", dns_models),
            ]
        elif user.is_staff:
            host_models = items.ModelList("", ["openipam.hosts.*"])
            dns_models = items.ModelList("", ["openipam.dns.*"])

            host_items = items.MenuItem("Hosts", url=reverse("list_hosts"))
            dns_items = items.MenuItem("DNS", url=reverse("list_dns"))

            if len(dns_models._visible_models(context["request"])) > 1:
                dns_items.children = [
                    items.MenuItem("DNS", url=reverse("list_dns")),
                    items.ModelList(
                        "",
                        ["openipam.dns.*"],
                        exclude=("openipam.dns.models.DnsRecord", ),
                    ),
                ]

            if len(host_models._visible_models(context["request"])) > 1:
                host_items.children = [
                    items.MenuItem("Hosts", url=reverse("list_hosts")),
                    items.ModelList(
                        "",
                        models=["openipam.hosts.*"],
                        exclude=("openipam.hosts.models.Host", ),
                    ),
                ]

            core_menus = [host_items, dns_items]
        else:
            core_menus = [
                items.MenuItem("Hosts", url=reverse("list_hosts")),
                items.MenuItem("DNS", url=reverse("list_dns")),
            ]

        self.children += [
            items.MenuItem(
                _("Home"),
                reverse("admin:index"),
                icon="glyphicon glyphicon-home icon-white",
            )
        ]

        self.children += core_menus
        self.children.append(items.ModelList("Network", network_models))

        if user.is_superuser:
            self.children.append(
                items.MenuItem(
                    "Admin",
                    children=[
                        items.ModelList(
                            "Users & Groups",
                            [
                                "openipam.user.models.User",
                                "django.contrib.auth.models.Group",
                                "rest_framework.authtoken.models.Token",
                            ],
                        ),
                        items.ModelList(
                            "Permissions",
                            [
                                "django.contrib.auth.models.Permission",
                                "guardian.models.UserObjectPermission",
                                "guardian.models.GroupObjectPermission",
                                "taggit.models.Tag",
                            ],
                        ),
                        items.ModelList(
                            "Logs",
                            [
                                "django.contrib.admin.models.LogEntry",
                                "openipam.log.models.HostLog",
                                "openipam.log.models.EmailLog",
                                "openipam.log.models.DnsRecordsLog",
                                "openipam.log.models.AddressLog",
                                "openipam.log.models.UserLog",
                            ],
                        ),
                        items.ModelList(
                            "Feature Requests",
                            ["openipam.core.models.FeatureRequest"]),
                    ],
                    # icon='icon-user icon-white'
                ))

        elif user.is_staff:
            user_apps = items.AppList("",
                                      exclude=("openipam.hosts.*",
                                               "openipam.dns.*"))
            user_apps.init_with_context(context)

            # if user.has_perm("user.view_user"):
            #     self.children.append(
            #         items.MenuItem("User Manager", url=reverse("user_manager"))
            #     )

            if user_apps.children:
                self.children.append(
                    items.MenuItem(
                        "Admin",
                        children=[
                            items.AppList("",
                                          exclude=("openipam.hosts.*",
                                                   "openipam.dns.*"))
                        ],
                    ))

        if user.is_ipamadmin or user.groups.filter(
                name=CONFIG.get("REPORT_USER_GROUP")):
            self.children.append(
                IPAMMenuItem("Reports", url=reverse("reports_dashboard")))

        return super(IPAMMenu, self).init_with_context(context)
Beispiel #44
0
def weathermap_config(request):
    data = copy.deepcopy(CONFIG.get("WEATHERMAP_DATA").get("config"))

    return Response(data)
Beispiel #45
0
    def init_with_context(self, context):

        site_name = get_admin_site_name(context)
        request = context['request']

        #append an app list module for "IPAM"
        # self.children.append(modules.ModelList(
        #     _('Hosts'),
        #     models=(
        #         'openipam.hosts.*',
        #     ),
        # ))

        #self.children.append(modules.ModelList(
        #    _('Network'),
        #     models=(
        #         'openipam.network.*',
        #     ),
        # ))

        # self.children.append(modules.ModelList(
        #     _('Domains & DNS'),
        #     models=(
        #         'openipam.dns.*',
        #     ),
        # ))

        # append intro module
        self.children.append(HTMLContentModule(
            '<strong>Welcome to the openIPAM.</strong>',
            html='''
                    <div style="margin: 10px 20px;">
                        <p>
                            We have provided a <a href="%(feature_request_link)s">feature and bug submission tool</a> to help aid us with features and bugs.
                            Please use this tool whenever possible as it will give us great feedback.
                        </p>
                        <p>Item to consider when using the new interface:</p>
                        <ul id="new-interface-list">
                            <li>Permissions - Do you have all your permissions?</li>
                            <li>Hosts - Do you see all your hosts?</li>
                            <li>DNS Entries - Do you see all DNS Entries?</li>
                        </ul>
                        <p>If you have any questions, please email:  <a href="mailto:%(email)s">%(email)s</a></p>
                    </div>
            ''' % {
                'email': CONFIG.get('EMAIL_ADDRESS'),
                'legacy_domain': CONFIG.get('LEGACY_DOMAIN'),
                'feature_request_link': reverse_lazy('feature_request')
            }
        ))

        self.children.append(HTMLContentModule(
            'Navigation',
            html='''
                <ul>
                    <li><a href="%(url_hosts)s">List Hosts</a></li>
                    <li><a href="%(url_add_hosts)s">Add Host</a></li>
                    <li><a href="%(url_dns)s">DNS Records</a></li>
                </ul>
                <ul>
                    <li style="border-top: 1px solid #e5e5e5;">
                        <a href="%(url_feature_request)s">Feature or Bug?</a>
                    </li>
                    <li><a href="%(url_profile)s">Profile</a></li>
                </ul>
            ''' % {
                'url_hosts': reverse_lazy('list_hosts'),
                'url_add_hosts': reverse_lazy('add_hosts'),
                'url_dns': reverse_lazy('list_dns'),
                'url_feature_request': reverse_lazy('feature_request'),
                'url_profile': reverse_lazy('profile'),
            }
        ))


        if request.user.is_staff or request.user.is_superuser:
            # append an app list module for "Administration"
            self.children.append(IPAMAppList(
                _('Administration'),
                models=(),
            ))

        # if request.user.is_superuser:
        #     # append crap to delete.
        #     self.children.append(modules.AppList(
        #         _('TO BE DELETED'),
        #         models=(
        #             'openipam.user.models.Permission',
        #             'openipam.user.models.Group',
        #             'openipam.user.models.UserToGroup',
        #             'openipam.user.models.HostToGroup',
        #             'openipam.user.models.DomainToGroup',
        #             'openipam.user.models.NetworkToGroup',
        #             'openipam.user.models.PoolToGroup',
        #         ),
        #     ))

        # append recent stats module
        hosts = Host.objects.all()
        hosts_stats = qsstats.QuerySetStats(hosts, 'changed', aggregate=Count('mac'), today=datetime.now())
        users = User.objects.all()
        users_stats = qsstats.QuerySetStats(users, 'date_joined', today=datetime.now())

        hosts_today = cache.get('hosts_today')
        hosts_week = cache.get('hosts_week')
        hosts_month = cache.get('hosts_month')

        if hosts_today is None:
            hosts_today = hosts_stats.this_day()
            cache.set('hosts_today', hosts_today)
        if hosts_week is None:
            hosts_week = hosts_stats.this_week()
            cache.set('hosts_week', hosts_week)
        if hosts_month is None:
            hosts_month = hosts_stats.this_month()
            cache.set('hosts_month', hosts_month)

        users_today = cache.get('users_today')
        users_week = cache.get('users_week')
        users_month = cache.get('users_month')

        if users_today is None:
            users_today = users_stats.this_day()
            cache.set('users_today', users_today)
        if users_week is None:
            users_week = users_stats.this_week()
            cache.set('users_week', users_week)
        if users_month is None:
            users_month = users_stats.this_month()
            cache.set('users_month', users_month)

        self.children.append(HTMLContentModule(
            'Recent Stats',
            html='''
                <div style="margin: 10px 20px;" class="well well-sm">
                    <h5>Hosts</h5>
                    <p><strong>%(hosts_today)s</strong> hosts changed today.</p>
                    <p><strong>%(hosts_week)s</strong> hosts changed this week.</p>
                    <p><strong>%(hosts_month)s</strong> hosts changed this month.</p>
                </div>
                <div style="margin: 10px 20px;" class="well well-sm">
                    <h5>Users</h5>
                    <p><strong>%(users_today)s</strong> users joined today.</p>
                    <p><strong>%(users_week)s</strong> users joined this week.</p>
                    <p><strong>%(users_month)s</strong> users joined this month.</p>
                </div>
            ''' % {
                'hosts_today': hosts_today,
                'hosts_week': hosts_week,
                'hosts_month': hosts_month,
                'users_today': users_today,
                'users_week': users_week,
                'users_month': users_month,
            }
        ))

        # append a recent actions module
        self.children.append(modules.RecentActions(
            _('Recent Actions'),
            limit=5,

        ))
Beispiel #46
0
 def has_permission(self, request, view):
     guests_enabled = CONFIG.get("GUESTS_ENABLED", False)
     return guests_enabled
Beispiel #47
0
def weathermap_config(request):
    data = copy.deepcopy(CONFIG.get('WEATHERMAP_DATA').get('config'))

    return Response(data)
    def handle(self, *args, **options):
        test = options["test"]
        count = options["count"]
        noasync = options["noasync"]
        connection = None
        if test:
            connection = get_connection(
                backend="django.core.mail.backends.console.EmailBackend"
            )

        self.stdout.write("Sending Notifications...")

        from_address = CONFIG.get("NOTIFICATION_EMAIL_ADDRESS")

        dynamic_subject = (
            "[USU:Important] Your USU device registrations are about to expire"
        )
        dynamic_msg = """%(name)s (%(username)s),

The following device registrations are going to expire soon.

If you would like to continue using the USU network for another year:

1. If you are on the USU network, you can log in at https://bluezone.usu.edu/ . However, if you are
   not on the USU network you must first connect your device to the network using VPN
   and then go to https://bluezone.usu.edu/ and login.
2. Click "Renew" next to the following devices:

%(rows)s

Instructions on using the VPN server may be found at http://it.usu.edu/vpn.

If you have any questions, please contact the IT Service Desk.

Remember: never give your password to anyone, including USU employees.

--
IT Service Desk

Fall & Spring Hours
Mon-Thurs: 8:00am-8:00pm
Friday: 8:00am-6:00pm
Saturday: 10:00am-3:00pm

Summer Hours
Mon-Fri: 8:00am-6:00pm
Saturday: Closed

Contact us at:
Phone: 797-HELP (4357)
Toll Free: 877-878-8325
Email: [email protected]
http://usu.service-now.com (Issue Tracking System)


        """

        static_subject = "[USU:Important] openIPAM Host Renewal Notice"
        static_msg = """%(name)s (%(username)s),

The following device registrations are going to expire soon.

To renew your servers and clients for another year:

1. If you are on the USU network, you can log in at https://openipam.usu.edu/ . However, if you are
   not on the USU network you must first connect your device to the network using VPN
   and then go to https://openipam.usu.edu/ and login.
2. Click on the "Hosts" tab in the upper left to view hosts.
3. Click "Show Mine" to view your hosts.  You can sort your hosts by expiration date if you wish.
4. Check the boxes next to those hosts you wish to renew.
5. Select the "Choose an action" drop down and then select "Renew selected hosts" followed by the "Go" button.

Instructions on using the VPN server may be found at http://it.usu.edu/vpn.

Remember: help us keep up-to-date data. Don't renew hosts you don't need.

%(rows)s

If you have any questions, please contact the IT Service Desk.

--
IT Service Desk

Fall & Spring Hours
Mon-Thurs: 8:00am-8:00pm
Friday: 8:00am-6:00pm
Saturday: 10:00am-3:00pm

Summer Hours
Mon-Fri: 8:00am-6:00pm
Saturday: Closed

Contact us at:
Phone: 797-HELP (4357)
Toll Free: 877-878-8325
Email: [email protected]
http://usu.service-now.com (Issue Tracking System)


        """

        row_heading = "Hostname:                                MAC:                  Expiring in:   Description:"
        row_fmt = "%(hostname)-40s %(mac)-22s %(days)3s days      %(description)s"

        # Get list of people who need to be notified.
        host_qs = Host.objects.prefetch_related("pools").by_expiring(omit_guests=True)

        users_to_notify = {}
        messages = []
        bad_users = []

        for host in host_qs:
            host_users = host.get_owners(users_only=True)

            for user in host_users:
                if user not in users_to_notify:
                    users_to_notify[user] = {"static": [], "dynamic": []}
                if host.is_static:
                    users_to_notify[user]["static"].append(host)
                else:
                    users_to_notify[user]["dynamic"].append(host)

        for user, host_types in list(users_to_notify.items()):
            if not user.email:
                e_user = populate_user_from_ldap(user=user)
            else:
                e_user = user
            if e_user and e_user.email:
                mesg_type = "static" if host_types.get("static") else "dynamic"
                row_hosts = []
                for host_type, hosts in list(host_types.items()):
                    for host in hosts:
                        row_hosts.append(
                            row_fmt
                            % {
                                "hostname": host.hostname,
                                "mac": host.mac,
                                "days": host.expire_days,
                                "description": host.description,
                            }
                        )
                messages.append(
                    (
                        locals()["%s_subject" % mesg_type],
                        locals()["%s_msg" % mesg_type]
                        % {
                            "name": e_user.get_full_name(),
                            "username": e_user.username,
                            "rows": "%s\n%s" % (row_heading, "\n".join(row_hosts)),
                        },
                        from_address,
                        [e_user.email],
                    )
                )
            else:
                bad_users.append(user.username)

        if not count:
            if noasync:
                for message in messages:
                    self.stdout.write("Sending email to %s..." % ",".join(message[3]))
                    send_mail(*message, fail_silently=False, connection=connection)
            else:
                send_mass_mail(messages, fail_silently=False, connection=connection)

            if not test:
                host_qs.update(last_notified=timezone.now())

        self.stdout.write(
            "%s Notifications have been sent for %s hosts"
            % (len(messages), len(host_qs))
        )
        self.stdout.write("%s users have no email address." % len(bad_users))
        self.stdout.write("\n".join(bad_users))