Beispiel #1
0
class BaseB3SectionPageView(BaseSectionPageView):
    """Subclass of BaseSectionPageView to immediately support Bootstrap3.
    """
    @method_decorator(use_bootstrap3())
    def dispatch(self, request, *args, **kwargs):
        return super(BaseB3SectionPageView,
                     self).dispatch(request, *args, **kwargs)
Beispiel #2
0
class BulkImportIndicatorsView(BaseSectionPageView, DomainViewMixin):
    urlname = 'indicators_upload_bulk'
    section_name = ugettext_noop("Administer Indicators")
    page_title = ugettext_noop("Bulk Import Indicators")
    template_name = 'indicators/bulk_import.html'

    @method_decorator(login_and_domain_required)
    @method_decorator(require_edit_indicators)
    @method_decorator(use_bootstrap3())
    def dispatch(self, request, *args, **kwargs):
        return super(BulkImportIndicatorsView,
                     self).dispatch(request, *args, **kwargs)

    @property
    @memoized
    def import_form(self):
        if self.request.method == 'POST':
            return ImportIndicatorsFromJsonFileForm(self.request.POST)
        return ImportIndicatorsFromJsonFileForm()

    @property
    def page_context(self):
        return {
            'import_form': self.import_form,
            'domain': self.domain,
        }

    @property
    def section_url(self):
        return reverse('default_indicator_admin', args=[self.domain])

    @property
    def page_url(self):
        return reverse(self.urlname, args=[self.domain])

    def post(self, request, *args, **kwargs):
        upload = request.FILES.get('json_file')
        if upload and self.import_form.is_valid():
            data = json.loads(upload.read())
            for (view_type, indicator_class) in [
                (u'indicator_definitions', IndicatorDefinition),
                (u'dynamic_indicator_definitions', DynamicIndicatorDefinition),
            ]:
                for doc in data[view_type]:
                    copied = indicator_class.copy_to_domain(
                        self.domain,
                        doc,
                        override=self.import_form.
                        cleaned_data['override_existing'])
            messages.success(request, _("Imported indicators!"))
            return HttpResponseRedirect(self.page_url)
        messages.error(request,
                       _("Failed up import any indicators. Check your file."))
        return self.get(request, *args, **kwargs)
Beispiel #3
0
class BaseStyleGuideArticleView(TemplateView):
    template_name = 'styleguide/base_section.html'

    @method_decorator(use_bootstrap3())
    def dispatch(self, request, *args, **kwargs):
        return super(BaseStyleGuideArticleView,
                     self).dispatch(request, *args, **kwargs)

    @property
    def sections(self):
        """This will be inserted into the page context's sections variable
        as a list of strings following the format
        'styleguide/_includes/<section>.html'
        Make sure you create the corresponding template in the styleguide app.

        :return: List of the sections in order. Usually organized by
        <article>/<section_name>
        """
        raise NotImplementedError("please implement 'sections'")

    @property
    def navigation_name(self):
        """This will be inserted into the page context under
        styleguide/_includes/nav/<navigation_name>.html. Make sure
        you create the corresponding template in the styleguide app
        when you add this.
        :return: a string that is the name of the navigation section
        """
        raise NotImplementedError("please implement 'navigation_name'")

    @property
    def section_context(self):
        return {
            'sections':
            ['styleguide/_includes/%s.html' % s for s in self.sections],
            'navigation':
            ('styleguide/_includes/nav/%s.html' % self.navigation_name),
        }

    @property
    def page_context(self):
        """It's intended that you override this method when necessary to provide
        any additional content that's relevant to the view specifically.
        :return: a dict
        """
        return {}

    def render_to_response(self, context, **response_kwargs):
        context.update(self.section_context)
        context.update(self.page_context)
        return super(BaseStyleGuideArticleView,
                     self).render_to_response(context, **response_kwargs)
Beispiel #4
0
class BaseDashboardView(LoginAndDomainMixin, BasePageView, DomainViewMixin):
    @method_decorator(use_bootstrap3())
    def dispatch(self, request, *args, **kwargs):
        return super(BaseDashboardView, self).dispatch(request, *args,
                                                       **kwargs)

    @property
    def main_context(self):
        context = super(BaseDashboardView, self).main_context
        context.update({
            'domain': self.domain,
        })
        return context

    @property
    def page_url(self):
        return reverse(self.urlname, args=[self.domain])
