Example #1
0
    def done(self, form_list, **kwargs):
        invoice = None

        from django_tools.middlewares import ThreadLocal

        user = ThreadLocal.get_current_user().username
        klient = Klient.objects.get(nazwa=user)

        for form in form_list:
            if isinstance(form, ZamowienieForm):
                invoiceData = form.cleaned_data
                invoiceData.update({
                    'klient': klient
                })
                invoice = Zamowienie(**invoiceData)
                invoice.save()
            elif isinstance(form, BaseFormSet):
                for posForm in form.forms:
                    if isinstance(posForm, PozycjaZamowieniaForm):
                        positionData = posForm.cleaned_data
                        positionData.update({
                            'zamowienie': invoice
                        })
                        position = PozycjaZamowienia(**positionData)
                        position.save()
                    else:
                        posForm.save()

        self.storage.reset()

        return render_to_response('wizard/stepDone.html',
                                  {'zamowienie': invoice,
                                   'pozycje': PozycjaZamowienia.objects.filter(zamowienie_id=invoice.pk)},
                                  context_instance=RequestContext(ThreadLocal.get_current_request()))
Example #2
0
    def done(self, form_list, **kwargs):
        invoice = None

        from django_tools.middlewares import ThreadLocal

        user = ThreadLocal.get_current_user().username
        klient = Klient.objects.get(nazwa=user)

        for form in form_list:
            if isinstance(form, ZamowienieForm):
                invoiceData = form.cleaned_data
                invoiceData.update({'klient': klient})
                invoice = Zamowienie(**invoiceData)
                invoice.save()
            elif isinstance(form, BaseFormSet):
                for posForm in form.forms:
                    if isinstance(posForm, PozycjaZamowieniaForm):
                        positionData = posForm.cleaned_data
                        positionData.update({'zamowienie': invoice})
                        position = PozycjaZamowienia(**positionData)
                        position.save()
                    else:
                        posForm.save()

        self.storage.reset()

        return render_to_response('wizard/stepDone.html', {
            'zamowienie':
            invoice,
            'pozycje':
            PozycjaZamowienia.objects.filter(zamowienie_id=invoice.pk)
        },
                                  context_instance=RequestContext(
                                      ThreadLocal.get_current_request()))
Example #3
0
def get_ols_url():
    req = ThreadLocal.get_current_request()
    protocol = req.META['wsgi.url_scheme']
    r = req.build_absolute_uri()
    ols_url = protocol + '://' + ThreadLocal.get_current_request().META['HTTP_HOST'] + reverse(
        'copo:ajax_search_ontology')

    return ols_url
Example #4
0
    def process_request(self, request):
        url = request.get_full_path()
        if url.startswith('/copo', 0, 5):

            doc = Submission().get_incomplete_submissions_for_user(request.user.id, figshare)
            data_dict = dict()
            token = None

            if doc.count() > 0:

                if 'code' in request.GET and 'state' in request.GET:

                    token_obtained = True

                    for d in doc:
                        if d.get('token_obtained') == 'false':
                            token_obtained = False
                            break

                    if not token_obtained:

                        # get new token from Figshare
                        code = request.GET.get('code')
                        client_id = FIGSHARE_CREDENTIALS['client_id']
                        token_url = FIGSHARE_API_URLS['authorization_token']

                        # now get token
                        data = {
                            'client_id': client_id,
                            'code': code,
                            'client_secret': FIGSHARE_CREDENTIALS['client_secret'],
                            'grant_type': 'authorization_code',
                            'scope': 'all'
                        }
                        try:
                            r = requests.post(token_url, data)
                            data_dict = ast.literal_eval(r.content.decode('utf-8'))
                            token = data_dict['token']
                            t = Figshare().put_token_for_user(user_id=ThreadLocal.get_current_user().id, token=token)
                            if t:
                                # mark fighshare submissions for this user as token obtained
                                Submission().mark_all_token_obtained(user_id=request.user.id)

                                # if all is well, the access token will be stored in FigshareSubmussionCollection
                        except Exception as e:
                            print(e)

                    else:
                        # retrieve token
                        token = Figshare().get_token_for_user(user_id=ThreadLocal.get_current_user().id)


                        # request.session['partial_submissions'] = doc
            else:
                request.session['partial_submissions'] = None
