def has_permission(context, model, permission, obj=None):
    """
    :param model: 'app_label.model'
    """
    membership = context['current_membership']
    return (shortcuts.has_role_permission(membership, model, permission)
            or shortcuts.has_object_permission(membership, obj, permission))
Ejemplo n.º 2
0
    def get_queryset(self):
        queryset = super(MeetingsFilteredQuerysetMixin, self).get_queryset()
        if not has_role_permission(self.get_current_membership(), Meeting,
                                   PERMISSIONS.edit):
            queryset = queryset.filter(status=Meeting.STATUSES.published)

        default_filters = {'order_by': 'asc', 'committee': '__all__'}
        self.form = MeetingFilter(self.get_current_membership(),
                                  self.request.GET,
                                  initial=default_filters)
        filters = self.form.cleaned_data if self.form.is_valid(
        ) else default_filters

        if filters['committee'] == '__full__':
            queryset = queryset.filter(committee=None)
        elif filters['committee'] != '__all__' and filters[
                'committee'].isdigit():
            queryset = queryset.filter(committee=filters['committee'])

        if filters['order_by'] == 'desc':
            queryset = queryset.order_by('-next_repetition__date')
        else:
            queryset = queryset.order_by('next_repetition__date')

        return queryset.select_related('committee')
Ejemplo n.º 3
0
    def check_permissions(self, request):
        super(RestPermissionMixin, self).check_permissions(request)

        # Manual handling of @login_required to return proper response for API usage (not a redirect)
        if not request.user.is_authenticated:
            self.permission_denied(request)

        account = get_current_account_for_url(request, self.kwargs['url'])
        membership = request.user.get_membership(account)

        if hasattr(self,
                   'get_model_permission'):  # Support dynamic permissions
            model, permission = self.get_model_permission(request)
        else:
            model, permission = self.permission

        obj = self.get_permission_object()
        if (self.and_permission(account, membership)
                and ((has_role_permission(membership, model, permission)
                      or has_object_permission(membership, obj, permission))
                     or self.or_permission(account, membership))):
            return

        # Soft land folder urls to root folder instead of 403
        if 'folders/' in request.path:
            self.permission_denied(request, "No access to this folder")
Ejemplo n.º 4
0
 def get_queryset(self):
     account = get_current_account(self.request)
     membership = self.request.user.get_membership(account)
     queryset = News.objects.filter(account=account)
     if has_role_permission(membership, News, PERMISSIONS.edit):
         return queryset
     return queryset.filter(
         Q(is_publish=True) | Q(created_member=membership))
Ejemplo n.º 5
0
 def dispatch(self, request, *args, **kwargs):
     account = get_current_account(request)
     membership = request.user.get_membership(account)
     model, permission = self.permission
     obj = self.get_permission_object()
     if (self.and_permission(account, membership)
             and ((has_role_permission(membership, model, permission)
                   or has_object_permission(membership, obj, permission))
                  or self.or_permission(account, membership))):
         return super(PermissionMixin,
                      self).dispatch(request, *args, **kwargs)
     # Soft land folder urls to root folder instead of 403
     if 'folders/' in request.path:
         return redirect('folders:rootfolder_detail', url=account.url)
     raise PermissionDenied()
Ejemplo n.º 6
0
    def get_object(self, queryset=None):
        # can't use PermissionMixin because there's no current_account when reactivating
        if 'account_id' in self.request.GET:
            form = AccountReactivateForm(self.request.GET)
            if form.is_valid():
                account = get_object_or_404(self.request.user.accounts.all(),
                                            id=form.cleaned_data['account_id'])
            else:
                raise PermissionDenied()
        elif get_current_account(self.request):
            account = get_current_account(self.request)
        else:
            raise PermissionDenied(
            )  # !!! should redirect to /accounts/ in future. Fix in WEB-160.

        # handle permissions manually
        membership = self.request.user.get_membership(account=account)
        if not has_role_permission(membership, Account, PERMISSIONS.edit):
            raise PermissionDenied()
        return account
Ejemplo n.º 7
0
    def form_valid(self, form):
        account_id = form.cleaned_data['account_id']
        account = Account.objects.get(id=account_id)
        membership = self.request.user.get_membership(account)

        if not (account.can_be_activated() and has_role_permission(
                membership, Account, PERMISSIONS.edit)):
            raise PermissionDenied()

        account._update_subscription()
        if account.is_trial() or account.stripe_customer_id:
            account.is_active = True
            account.date_cancel = None
            account.save()
            messages.success(self.request,
                             _('Account was reactivated successfully.'))
        else:
            messages.error(
                self.request,
                _('There was a problem with your billing information.'))

        data = {'url': reverse('accounts:boards')}
        return self.render_to_json_response(data)