Beispiel #5
0
class NewListWebUsersView(JSONResponseMixin, BaseUserSettingsView):
    template_name = 'users/web_users.b3.html'
    page_title = ugettext_lazy("Web Users & Roles")
    urlname = 'web_users_b3'

    @method_decorator(use_bootstrap3())
    @method_decorator(use_knockout_js())
    @method_decorator(require_can_edit_web_users)
    def dispatch(self, request, *args, **kwargs):
        return super(NewListWebUsersView,
                     self).dispatch(request, *args, **kwargs)

    def query_es(self, limit, skip, query=None):
        web_user_filter = [
            {
                "term": {
                    "user.domain_memberships.domain": self.domain
                }
            },
        ]
        web_user_filter.extend(ADD_TO_ES_FILTER['web_users'])

        q = {
            "filter": {
                "and": web_user_filter
            },
            "sort": {
                'username.exact': 'asc'
            },
        }
        default_fields = ["username", "last_name", "first_name"]
        q["query"] = search_string_query(query, default_fields)
        return es_query(
            params={},
            q=q,
            es_url=ES_URLS["users"],
            size=limit,
            start_at=skip,
        )

    def apply_teams_to_users(self, web_users):
        teams = Team.get_by_domain(self.domain)
        for team in teams:
            for user in team.get_members():
                if user.get_id not in [
                        web_user.get_id for web_user in web_users
                ]:
                    user.from_team = True
                    web_users.append(user)
        for user in web_users:
            user.current_domain = self.domain

    @allow_remote_invocation
    def get_users(self, in_data):
        if not isinstance(in_data, dict):
            return {
                'success': False,
                'error': _("Please provide pagination info."),
            }
        try:
            limit = in_data.get('limit', 10)
            page = in_data.get('page', 1)
            skip = limit * (page - 1)
            query = in_data.get('query')

            web_users_query = self.query_es(limit, skip, query=query)
            total = web_users_query.get('hits', {}).get('total', 0)
            results = web_users_query.get('hits', {}).get('hits', [])

            web_users = [WebUser.wrap(w['_source']) for w in results]
            self.apply_teams_to_users(web_users)  # for roles

            def _fmt_result(domain, u):
                return {
                    'email':
                    u.email,
                    'domain':
                    domain,
                    'name':
                    u.full_name,
                    'role':
                    u.role_label(),
                    'phoneNumbers':
                    u.phone_numbers,
                    'id':
                    u.get_id,
                    'editUrl':
                    reverse('user_account', args=[domain, u.get_id]),
                    'removeUrl':
                    (reverse('remove_web_user', args=[domain, u.user_id])
                     if self.request.user.username != u.username else None),
                }

            web_users_fmt = [_fmt_result(self.domain, u) for u in web_users]

            return {
                'response': {
                    'users': web_users_fmt,
                    'total': total,
                    'page': page,
                    'query': query,
                },
                'success': True,
            }
        except Exception as e:
            return {
                'error': e.message,
                'success': False,
            }

    @property
    @memoized
    def user_roles(self):
        user_roles = [AdminUserRole(domain=self.domain)]
        user_roles.extend(
            sorted(UserRole.by_domain(self.domain),
                   key=lambda role: role.name if role.name else u'\uFFFF'))

        #  indicate if a role has assigned users, skip admin role
        for i in range(1, len(user_roles)):
            role = user_roles[i]
            role.__setattr__(
                'hasUsersAssigned',
                True if len(role.ids_of_assigned_users) > 0 else False)
        return user_roles

    @property
    def can_edit_roles(self):
        return has_privilege(self.request, privileges.ROLE_BASED_ACCESS) \
            and self.couch_user.is_domain_admin

    @property
    @memoized
    def role_labels(self):
        role_labels = {}
        for r in self.user_roles:
            key = 'user-role:%s' % r.get_id if r.get_id else r.get_qualified_id(
            )
            role_labels[key] = r.name
        return role_labels

    @property
    @memoized
    def invitations(self):
        invitations = DomainInvitation.by_domain(self.domain)
        for invitation in invitations:
            invitation.role_label = self.role_labels.get(invitation.role, "")
        return invitations

    @property
    def page_context(self):
        return {
            'user_roles': self.user_roles,
            'can_edit_roles': self.can_edit_roles,
            'default_role': UserRole.get_default(),
            'report_list': get_possible_reports(self.domain),
            'invitations': self.invitations,
            'domain_object': self.domain_object,
            'uses_locations': self.domain_object.uses_locations,
        }