Example #5
0
    def create_sra_person(self):
        """
        create an (SRA) person record and attach to profile

        Args:
            profile_id: to be linked to created record

        Returns:

        """
        user = ThreadLocal.get_current_user()

        auto_fields = {
            'copo.person.roles.annotationValue': 'SRA Inform On Status',
            'copo.person.lastName': user.last_name,
            'copo.person.firstName': user.first_name,
            'copo.person.roles.annotationValue_1': 'SRA Inform On Error',
            'copo.person.email': user.email
        }

        people = self.get_all_records()
        sra_roles = list()
        for record in people:
            for role in record.get("roles", list()):
                sra_roles.append(role.get("annotationValue", str()))

        # has sra roles?
        has_sra_roles = all(x in sra_roles for x in ['SRA Inform On Status', 'SRA Inform On Error'])

        if not has_sra_roles:
            kwargs = dict()
            self.save_record(auto_fields, **kwargs)

        return
Example #6
0
    def get_permalink(self):
        """
        return a permalink. Use page slug/name/title or nothing as additional text.
        """
        if self.pk in self._permalink_cache:
            #print "PageMeta permalink_cache len: %s, pk: %s" % (len(self._permalink_cache), self.pk)
            return self._permalink_cache[self.pk]

        # Get the system preferences
        request = ThreadLocal.get_current_request()
        sys_pref = request.PYLUCID.preferences
        sys_pref_form = request.PYLUCID.preferences_form

        use_additions = sys_pref.get("permalink_additions", sys_pref_form.PERMALINK_USE_TITLE)

        do_slugify = False
        if use_additions == sys_pref_form.PERMALINK_USE_TITLE:
            # Append the PageMeta title (language dependent)
            addition_txt = self.get_title()
            do_slugify = True
        elif use_additions == sys_pref_form.PERMALINK_USE_NAME:
            addition_txt = self.get_name()
            do_slugify = True
        elif use_additions == sys_pref_form.PERMALINK_USE_SLUG:
            addition_txt = self.pagetree.slug
        else:
            addition_txt = ""

        if do_slugify:
            addition_txt = slugify(addition_txt)

        url = reverse('PyLucid-permalink', kwargs={'page_id': self.pagetree.id, 'url_rest': addition_txt})
        self._permalink_cache[self.pk] = url
        return url
Example #7
0
    def get_permalink(self):
        """
        return a permalink. Use page slug/name/title or nothing as additional text.
        """
        # Get the system preferences
        request = ThreadLocal.get_current_request()
        sys_pref = request.PYLUCID.preferences
        sys_pref_form = request.PYLUCID.preferences_form

        use_additions = sys_pref.get("permalink_additions",
                                     sys_pref_form.PERMALINK_USE_TITLE)

        do_slugify = False
        if use_additions == sys_pref_form.PERMALINK_USE_TITLE:
            # Append the PageMeta title (language dependent)
            addition_txt = self.get_title()
            do_slugify = True
        elif use_additions == sys_pref_form.PERMALINK_USE_NAME:
            addition_txt = self.get_name()
            do_slugify = True
        elif use_additions == sys_pref_form.PERMALINK_USE_SLUG:
            addition_txt = self.pagetree.slug
        else:
            addition_txt = ""

        if do_slugify:
            addition_txt = slugify(addition_txt)

        url = reverse('PyLucid-permalink',
                      kwargs={
                          'page_id': self.pagetree.id,
                          'url_rest': addition_txt
                      })
        return url
Example #8
0
    def get_permissions(self):
        """
        returns the access permissions for this menu entry.
        TODO: Should be cache this?
        """
        if not self.url_name: # a menu section
            # TODO: Check if at least one sub entry is accessible.
            return (False, (), False)

        url = self.get_url()
        if url is None: # can't resolve url, message was created.
            return (True, (), True) # view can only superusers use

        # Get the view function for this url_name
        view_func, func_args, func_kwargs = urlresolvers.resolve(url)

        # get the rights from pylucid_project.apps.pylucid.decorators.check_permissions
        try:
            access_permissions = view_func.access_permissions
        except AttributeError, err:
            # If no permissions available, fallback to superuser only
            request = ThreadLocal.get_current_request()
            if settings.DEBUG or request.user.is_staff:
                messages.error(request, (
                    "The view %s for url %r has no permissions attribute!"
                    " Please use pylucid_project.apps.pylucid.decorators.check_permissions!"
                    ) % (view_func.__name__, self.url_name)
                )
            access_permissions = (True, (), True)
Example #9
0
 def GET_FOR_USER(self, user=None):
     if (user == None):
         user = ThreadLocal.get_current_user().id
     docs = Profiles.find({'user_id': user})
     if not docs:
         pass
     return docs
