Esempio n. 1
0
    def test_caching_of_values(self):
        """Test that caching of values for authenticate users."""
        session_mock = MagicMock()
        session_dict = {}
        session_mock.__setitem__.side_effect = session_dict.__setitem__
        session_mock.__getitem__.side_effect = session_dict.__getitem__
        session_mock.__contains__.side_effect = session_dict.__contains__
        self.request.session = session_mock

        mock = Mock(return_value=False)
        self.request.user.groups.filter().exists = mock
        self.assertFalse(is_user_admin(self.request))
        mock.assert_called_once_with()
        session_mock.__setitem__.assert_called_once_with(
            'cache_user_is_admin', False)

        mock = Mock(return_value=False)
        self.request.user.groups.filter().exists = mock
        self.assertFalse(is_user_admin(self.request, cached=True))
        mock.assert_not_called()
        session_mock.__getitem__.assert_called_once_with(
            'cache_user_is_admin')

        mock = Mock(return_value=False)
        self.request.user.groups.filter().exists = mock
        self.assertFalse(is_user_admin(self.request, cached=False))
        mock.assert_called_once_with()
        session_mock.__getitem__.assert_called_once_with(
            'cache_user_is_admin')
Esempio n. 2
0
 def test_is_false_for_anonymous_user(self):
     """Test anonymous user is reported as non-admin."""
     super(TestIsAdminUser, self).setUp()
     self.request.user = Mock()
     self.request.user.is_authenticated.return_value = False
     self.assertFalse(is_user_admin(self.request))
     self.assertFalse(is_user_admin(self.request, cached=True))
Esempio n. 3
0
    def test_caching_of_values(self):
        """Test that caching of values for authenticate users."""
        session_mock = MagicMock()
        session_dict = {}
        session_mock.__setitem__.side_effect = session_dict.__setitem__
        session_mock.__getitem__.side_effect = session_dict.__getitem__
        session_mock.__contains__.side_effect = session_dict.__contains__
        self.request.session = session_mock

        mock = Mock(return_value=False)
        self.request.user.groups.filter().exists = mock
        self.assertFalse(is_user_admin(self.request))
        mock.assert_called_once_with()
        session_mock.__setitem__.assert_called_once_with(
            'cache_user_is_admin', False)

        mock = Mock(return_value=False)
        self.request.user.groups.filter().exists = mock
        self.assertFalse(is_user_admin(self.request, cached=True))
        mock.assert_not_called()
        session_mock.__getitem__.assert_called_once_with(
            'cache_user_is_admin')

        mock = Mock(return_value=False)
        self.request.user.groups.filter().exists = mock
        self.assertFalse(is_user_admin(self.request, cached=False))
        mock.assert_called_once_with()
        session_mock.__getitem__.assert_called_once_with(
            'cache_user_is_admin')
Esempio n. 4
0
 def test_is_false_for_anonymous_user(self):
     """Test anonymous user is reported as non-admin."""
     super(TestIsAdminUser, self).setUp()
     self.request.user = Mock()
     self.request.user.is_authenticated = False
     self.assertFalse(is_user_admin(self.request))
     self.assertFalse(is_user_admin(self.request, cached=True))
Esempio n. 5
0
    def __init__(self, request, username, *args, **kwargs):
        """Initialize the form with extra request argument."""
        group_choices = dict(get_group_choices())
        for group in group_choices:
            Group.objects.get_or_create(name=group)

        self.request = request
        self.username = username
        super(UserUpdateForm, self).__init__(*args, **kwargs)

        choices = []

        for c in sorted(self.fields['groups'].choices, key=lambda x: x[1]):
            # Handle case where groups exist in database for
            # applications not installed yet.
            if c[1] in group_choices:
                # Replace group names with descriptions
                choices.append((c[0], group_choices[c[1]]))

        self.fields['groups'].label = 'Permissions'
        self.fields['groups'].choices = choices

        if not is_user_admin(request):
            self.fields['is_active'].widget = forms.HiddenInput()
            self.fields['groups'].disabled = True
Esempio n. 6
0
def warn_about_low_disk_space(request):
    """Warn about insufficient space on root partition."""
    if not is_user_admin(request, cached=True):
        return

    disks = storage.get_disks()
    list_root = [disk for disk in disks if disk['mountpoint'] == '/']
    if not list_root:
        logger.error('Error getting information about root partition.')
        return

    percent_used = list_root[0]['percent_used']
    size_bytes = list_root[0]['size']
    free_bytes = list_root[0]['free']
    free_gib = free_bytes / (1024 ** 3)

    message = format_lazy(
        # Translators: xgettext:no-python-format
        _('Warning: Low space on system partition ({percent_used}% used, '
          '{free_space} free).'),
        percent_used=percent_used,
        free_space=storage.format_bytes(free_bytes))

    if percent_used > 90 or free_gib < 1:
        messages.error(request, message)
    elif percent_used > 75 or free_gib < 2:
        messages.warning(request, message)