def has_role_permission(membership, permission_string):
    """
    :param permission_string: 'app_label.model:permission'.
    """
    model, permission = permission_string.split(':')
    return shortcuts.has_role_permission(membership, model, permission)
Ejemplo n.º 9
0
    def __init__(self, *args, **kwargs):
        is_event = kwargs.pop('is_event')

        super(MeetingAddForm, self).__init__(*args, **kwargs)
        self.fields['committee'].label = _('Attendees')
        self.fields['committee'].empty_label = _('All Board Members')
        self.fields['name'].widget.attrs['placeholder'] = \
            _('Untitled Event') if is_event else _('Untitled Meeting')
        self.fields['description'].widget.attrs['placeholder'] = \
            _('Event Description') if is_event else _('Meeting Description')

        membership = self.initial.get('membership')
        account = self.initial.get('account')
        meeting = self.instance
        assert isinstance(meeting, Meeting)

        top_locations = self.get_locations()

        if account.default_meetings_location and len(
                account.default_meetings_location) > 0:
            init_location = account.default_meetings_location
        elif top_locations and len(top_locations) > 0:
            init_location = top_locations[0]
        else:
            init_location = ""

        self.fields['location'] = \
            forms.CharField(label=_('Location'),
                            widget=LocationWidget(data_list=top_locations),
                            initial=init_location,
                            max_length=250,
                            required=True)

        queryset = Committee.objects.filter(account=account)
        if has_role_permission(membership, Committee, PERMISSIONS.add):
            # can add meeting for any committee
            self.fields['committee'].queryset = queryset
        else:
            # can add meeting only if chairman
            self.fields['committee'].queryset = \
                queryset.filter(Q(chairman=membership) | Q(chairman__in=membership.get_bosses()))

        self.fields['repeat_end_date'] = \
            forms.DateField(label=_('Repeat end date'),
                            input_formats=['%b. %d, %Y'],
                            widget=forms.DateInput(attrs={'placeholder': '{:%b. %d, %Y}'.format(timezone.now())}),
                            required=False)
        self.fields['date'] = \
            forms.DateField(label=_('Date'),
                            input_formats=['%b. %d, %Y'],
                            widget=forms.DateInput(attrs={'placeholder': '{:%b. %d, %Y}'.format(timezone.now())}),
                            required=True)
        self.fields['time_start'] = forms.TimeField(
            label=_('From'),
            input_formats=['%I:%M %p'],
            widget=forms.TimeInput(attrs={'class': 'from'}),
            required=True)
        self.fields['time_end'] = forms.TimeField(
            label=_('To'),
            input_formats=['%I:%M %p'],
            widget=forms.TimeInput(attrs={'class': 'to'}),
            required=True)
        self.fields['action'] = forms.ChoiceField(
            meeting_action_choices(meeting, membership))

        members = Membership.objects.filter(
            account=account, user__is_active=True,
            is_active=True).select_related('user')
        self.fields['extra_members'] = \
            forms.ModelMultipleChoiceField(members, label=_('Additional Attendees'), required=False,
                                           widget=forms.SelectMultiple(attrs={'class': 'default'}))

        key_order = [
            'name', 'description', 'committee', 'extra_members', 'date',
            'time_start', 'time_end', 'location', 'action', 'repeat_type',
            'repeat_interval', 'repeat_max_count', 'repeat_end_date',
            'repeat_week_days', 'repeat_end_type'
        ]
        self.fields = reorder_form_fields(self.fields, key_order)

        if not is_event:
            self.fields['board_book'] = forms.FileField(
                label=_('Add Board Book'), required=False)
            self.fields['agenda'] = forms.FileField(label=_('Add Agenda'),
                                                    required=False)
            self.fields['minutes'] = forms.FileField(label=_('Add Minutes'),
                                                     required=False)

        self.fields['other'] = forms.FileField(label=_('Add Other Documents'),
                                               required=False)
        self.fields['uploaded'] = forms.CharField(widget=forms.HiddenInput(),
                                                  required=False)
        self.fields['repeat_end_type'].initial = meeting.repeat_end_type

        if meeting.pk:
            start = timezone.localtime(meeting.start)
            end = timezone.localtime(meeting.end)
            self.fields['date'].initial = start.strftime("%b. %d, %Y")
            self.initial['repeat_end_date'] = \
                meeting.repeat_end_date.strftime("%b. %d, %Y") if meeting.repeat_end_date else None
            self.fields['time_start'].initial = start.strftime("%I:%M %p")
            self.fields['time_end'].initial = end.strftime("%I:%M %p")