Example #10
0
    def get_absolute_url(self):
        """
        absolute url (without domain/host part)
        TODO: Should be used a cache here?
        """
        if not self.url_name:
            return "" # menu section

        url = self.get_url()
        if url is None: # can't resolve url, message was created.
            return "#resolve-error" # XXX: return something else?

        request = ThreadLocal.get_current_request()
        get_data = {}
        if self.get_pagetree and hasattr(request.PYLUCID, "pagetree"):
            get_data["pagetree"] = request.PYLUCID.pagetree.pk
        if self.get_pagemeta and hasattr(request.PYLUCID, "pagemeta"):
            get_data["pagemeta"] = request.PYLUCID.pagemeta.pk
        if self.get_page:
            if hasattr(request.PYLUCID, "pagecontent"):
                get_data["pagecontent"] = request.PYLUCID.pagecontent.pk
            elif hasattr(request.PYLUCID, "pluginpage"):
                get_data["pluginpage"] = request.PYLUCID.pluginpage.pk

        if get_data:
            # FIXME: There must be a better was to to this.
            # TODO: escape it.
            url += "?" + "&".join(["%s=%s" % (key, value) for key, value in get_data.items()])

        return url
Example #11
0
 def get_absolute_url(self):
     country = ThreadLocal.get_current_request().country
     return reverse('source_view',
                    kwargs={
                        'pk': self.pk,
                        'country': country,
                    })
Example #12
0
    def log_action(self, app_label, action, request=None, message=None, long_message=None, data=None):
        if request is None:
            request = ThreadLocal.get_current_request()

        kwargs = {
            "uri": request.build_absolute_uri(),
            "app_label": app_label,
            "action": action,
            "message": message,
            "long_message": long_message,
            "data": data,
        }

        if hasattr(request, "PYLUCID"):
            kwargs["used_language"] = request.PYLUCID.current_language

        for key in META_KEYS:
            value = request.META.get(key)
            if value and len(value) > 255:
                value = "%s..." % value[:252]
            kwargs[key.lower()] = value

        new_entry = self.model(**kwargs)
        new_entry.save()
        return new_entry
Example #13
0
def view_orcid_profile(request):
    user = ThreadLocal.get_current_user()
    op = Orcid().get_orcid_profile(user)
    data_dict = {'op': op}
    # data_dict = jsonpickle.encode(data_dict)

    return render(request, 'copo/orcid_profile.html', data_dict)
Example #14
0
    def __init__(self, *args, **kwargs):
        """
        prepare the tag queryset filter
        """
        super(TagLanguageSitesFilter, self).__init__(*args, **kwargs)

        def get_data(field_name):
            return self.initial.get(field_name, None) or self.data.get(field_name, None)

        language = get_data("language")
        if not language:
            # Use current language for tag queryset filter
            request = ThreadLocal.get_current_request()
            language = request.PYLUCID.current_language

        sites = get_data("sites")
        if not sites:
            # Use current site for tag queryset filter
            sites = [settings.SITE_ID]

        # change the tag queryset filter:
        self.fields["tags"].widget.tag_queryset_filters = {
            "language": language,
            "sites__id__in": sites,
        }
Example #15
0
    def _check_permissions(self):
        usr = ThreadLocal.get_current_user()

        # The chunk_info field is set to 'restricted' if only authors and
        # reviewers of the chunk are allowed to view it.
        if self.chunk_info == None:
            cinfo = ""
        else:
            cinfo = self.chunk_info

        # get the authors.
        authors = [
            str(u.username) for u in self.file.submission.authors.filter()
        ]
        # get the assigned reviewers.
        assigned_reviewers = User.objects.filter(
            tasks__submission=self.file.submission)
        reviewers = [str(u.username) for u in assigned_reviewers]

        allowed_users = authors + reviewers

        if cinfo.find('restricted') != -1 and not str(
                usr.username) in allowed_users:
            # Don't stop super users from viewing chunks.
            if not usr.is_superuser:
                raise PermissionDenied
Example #16
0
    def __init__(self, *args, **kwargs):
        """
        prepare the tag queryset filter
        """
        super(TagLanguageSitesFilter, self).__init__(*args, **kwargs)

        def get_data(field_name):
            return self.initial.get(field_name, None) or self.data.get(
                field_name, None)

        language = get_data("language")
        if not language:
            # Use current language for tag queryset filter
            request = ThreadLocal.get_current_request()
            language = request.PYLUCID.current_language

        sites = get_data("sites")
        if not sites:
            # Use current site for tag queryset filter
            sites = [settings.SITE_ID]

        # change the tag queryset filter:
        self.fields["tags"].widget.tag_queryset_filters = {
            "language": language,
            self.sites_filter: sites,
        }