Esempio n. 7
0
    def dispatch(self, request, *args, **kwargs):
        """Handle a request and return a HTTP response."""
        if self.request.user.get_username() != self.kwargs['slug'] \
           and not is_user_admin(self.request.user):
            raise PermissionDenied

        return super().dispatch(request, *args, **kwargs)
Esempio n. 8
0
def common(request):
    """Add additional context values to RequestContext for use in templates.

    Any resources referenced in the return value are expected to have been
    initialized or configured externally beforehand.
    """
    # Allow a value in configuration file to be translated.  Allow
    # the brand name 'FreedomBox' itself to be translated.
    gettext_noop('FreedomBox')

    from plinth.notification import Notification
    notifications_context = Notification.get_display_context(request,
                                                             user=request.user)

    slash_indices = [match.start() for match in re.finditer('/', request.path)]
    active_menu_urls = [request.path[:index + 1] for index in slash_indices]
    return {
        'cfg': cfg,
        'submenu': menu.main_menu.active_item(request),
        'active_menu_urls': active_menu_urls,
        'box_name': _(cfg.box_name),
        'user_is_admin': is_user_admin(request, True),
        'notifications': notifications_context['notifications'],
        'notifications_max_severity': notifications_context['max_severity']
    }
Esempio n. 9
0
def warn_about_low_disk_space(request):
    """Warn about insufficient space on root partition."""
    if not is_user_admin(request, cached=True):
        return

    disks = storage.get_disks()
    list_root = [disk for disk in disks if disk['mountpoint'] == '/']
    if not list_root:
        logger.error('Error getting information about root partition.')
        return

    percent_used = list_root[0]['percent_used']
    size_bytes = list_root[0]['size']
    free_bytes = list_root[0]['free']
    free_gib = free_bytes / (1024**3)

    message = format_lazy(
        # Translators: xgettext:no-python-format
        _('Warning: Low space on system partition ({percent_used}% used, '
          '{free_space} free).'),
        percent_used=percent_used,
        free_space=storage.format_bytes(free_bytes))

    if percent_used > 90 or free_gib < 1:
        messages.error(request, message)
    elif percent_used > 75 or free_gib < 2:
        messages.warning(request, message)
Esempio n. 10
0
    def __init__(self, request, username, *args, **kwargs):
        """Initialize the form with extra request argument."""
        group_choices = dict(get_group_choices())
        for group in group_choices:
            Group.objects.get_or_create(name=group)

        self.request = request
        self.username = username
        super(UserUpdateForm, self).__init__(*args, **kwargs)

        choices = []

        for c in sorted(self.fields['groups'].choices, key=lambda x: x[1]):
            # Handle case where groups exist in database for
            # applications not installed yet.
            if c[1] in group_choices:
                # Replace group names with descriptions
                choices.append((c[0], group_choices[c[1]]))

        self.fields['groups'].label = 'Permissions'
        self.fields['groups'].choices = choices

        if not is_user_admin(request):
            self.fields['is_active'].widget = forms.HiddenInput()
            self.fields['groups'].disabled = True
Esempio n. 11
0
    def dispatch(self, request, *args, **kwargs):
        """Handle a request and return a HTTP response."""
        if self.request.user.get_username() != self.kwargs['slug'] \
           and not is_user_admin(self.request):
            raise PermissionDenied

        return super().dispatch(request, *args, **kwargs)
Esempio n. 12
0
def warn_about_low_disk_space(request):
    """Warn about insufficient space on root partition."""
    if not is_user_admin(request, cached=True):
        return

    disks = disks_module.get_disks()
    list_root = [disk for disk in disks if disk['mountpoint'] == '/']
    if not list_root:
        logger.error('Error getting information about root partition.')
        return

    perc_used = list_root[0]['percentage_used']
    size_bytes = _interpret_size_string(list_root[0]['size'])
    free_bytes = size_bytes * (100 - perc_used) / 100

    message = format_lazy(_(
        'Warning: Low space on system partition ({percent_used}% used, '
        '{free_space} free).'),
                          percent_used=perc_used,
                          free_space=_format_bytes(free_bytes))

    free_gib = free_bytes / (1024**3)
    if perc_used > 90 or free_gib < 1:
        messages.error(request, message)
    elif perc_used > 75 or free_gib < 2:
        messages.warning(request, message)
Esempio n. 13
0
    def process_view(request, view_func, view_args, view_kwargs):
        """Reject non-admin access to views that are private and not marked."""
        if is_view_func_public(view_func) or \
           hasattr(view_func, 'IS_NON_ADMIN'):
            return

        if not is_user_admin(request.user):
            raise PermissionDenied