Example #17
0
def generate_copo_sample_form(source_id=None, sample_id=None):
    profile_id = ThreadLocal.get_current_request().session['profile_id']

    # if there are sources in the profile, create a dropdown showing the sources and a box to create a new one
    # if there are no sources in the profile, create the new source form
    output = ''
    if ProfileInfo(profile_id).source_count() > 0:
        # get sources
        sources = Source(profile_id).get_all_sources()

        output += "<div id='source_select'>"
        output += generate_copo_source_dropdown(sources)
        output += generate_copo_source_add_button()
        output += "</div>"
        output += "<div id='new_source_div'>"
        output += generate_copo_source_form_html()
        output += "</div>"
    else:
        output += "<div id='new_source_div'>"
        output += generate_copo_source_form_html()
        output += "</div>"

    output += generate_copo_sample_form_html()

    return output
Example #18
0
    def get_permissions(self):
        """
        returns the access permissions for this menu entry.
        TODO: Should be cache this?
        """
        if not self.url_name:  # a menu section
            # TODO: Check if at least one sub entry is accessible.
            return (False, (), False)

        url = self.get_url()
        if url is None:  # can't resolve url, message was created.
            return (True, (), True)  # view can only superusers use

        # Get the view function for this url_name
        view_func, func_args, func_kwargs = urlresolvers.resolve(url)

        # get the rights from pylucid_project.apps.pylucid.decorators.check_permissions
        try:
            access_permissions = view_func.access_permissions
        except AttributeError, err:
            # If no permissions available, fallback to superuser only
            request = ThreadLocal.get_current_request()
            if settings.DEBUG or request.user.is_staff:
                messages.error(request, (
                    "The view %s for url %r has no permissions attribute!"
                    " Please use pylucid_project.apps.pylucid.decorators.check_permissions!"
                ) % (view_func.__name__, self.url_name))
            access_permissions = (True, (), True)
Example #19
0
    def get_absolute_url(self):
        """
        absolute url (without domain/host part)
        TODO: Should be used a cache here?
        """
        if not self.url_name:
            return ""  # menu section

        url = self.get_url()
        if url is None:  # can't resolve url, message was created.
            return "#resolve-error"  # XXX: return something else?

        request = ThreadLocal.get_current_request()
        get_data = {}
        if self.get_pagetree and hasattr(request.PYLUCID, "pagetree"):
            get_data["pagetree"] = request.PYLUCID.pagetree.pk
        if self.get_pagemeta and hasattr(request.PYLUCID, "pagemeta"):
            get_data["pagemeta"] = request.PYLUCID.pagemeta.pk
        if self.get_page:
            if hasattr(request.PYLUCID, "pagecontent"):
                get_data["pagecontent"] = request.PYLUCID.pagecontent.pk
            elif hasattr(request.PYLUCID, "pluginpage"):
                get_data["pluginpage"] = request.PYLUCID.pluginpage.pk

        if get_data:
            # FIXME: There must be a better was to to this.
            # TODO: escape it.
            url += "?" + "&".join(
                ["%s=%s" % (key, value) for key, value in get_data.items()])

        return url
Example #20
0
 def __init__(self, sub_id):
     self.BASE_URL = FIGSHARE_API_URLS['base_url']
     request = ThreadLocal.get_current_request()
     self.TOKEN = Figshare().get_token_for_user(request.user.id)['token']
     self.HEADERS = {'Authorization': 'token ' + self.TOKEN}
     self.MEDIA_ROOT = settings.MEDIA_ROOT
     self.transfer_token = RemoteDataFile().create_transfer(sub_id)['_id']
Example #21
0
    def _setup_tag_filter(self):
        """
        prepare the tag queryset filter
        """
        def get_data(field_name):
            return self.initial.get(field_name, None) or self.data.get(field_name, None)

        language = get_data("language")
        if not language:
            # Use current language for tag queryset filter
            request = ThreadLocal.get_current_request()
            language = request.PYLUCID.current_language

        pagetree_id = get_data("pagetree")
        if pagetree_id:
            pagetree = PageTree.objects.only("site").get(id=pagetree_id)
            site = pagetree.site
        else:
            # Use current site for tag queryset filter
            site = settings.SITE_ID

        # change the tag queryset filter:
        self.fields["tags"].widget.tag_queryset_filters = {
            "language": language,
            "pagetree__site": site,
        }
Example #22
0
    def save(self, *args, **kwargs):
        user = ThreadLocal.get_current_user()
        if user:
            if not self.pk:
                self.created_by = user

            self.modified_by = user
        super(UserDateAbstractModel, self).save(*args, **kwargs)
Example #23
0
def get_current_language():
    """
    Get the current language from request
    """
    request = ThreadLocal.get_current_request()
    if request:
        return request.LANGUAGE_CODE
    else:
        return properties.LANGUAGE_CODE
Example #24
0
    def save(self, *args, **kwargs):
        current_user = ThreadLocal.get_current_user()

        if current_user and isinstance(current_user, User):
            if self.pk == None or kwargs.get("force_insert", False): # New model entry
                self.createby = current_user
            self.lastupdateby = current_user

        return super(UpdateUserBaseModel, self).save(*args, **kwargs)