Esempio n. 14
0
    def process_view(request, view_func, view_args, view_kwargs):
        """Reject non-admin access to views that are private and not marked."""
        if is_view_func_public(view_func) or \
           hasattr(view_func, 'IS_NON_ADMIN'):
            return

        if not is_user_admin(request.user):
            raise PermissionDenied
Esempio n. 15
0
    def __init__(self, request, username, *args, **kwargs):
        """Initialize the form with extra request argument."""
        for group, group_name in GROUP_CHOICES:
            Group.objects.get_or_create(name=group)

        self.request = request
        self.username = username

        super(UserUpdateForm, self).__init__(*args, **kwargs)

        if not is_user_admin(request):
            self.fields['is_active'].widget = forms.HiddenInput()
            self.fields['groups'].disabled = True
Esempio n. 16
0
    def __init__(self, request, username, *args, **kwargs):
        """Initialize the form with extra request argument."""
        for group, group_name in GROUP_CHOICES:
            Group.objects.get_or_create(name=group)

        self.request = request
        self.username = username

        super(UserUpdateForm, self).__init__(*args, **kwargs)

        if not is_user_admin(request.user):
            self.fields['is_active'].widget = forms.HiddenInput()
            self.fields['groups'].disabled = True
Esempio n. 17
0
def common(request):
    """Add additional context values to RequestContext for use in templates.

    Any resources referenced in the return value are expected to have been
    initialized or configured externally beforehand.
    """
    # Allow a value in configuration file to be translated.  Allow
    # the brand name 'FreedomBox' itself to be translated.
    ugettext_noop('FreedomBox')

    slash_indices = [match.start() for match in re.finditer('/', request.path)]
    active_menu_urls = [request.path[:index + 1] for index in slash_indices]
    return {
        'cfg': cfg,
        'submenu': main_menu.active_item(request),
        'active_menu_urls': active_menu_urls,
        'box_name': _(cfg.box_name),
        'user_is_admin': is_user_admin(request, True)
    }
Esempio n. 18
0
def index(request):
    """Serve the main index page."""
    shortcuts = frontpage.get_shortcuts()
    selection = request.GET.get('selected')

    details, details_label, configure_url = None, None, None
    if selection in frontpage.shortcuts:
        details = frontpage.shortcuts[selection]['details']
        details_label = frontpage.shortcuts[selection]['label']
        configure_url = frontpage.shortcuts[selection]['configure_url']

    return TemplateResponse(request, 'index.html',
                            {'title': _('FreedomBox'),
                             'shortcuts': shortcuts,
                             'selected_id': selection,
                             'details': details,
                             'details_label': details_label,
                             'configure_url': configure_url,
                             'user_is_admin': is_user_admin(request.user)})
Esempio n. 19
0
    def __init__(self, request, username, *args, **kwargs):
        """Initialize the form with extra request argument."""
        group_choices = dict(UsersAndGroups.get_group_choices())
        for group in group_choices:
            Group.objects.get_or_create(name=group)

        self.request = request
        self.username = username
        super(UserUpdateForm, self).__init__(*args, **kwargs)
        self.is_last_admin_user = get_last_admin_user() == self.username
        self.fields['username'].widget.attrs.update({
            'autofocus': 'autofocus',
            'autocapitalize': 'none',
            'autocomplete': 'username'
        })

        choices = []
        django_groups = sorted(self.fields['groups'].choices,
                               key=lambda choice: choice[1])
        for group_id, group_name in django_groups:
            try:
                group_id = group_id.value
            except AttributeError:
                pass

            # Show choices only from groups declared by apps.
            if group_name in group_choices:
                label = group_choices[group_name]
                if group_name == 'admin' and self.is_last_admin_user:
                    label = {'label': label, 'disabled': True}

                choices.append((group_id, label))

        self.fields['groups'].label = _('Permissions')
        self.fields['groups'].choices = choices

        if not is_user_admin(request):
            self.fields['is_active'].widget = forms.HiddenInput()
            self.fields['groups'].disabled = True

        if self.is_last_admin_user:
            self.fields['is_active'].disabled = True
Esempio n. 20
0
    def __init__(self, request, username, *args, **kwargs):
        """Initialize the form with extra request argument."""
        group_choices = dict(UsersAndGroups.get_group_choices())
        for group in group_choices:
            Group.objects.get_or_create(name=group)

        self.request = request
        self.username = username
        super(UserUpdateForm, self).__init__(*args, **kwargs)
        self.is_last_admin_user = get_last_admin_user() == self.username
        self.fields['username'].widget.attrs.update({
            'autofocus': 'autofocus',
            'autocapitalize': 'none',
            'autocomplete': 'username'
        })

        choices = []

        for c in sorted(self.fields['groups'].choices, key=lambda x: x[1]):
            # Handle case where groups exist in database for
            # applications not installed yet.
            if c[1] in group_choices:
                # Replace group names with descriptions
                if c[1] == 'admin' and self.is_last_admin_user:
                    choices.append((c[0], {
                        'label': group_choices[c[1]],
                        'readonly': True
                    }))
                else:
                    choices.append((c[0], group_choices[c[1]]))

        self.fields['groups'].label = _('Permissions')
        self.fields['groups'].choices = choices

        if not is_user_admin(request):
            self.fields['is_active'].widget = forms.HiddenInput()
            self.fields['groups'].disabled = True

        if self.is_last_admin_user:
            self.fields['is_active'].disabled = True
Esempio n. 21
0
    def process_request(request):
        """Handle a request as Django middleware request handler."""
        # Don't interfere with login page
        user_requests_login = request.path.startswith(
            reverse(settings.LOGIN_URL))
        if user_requests_login:
            return

        # Don't interfere with help pages
        user_requests_help = request.path.startswith(reverse('help:index'))
        if user_requests_help:
            return

        firstboot_completed = first_boot.is_completed()
        user_requests_firstboot = first_boot.is_firstboot_url(request.path)

        # If user requests a step other than the welcome step, verify that they
        # indeed completed the secret verification by looking at the session.
        if (user_requests_firstboot
                and not request.path.startswith(reverse('first_boot:welcome'))
                and first_boot.firstboot_wizard_secret_exists()
                and not request.session.get('firstboot_secret_provided', False)
                and not is_user_admin(request)):
            return HttpResponseRedirect(reverse('first_boot:welcome'))

        # Redirect to first boot if requesting normal page and first
        # boot is not complete.
        if not firstboot_completed and not user_requests_firstboot:
            next_step = first_boot.next_step_or_none()
            if next_step:
                return HttpResponseRedirect(reverse(next_step))
            else:
                # No more steps in first boot
                first_boot.set_completed()

        # Redirect to index page if request firstboot after it is
        # finished.
        if firstboot_completed and user_requests_firstboot:
            return HttpResponseRedirect(reverse('index'))
Esempio n. 22
0
    def process_view(request, view_func, view_args, view_kwargs):
        """Handle a request as Django middleware request handler."""
        # Don't interfere with login page
        user_requests_login = request.path.startswith(
            urls.reverse(settings.LOGIN_URL))
        if user_requests_login:
            return

        # Perform a URL resolution. This is slightly inefficient as
        # Django will do this resolution again.
        try:
            resolver_match = urls.resolve(request.path_info)
        except urls.Resolver404:
            return

        if not resolver_match.namespaces or not len(resolver_match.namespaces):
            # Requested URL does not belong to any application
            return

        app_id = resolver_match.namespaces[0]
        app = app_module.App.get(app_id)

        is_admin = is_user_admin(request)
        # Collect and show setup operation result to admins
        if is_admin:
            _collect_setup_result(request, app)

        # Check if application is up-to-date
        if app.get_setup_state() == \
           app_module.App.SetupState.UP_TO_DATE:
            return

        if not is_admin:
            raise PermissionDenied

        # Only allow logged-in users to access any setup page
        view = login_required(views.SetupView.as_view())
        return view(request, app_id=app_id)
Esempio n. 23
0
 def test_values_for_authenticated_users(self):
     """Test correct return values for authenticated users."""
     self.request.user.groups.filter().exists = Mock(return_value=False)
     self.assertFalse(is_user_admin(self.request))
     self.request.user.groups.filter().exists = Mock(return_value=True)
     self.assertTrue(is_user_admin(self.request))
Esempio n. 24
0
 def test_values_for_authenticated_users(self):
     """Test correct return values for authenticated users."""
     self.request.user.groups.filter().exists = Mock(return_value=False)
     self.assertFalse(is_user_admin(self.request))
     self.request.user.groups.filter().exists = Mock(return_value=True)
     self.assertTrue(is_user_admin(self.request))
Esempio n. 25
0
 def test_values_for_authenticated_users(web_request):
     """Test correct return values for authenticated users."""
     web_request.user.groups.filter().exists = Mock(return_value=False)
     assert not is_user_admin(web_request)
     web_request.user.groups.filter().exists = Mock(return_value=True)
     assert is_user_admin(web_request)
Esempio n. 26
0
 def test_is_false_for_anonymous_user(web_request):
     """Test anonymous user is reported as non-admin."""
     web_request.user = Mock()
     web_request.user.is_authenticated = False
     assert not is_user_admin(web_request)
     assert not is_user_admin(web_request, cached=True)