Example #25
0
 def _get_callable(self, obj, attr):
     """ Check if the attr is callable, return its value if it is """
     try:
         _attr = getattr(obj, attr)
         if callable(_attr):
             request = ThreadLocal.get_current_request()
             return _attr(request=request)
     except AttributeError:  # not a model/object attribute or relation does not exist
         pass
     return None
Example #26
0
    def save(self, *args, **kwargs):
        current_user = ThreadLocal.get_current_user()

        if current_user and isinstance(current_user, User):
            if self.pk == None or kwargs.get("force_insert",
                                             False):  # New model entry
                self.createby = current_user
            self.lastupdateby = current_user

        return super(UpdateUserBaseModel, self).save(*args, **kwargs)
Example #27
0
    def do_sample_wizard_components(self):
        self.context['wiz_message'] = d_utils.json_to_pytype(lkup.MESSAGES_LKUPS["sample_wizard_messages"])[
            "properties"]
        self.context['wiz_howtos'] = d_utils.json_to_pytype(lkup.MESSAGES_LKUPS["sample_wizard_howto"])
        self.context['wizard_stages'] = self.wizard_helper.generate_stage_items()

        # get all records: used in the UI for 'cloning' and other purposes
        profile_id = ThreadLocal.get_current_request().session['profile_id']
        self.context["component_records"] = htags.generate_component_records("sample", profile_id)

        return self.context
Example #28
0
 def get_html(self):
     """ return the marker_text as html """
     request = ThreadLocal.get_current_request()
     html = apply_markup(
         raw_content=self.marker_text,
         markup_no=self.markup,
         request=request
     )
     # Needed for JavaScript:
     html = html.strip().replace("\n", "").replace('"', '\"')
     return mark_safe(html)
Example #29
0
    def __init__(self, target_object, data=None, initial=None):
        """ prefill some user info """       
        if initial is None:
            initial = {}

        current_user = ThreadLocal.get_current_user()
        if current_user.is_authenticated():
            initial["name"] = current_user.get_full_name() or current_user.username
            initial["email"] = current_user.email

        super(PyLucidCommentForm, self).__init__(target_object, data, initial)
Example #30
0
    def get_current(self, request=None):
        """ return client Language instance, if not available, use get_default_lang_entry() """
        if request == None:
            request = ThreadLocal.get_current_request()

        if request == None:
            # no request available, e.g. loading fixtures
            return self._get_default_language()

        language_list = self.get_languages(request)
        return language_list[0]
Example #31
0
    def get_current(self, request=None):
        """ return client Language instance, if not available, use get_default_lang_entry() """
        if request == None:
            request = ThreadLocal.get_current_request()

        if request == None:
            # no request available, e.g. loading fixtures
            return self._get_default_language()

        language_list = self.get_languages(request)
        return language_list[0]
Example #32
0
def get_current_host():
    """
    Get the current hostname with protocol
    E.g. http://localhost:8000 or https://bluebottle.org
    """
    request = ThreadLocal.get_current_request()
    if request.is_secure():
        scheme = 'https'
    else:
        scheme = 'http'
    return '{0}://{1}'.format(scheme, request.get_host())
Example #33
0
    def get_for_user(self, user=None):
        if not user:
            user = ThreadLocal.get_current_user().id

        docs = self.get_collection_handle().find({"user_id": user, "deleted": data_utils.get_not_deleted_flag()}).sort(
            [['_id', -1]])

        if docs:
            return docs
        else:
            return None
Example #34
0
    def purge_descriptions(self):
        """
        purges the Description collection of all 'obsolete' tokens
        :return:
        """

        user_id = ThreadLocal.get_current_user().id

        bulk = self.DescriptionCollection.initialize_unordered_bulk_op()
        bulk.find({'user_id': user_id}).remove()
        bulk.execute()
Example #35
0
 def get_html(self):
     """ return the marker_text as html """
     request = ThreadLocal.get_current_request()
     html = apply_markup(
         raw_content=self.marker_text,
         markup_no=self.markup,
         request=request
     )
     # Needed for JavaScript:
     html = html.strip().replace("\n", "").replace('"', '\"')
     return mark_safe(html)
Example #36
0
    def __init__(self, target_object, data=None, initial=None):
        """ prefill some user info """
        if initial is None:
            initial = {}

        current_user = ThreadLocal.get_current_user()
        if current_user.is_authenticated():
            initial["name"] = current_user.get_full_name(
            ) or current_user.username
            initial["email"] = current_user.email

        super(PyLucidCommentForm, self).__init__(target_object, data, initial)
Example #37
0
    def all_accessible(self, user=None, filter_showlinks=False):
        """ returns a PageTree queryset with all items that the given user can access. """
        if user == None:
            user = ThreadLocal.get_current_user()

        queryset = self.model.on_site.order_by("position")
        queryset = self.filter_accessible(queryset, user)

        if filter_showlinks:
            # Filter PageTree.showlinks
            queryset = queryset.filter(showlinks=True)

        return queryset
Example #38
0
    def all_accessible(self, user=None, filter_showlinks=False):
        """ returns a PageTree queryset with all items that the given user can access. """
        if user == None:
            user = ThreadLocal.get_current_user()

        queryset = self.model.on_site.order_by("position")
        queryset = self.filter_accessible(queryset, user)

        if filter_showlinks:
            # Filter PageTree.showlinks
            queryset = queryset.filter(showlinks=True)

        return queryset
Example #39
0
 def _create_dataverse(self, meta, conn):
     alias = str(uuid.uuid4())
     email = ""
     for f in meta["fields"]:
         if f["dc"] == "dc.title":
             name = f["vals"][0]
         if f["dc"] == "dc.email":
             email = f["vals"][0]
     if email == "":
         u = ThreadLocal.get_current_user()
         email = u.email
     dv = conn.create_dataverse(alias, name, email)
     return dv
Example #40
0
    def save(self, *args, **kwargs):
        """
        Automatic update createby and lastupdateby attributes with the request object witch must be
        the first argument.
        """
        current_user = ThreadLocal.get_current_user()

        if current_user and isinstance(current_user, User):
            if self.pk == None or kwargs.get("force_insert", False): # New model entry
                self.createby = current_user
            self.lastupdateby = current_user

        return super(UpdateInfoBaseModel, self).save(*args, **kwargs)
Example #41
0
    def isValidCredentials(self, user_id):

        # check if token exists for user
        token = Figshare().get_token_for_user(user_id=ThreadLocal.get_current_user().id)
        if token:
            # now check if token works
            headers = {'Authorization': 'token ' + token['token']}
            r = requests.get('https://api.figshare.com/v2/account/articles', headers=headers)
            if r.status_code == 200:
                return True
            else:
                # we have an invalid token stored, so we should delete it and prompt the user for a new one
                Figshare().delete_tokens_for_user(user_id=user_id)
        return False
Example #42
0
    def create_description(self, stages=list(), attributes=dict()):
        self.purge_descriptions()

        fields = dict(
            stages=stages,
            attributes=attributes,
            created_on=data_utils.get_datetime(),
            user_id=ThreadLocal.get_current_user().id
        )
        doc = self.DescriptionCollection.insert(fields)

        # return inserted record
        df = self.GET(str(doc))
        return df
Example #43
0
def get_current_host(include_scheme=True):
    """
    Get the current hostname with protocol
    E.g. http://localhost:8000 or https://bluebottle.org
    """
    request = ThreadLocal.get_current_request()
    host = request.get_host()
    if include_scheme:
        if request.is_secure():
            scheme = 'https'
        else:
            scheme = 'http'
        return '{0}://{1}'.format(scheme, request.get_host())
    else:
        return host
Example #44
0
    def get_profiles_status(self):
        from .copo_da import Profile
        # this method examines all the profiles owned by the current user and returns
        # the number of profiles which have been marked as dirty
        issues = {}
        issue_desc = []
        issue_id = []
        issues_count = 0
        try:
            user_id = ThreadLocal.get_current_user().id
            prof = Profiles.find({"user_id": user_id})
        except AttributeError as e:
            prof = []

        # iterate profiles and find collections which are dirty
        for p in prof:
            try:
                collections_ids = p['collections']
            except:
                issues_count += 1
                context = {}
                context["profile_name"] = p['title']
                context["link"] = reverse('copo:view_copo_profile', args=[p["_id"]])
                issue_desc.append(STATUS_CODES['PROFILE_EMPTY'].format(**context))
                break
            # now get the corresponding collection_heads
            collections_heads = Collections.find({'_id': {'$in': collections_ids}},
                                                 {'is_clean': 1, 'collection_details': 1})
            # for c in collections_heads:
            #     try:
            #         if c['is_clean'] == 0:
            #             profile = Profile().get_profile_from_collection_id(c["_id"])
            #             issues_count += 1
            #             context = {}
            #             context["profile_name"] = p['title']
            #             context["link"] = reverse('copo:view_copo_profile', args=[profile["_id"]])
            #
            #             # now work out why the collection is dirty
            #             if False:
            #                 pass
            #             else:
            #                 issue_desc.append(STATUS_CODES['PROFILE_NOT_DEPOSITED'].format(**context))
            #     except:
            #         pass
        issues['issue_id_list'] = issue_id
        issues['num_issues'] = issues_count
        issues['issue_description_list'] = issue_desc
        return issues
Example #45
0
    def auto_order_posten(self):
        queryset = RechnungsPosten.objects.filter(rechnung=self.rechnung).exclude(pk=self.pk).order_by("-order").only("order")
        try:
            last_order = queryset[0].order
        except IndexError:
            # This is the first RechnungsPosten
            self.order = 1
        else:
            if last_order is None:
                self.order = 1
            else:
                self.order = last_order + 1

            request = ThreadLocal.get_current_request()
            if request: # also called from a management command
                messages.debug(request, "Auto add order numer %i to %r" % (self.order, self.beschreibung))
Example #46
0
    def save_record(self, auto_fields=dict(), **kwargs):
        if kwargs.get("datafile_ids", list()):
            datafile_ids = kwargs.get("datafile_ids")
            kwargs["bundle"] = datafile_ids

            # get the target repository from one of the files
            repo = DataFile().get_record_property(datafile_ids[0], "target_repository")
            for k, v in dict(
                    repository=repo,
                    status=False,
                    complete='false',
                    user_id=ThreadLocal.get_current_user().id,
            ).items():
                auto_fields[self.get_qualified_field(k)] = v

        return super(Submission, self).save_record(auto_fields, **kwargs)
Example #47
0
    def permalink(self, obj):
        """ view on site link in admin changelist, try to use complete uri with site info. """
        current_site = Site.objects.get_current()

        count = obj.sites.filter(id=current_site.id).count()
        if count == 0:
            # TODO: Create a link with the domain of the first site
            return u"<i>[not on current site]</i>"

        request = ThreadLocal.get_current_request()
        permalink = obj.get_permalink(request)
        if permalink is None:
            return u"<i>[no permalink available]</i>"

        context = {"permalink": permalink}
        html = render_to_string('admin/blog/permalink.html', context)
        return html
Example #48
0
def failsafe_message(msg, level=messages.INFO):
    """
    Display a message to the user.
    Use ThreadLocalMiddleware to get the current request object.
    If no request object is available, create a warning.
    """
    request = ThreadLocal.get_current_request()
    if request:
        # create a normal user message
        try:
            messages.add_message(request, level, msg)
        except Exception, err:
            # e.g.:
            # Without the django.contrib.messages middleware,
            # messages can only be added to authenticated users.
            msg += " (Error create a message: %s)" % err
        else:
            return
Example #49
0
 def add_personal_dataverse(self, url, name, apikey, type, username,
                            password):
     u = ThreadLocal.get_current_user()
     doc = self.get_collection_handle().insert({
         "isCG": False,
         "url": url,
         "name": name,
         "apikey": apikey,
         "personal": True,
         "uid": u.id,
         "type": type,
         "username": username,
         "password": password
     })
     udetails = u.userdetails
     udetails.repo_submitter.append(str(doc))
     udetails.save()
     return doc
Example #50
0
    def log_action(self,
                   app_label,
                   action,
                   request=None,
                   message=None,
                   long_message=None,
                   data=None):
        if request is None:
            request = ThreadLocal.get_current_request()

        kwargs = {
            "uri": request.build_absolute_uri(),
            "app_label": app_label,
            "action": action,
            "message": message,
            "long_message": long_message,
            "data": data,
        }

        if hasattr(request, "PYLUCID"):
            kwargs["used_language"] = request.PYLUCID.current_language
            preferences = request.PYLUCID.preferences  # Get SystemPreferences
        else:
            from pylucid_project.apps.pylucid.preference_forms import SystemPreferencesForm  # import loops
            preferences_form = SystemPreferencesForm()
            preferences = preferences_form.get_preferences()

        for key in META_KEYS:
            value = request.META.get(key)
            if value and len(value) > 255:
                value = "%s..." % value[:252]
            kwargs[key.lower()] = value

        new_entry = self.model(**kwargs)
        new_entry.save()

        # Auto cleanup Log Table to protect against overloading.
        max_count = preferences.get("max_log_entries", 1000)
        queryset = LogEntry.objects.order_by('-createtime')
        ids = tuple(queryset[max_count:].values_list('id', flat=True))
        if ids:
            queryset.filter(id__in=ids).delete()

        return new_entry
Example #51
0
    def check_sub_page_permissions(self, attributes, exclude, message_dict,
                                   queryset):
        """
        Warn user if PageTree permissions mismatch with sub pages.
        
        self.check_sub_page_permissions(
            ("permitViewGroup", "permitEditGroup"),
            exclude, message_dict, queryset
        )
        
        """
        request = ThreadLocal.get_current_request()
        if request is None:
            # Check only if we are in a request
            return

        attributes2 = []
        for attribute in attributes:
            if attribute not in exclude and attribute not in message_dict:
                # ...and don't check if ValidationError exist for this field
                attributes2.append(attribute)

        if not attributes2:
            return

        sub_pages = queryset.only(*attributes2)

        for attribute in attributes2:
            own_permission = getattr(self, attribute)
            for sub_page in sub_pages:
                sub_page_permission = getattr(sub_page, attribute)
                if sub_page_permission != own_permission:
                    msg = _(
                        "Permission mismatch:"
                        " current %(attribute)s is set to '%(own_permission)s'"
                        " and sub page '%(slug)s' used '%(sub_permission)s'."
                        " This may be ok.") % {
                            "slug": sub_page.get_absolute_url(),
                            "attribute": attribute,
                            "own_permission": own_permission,
                            "sub_permission": sub_page_permission,
                        }
                    messages.warning(request, msg)
Example #52
0
def get_client_ip(request=None):
    """
    A utility method that returns the client IP for the given request.
    """
    if not request:
        request = ThreadLocal.get_current_request()

    try:
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    except AttributeError:
        x_forwarded_for = None

    if x_forwarded_for:
        ipa = x_forwarded_for.split(',')[0]
    else:
        try:
            ipa = request.META.get('REMOTE_ADDR')
        except AttributeError:
            ipa = None
    return ipa
Example #53
0
    def get_preferences(self):
        """
        Fall back to initial data, if something wrong with system preferences.
        This is important, because nothing would work, if validation error raised.
        """
        try:
            return super(SystemPreferencesForm, self).get_preferences()
        except ValidationError, e:
            self.data = self.save_form_init()

            msg = 'Reset system preferences cause: %s' % e
            request = ThreadLocal.get_current_request()
            try:
                messages.info(request, msg)
            except MessageFailure:
                # If message system is not initialized, e.g.:
                # load the system preferences on module level
                warnings.warn(msg)

            return self.data
Example #54
0
    def get_absolute_uri(self):
        """ returned the complete absolute URI (with the domain/host part) """
        request = ThreadLocal.get_current_request()
        is_secure = request.is_secure()
        if is_secure:
            protocol = "https://"
        else:
            protocol = "http://"
        site = self.get_site()
        domain = site.domain

        if "://" in domain:
            domain2 = domain.split("://", 1)[-1]
            msg = ("Wrong site domain %r: protocol should not inserted there!"
                   " (Please change it to: %r)") % (domain, domain2)
            messages.error(request, msg)
            domain = domain2

        absolute_url = self.get_absolute_url()
        return protocol + domain + absolute_url
Example #55
0
    def recusive_attribute(self, attribute):
        """
        Goes the pagetree back to root and return the first match of attribute if not None.
        
        used e.g.
            with permitViewGroup and permitEditGroup
            from self.validate_permit_group() and self.check_sub_page_permissions()
        """
        parent_pagetree = self.pagetree.parent
        if parent_pagetree is None: # parent is the tree root
            return None

        request = ThreadLocal.get_current_request()
        if request is None:
            # Check only if we are in a request
            return

        queryset = PageMeta.objects.filter(pagetree=parent_pagetree)
        parent_pagemeta = None
        languages = request.PYLUCID.languages # languages are in client prefered order
        for language in languages:
            try:
                parent_pagemeta = queryset.get(language=language)
            except PageMeta.DoesNotExist:
                continue
            else:
                break

        if parent_pagemeta is None:
            return

        if getattr(parent_pagemeta, attribute) is not None:
            # the attribute was set by parent page
            return parent_pagemeta
        else:
            # go down to root
            return parent_pagemeta.recusive_attribute(attribute)
Example #56
0
    def _send(self, email_message):
        """ Force recipient to the current user."""
        request = ThreadLocal.get_current_request()

        try:
            request.user.is_authenticated()
            recipient = request.user.email
        except Exception:
            recipient = str(email_message.recipients()[0])
            if '+test' not in recipient:
                return False

        try:
            email_message.subject += ' || To: ' + \
                                     str(email_message.recipients()[0])
            message_string = email_message.message().as_string()

            self.connection.sendmail(email_message.from_email, recipient,
                                     message_string)
        except Exception:
            if not self.fail_silently:
                raise
            return False
        return True
Example #57
0
def get_base_url():
    r = ThreadLocal.get_current_request()
    scheme = r.scheme
    domain = r.get_host()
    return scheme + "://" + domain
Example #58
0
def get_current_request():
    return ThreadLocal.get_current_request()
Example #59
0
def get_current_user():
    if settings.UNIT_TESTING:
        return User.objects.get(username=settings.TEST_USER_NAME)
    else:
        return ThreadLocal.get_current_user()