コード例 #1
0
ファイル: claim.py プロジェクト: msincan/juliabase
 def clean_samples(self):
     sample_names = self.cleaned_data["samples"].split(",")
     valid_names = []
     invalid_names = []
     for name in sample_names:
         name = name.strip()
         if name:
             if utils.sample_name_format(name) == "old":
                 if name in valid_names:
                     raise ValidationError(_("The name {name} appears more than once.").format(name=name))
                 valid_names.append(name)
             else:
                 invalid_names.append(name)
     if invalid_names:
         error_message = ungettext(
             "The name {invalid_names} is not valid.", "The names {invalid_names} are not valid.",
             len(invalid_names)).format(invalid_names=format_enumeration(invalid_names))
         raise ValidationError(error_message)
     if not valid_names:
         raise ValidationError(self.fields["samples"].error_messages["required"])
     existing_names = [name for name in valid_names if utils.does_sample_exist(name)]
     if existing_names:
         # This opens a small security hole because people can find out that
         # confidential samples are existing.  However, such samples mostly
         # have non-oldstyle names anyway.
         error_message = ungettext(
             "The name {existing_names} is already existing.", "The names {existing_names} are already existing.",
             len(existing_names)).format(existing_names=format_enumeration(existing_names))
         raise ValidationError(error_message)
     return valid_names
コード例 #2
0
ファイル: forms.py プロジェクト: muescha/juliabase
    def is_referentially_valid(self, samples_form):
        """Test whether the forms are consistent with each other and with the database.
        In its current form, it only checks whether the sample is still “alive”
        at the time of the measurement.

        :param samples_form: a bound samples selection form

        :type samples_form: `SampleSelectForm` or `MultipleSamplesSelectForm`

        :return:
          whether the forms are consistent with each other and the database

        :rtype: bool
        """
        referentially_valid = True
        if self.is_valid() and samples_form.is_valid():
            if isinstance(samples_form, SampleSelectForm):
                samples = [samples_form.cleaned_data["sample"]]
            else:
                samples = samples_form.cleaned_data["sample_list"]
            dead_samples_list = dead_samples(samples, self.cleaned_data["timestamp"])
            if dead_samples_list:
                samples_list = format_enumeration(dead_samples_list)
                self.add_error("timestamp", ValidationError(
                    ungettext_lazy("The sample {samples} is already dead at this time.",
                                   "The samples {samples} are already dead at this time.",
                                   len(dead_samples_list)), params={"samples": samples_list}, code="invalid"))
                referentially_valid = False
        return referentially_valid
コード例 #3
0
    def is_referentially_valid(self, samples_form):
        """Test whether the forms are consistent with each other and with the database.
        In its current form, it only checks whether the sample is still “alive”
        at the time of the measurement.

        :param samples_form: a bound samples selection form

        :type samples_form: `SampleSelectForm` or `MultipleSamplesSelectForm`

        :return:
          whether the forms are consistent with each other and the database

        :rtype: bool
        """
        referentially_valid = True
        if self.is_valid() and samples_form.is_valid():
            if isinstance(samples_form, SampleSelectForm):
                samples = [samples_form.cleaned_data["sample"]]
            else:
                samples = samples_form.cleaned_data["sample_list"]
            dead_samples_list = dead_samples(samples,
                                             self.cleaned_data["timestamp"])
            if dead_samples_list:
                samples_list = format_enumeration(dead_samples_list)
                self.add_error(
                    "timestamp",
                    ValidationError(ungettext_lazy(
                        "The sample {samples} is already dead at this time.",
                        "The samples {samples} are already dead at this time.",
                        len(dead_samples_list)),
                                    params={"samples": samples_list},
                                    code="invalid"))
                referentially_valid = False
        return referentially_valid
コード例 #4
0
ファイル: split_and_rename.py プロジェクト: colima/juliabase
 def clean_new_name(self):
     new_name = self.cleaned_data["new_name"]
     sample_name_format, match = sample_names.sample_name_format(
         new_name, with_match_object=True)
     if not sample_name_format:
         raise ValidationError(_("The sample name has an invalid format."),
                               code="invalid")
     elif not new_name.startswith(self.parent_name):
         if sample_name_format not in self.possible_new_name_formats:
             error_message = _(
                 "The new sample name must start with the parent sample's name."
             )
             params = {}
             if self.possible_new_name_formats:
                 further_error_message = ungettext(
                     "  Alternatively, it must be a valid “%(sample_formats)s” name.",
                     "  Alternatively, it must be a valid name of one of these types: "
                     "%(sample_formats)s",
                     len(self.possible_new_name_formats))
                 error_message += further_error_message
                 params.update({
                     "sample_formats":
                     format_enumeration(
                         sample_names.verbose_sample_name_format(
                             name_format)
                         for name_format in self.possible_new_name_formats)
                 })
             raise ValidationError(error_message,
                                   params=params,
                                   code="invalid")
         utils.check_sample_name(match, self.user)
     if sample_names.does_sample_exist(new_name):
         raise ValidationError(_("Name does already exist in database."),
                               code="duplicate")
     return new_name
コード例 #5
0
 def clean_new_name(self):
     new_name = self.cleaned_data["new_name"]
     sample_name_format, match = utils.sample_name_format(
         new_name, with_match_object=True)
     if not sample_name_format:
         raise ValidationError(_("The sample name has an invalid format."))
     elif not new_name.startswith(self.parent_name):
         if sample_name_format not in self.possible_new_name_formats:
             error_message = _(
                 "The new sample name must start with the parent sample's name."
             )
             if self.possible_new_name_formats:
                 further_error_message = ungettext(
                     "  Alternatively, it must be a valid “{sample_formats}” name.",
                     "  Alternatively, it must be a valid name of one of these types: "
                     "{sample_formats}",
                     len(self.possible_new_name_formats))
                 further_error_message = further_error_message.format(
                     sample_formats=format_enumeration(
                         utils.verbose_sample_name_format(name_format)
                         for name_format in self.possible_new_name_formats))
                 error_message += further_error_message
             raise ValidationError(error_message)
         utils.check_sample_name(match, self.user)
     if utils.does_sample_exist(new_name):
         raise ValidationError(_("Name does already exist in database."))
     return new_name
コード例 #6
0
    def is_referentially_valid(self):
        """Test whether all forms are consistent with each other and with the
        database.  For example, no layer number must occur twice, and the
        deposition number must not exist within the database.

        Note that we test many situations here that cannot be achieved with
        using the browser because all number fields are read-only and thus
        inherently referentially valid.  However, the remote client (or a
        manipulated HTTP client) may be used in a malicious way, thus we have
        to test for *all* cases.

        :return:
          whether all forms are consistent with each other and the database

        :rtype: bool
        """
        referentially_valid = super(DepositionView,
                                    self).is_referentially_valid()
        if not self.forms["layers"]:
            self.forms["process"].add_error(None, _("No layers given."))
            referentially_valid = False
        if self.forms["process"].is_valid():
            if self.forms["samples"].is_valid():
                dead_samples = utils.dead_samples(
                    self.forms["samples"].cleaned_data["sample_list"],
                    self.forms["process"].cleaned_data["timestamp"])
                if dead_samples:
                    error_message = ungettext(
                        "The sample {samples} is already dead at this time.",
                        "The samples {samples} are already dead at this time.",
                        len(dead_samples)).format(samples=format_enumeration(
                            [sample.name for sample in dead_samples]))
                    self.forms["process"].add_error("timestamp", error_message)
                    referentially_valid = False
        return referentially_valid
コード例 #7
0
 def clean_samples(self):
     sample_names = self.cleaned_data["samples"].split(",")
     valid_names = []
     invalid_names = []
     for name in sample_names:
         name = name.strip()
         if name:
             if sample_names.sample_name_format(name) == "old":
                 if name in valid_names:
                     raise ValidationError(
                         _("The name %(name)s appears more than once."),
                         params={"name": name},
                         code="invalid")
                 valid_names.append(name)
             else:
                 invalid_names.append(name)
     if invalid_names:
         error_message = ungettext(
             "The name %(invalid_names)s is not valid.",
             "The names %(invalid_names)s are not valid.",
             len(invalid_names))
         raise ValidationError(
             error_message,
             params={"invalid_names": format_enumeration(invalid_names)},
             code="invalid")
     if not valid_names:
         raise ValidationError(
             self.fields["samples"].error_messages["required"],
             code="required")
     existing_names = [
         name for name in valid_names
         if sample_names.does_sample_exist(name)
     ]
     if existing_names:
         # This opens a small security hole because people can find out that
         # confidential samples are existing.  However, such samples mostly
         # have non-oldstyle names anyway.
         error_message = ungettext(
             "The name %(existing_names)s is already existing.",
             "The names %(existing_names)s are already existing.",
             len(existing_names))
         raise ValidationError(
             error_message,
             params={"existing_names": format_enumeration(existing_names)},
             code="duplicate")
     return valid_names
コード例 #8
0
ファイル: sample.py プロジェクト: muescha/juliabase
def show(request, sample_name):
    """A view for showing existing samples.

    :param request: the current HTTP Request object
    :param sample_name: the name of the sample

    :type request: HttpRequest
    :type sample_name: unicode

    :return:
      the HTTP response object

    :rtype: HttpResponse
    """
    start = time.time()
    if request.method == "POST":
        samples_and_processes = SamplesAndProcesses.samples_and_processes(sample_name, request.user, request.POST)
        if samples_and_processes.is_valid():
            added, removed = samples_and_processes.save_to_database()
            if is_json_requested(request):
                return respond_in_json(True)
            if added:
                success_message = ungettext("Sample {samples} was added to My Samples.",
                                            "Samples {samples} were added to My Samples.",
                                            len(added)).format(samples=format_enumeration(added))
            else:
                success_message = ""
            if removed:
                if added:
                    success_message += "  "
                success_message += ungettext("Sample {samples} was removed from My Samples.",
                                             "Samples {samples} were removed from My Samples.",
                                             len(removed)).format(samples=format_enumeration(removed))
            elif not added:
                success_message = _("Nothing was changed.")
            messages.success(request, success_message)
    else:
        if is_json_requested(request):
            sample = utils.lookup_sample(sample_name, request.user)
            return respond_in_json(sample.get_data())
        samples_and_processes = SamplesAndProcesses.samples_and_processes(sample_name, request.user)
    messages.debug(request, "DB-Zugriffszeit: {0:.1f} ms".format((time.time() - start) * 1000))
    return render(request, "samples/show_sample.html",
                  {"title": _("Sample “{sample}”").format(sample=samples_and_processes.sample_context["sample"]),
                   "samples_and_processes": samples_and_processes})
コード例 #9
0
ファイル: bulk_rename.py プロジェクト: msincan/juliabase
 def clean_name(self):
     new_name = self.prefix_ + self.cleaned_data["name"]
     name_format, match = utils.sample_name_format(new_name, with_match_object=True)
     if name_format not in self.possible_new_name_formats:
         error_message = ungettext("New name must be a valid “{sample_formats}” name.",
                                   "New name must be a valid name of one of these types: {sample_formats}",
                                   len(self.possible_new_name_formats))
         error_message = error_message.format(sample_formats=format_enumeration(
             utils.verbose_sample_name_format(name_format) for name_format in self.possible_new_name_formats))
         raise ValidationError(error_message)
     utils.check_sample_name(match, self.user)
     if utils.does_sample_exist(new_name):
         raise ValidationError(_("This sample name exists already."))
     return new_name
コード例 #10
0
 def clean_name(self):
     new_name = self.prefix_ + self.cleaned_data["name"]
     name_format, match = utils.sample_name_format(new_name, with_match_object=True)
     if name_format not in self.possible_new_name_formats:
         error_message = ungettext("New name must be a valid “{sample_formats}” name.",
                                   "New name must be a valid name of one of these types: {sample_formats}",
                                   len(self.possible_new_name_formats))
         error_message = error_message.format(sample_formats=format_enumeration(
             utils.verbose_sample_name_format(name_format) for name_format in self.possible_new_name_formats))
         raise ValidationError(error_message)
     utils.check_sample_name(match, self.user)
     if utils.does_sample_exist(new_name):
         raise ValidationError(_("This sample name exists already."))
     return new_name
コード例 #11
0
ファイル: bulk_rename.py プロジェクト: muescha/juliabase
 def clean_name(self):
     new_name = self.prefix_ + self.cleaned_data["name"]
     name_format, match = sample_names.sample_name_format(new_name, with_match_object=True)
     if name_format not in self.possible_new_name_formats:
         error_message = ungettext("New name must be a valid “%(sample_formats)s” name.",
                                   "New name must be a valid name of one of these types: %(sample_formats)s.",
                                   len(self.possible_new_name_formats))
         raise ValidationError(error_message,
             params={"sample_formats": format_enumeration(
                 sample_names.verbose_sample_name_format(name_format) for name_format in self.possible_new_name_formats)},
             code="invalid")
     utils.check_sample_name(match, self.user)
     if sample_names.does_sample_exist(new_name):
         raise ValidationError(_("This sample name exists already."), code="duplicate")
     return new_name
コード例 #12
0
 def clean(self):
     cleaned_data = super(OriginalDataForm, self).clean()
     if "new_name" in cleaned_data:
         new_name = cleaned_data["new_name"]
         sample = cleaned_data.get("sample")
         if sample and not sample_names.valid_new_sample_name(sample.name, new_name) and \
            not new_name.startswith(sample.name):
             error_message = _("The new name must begin with the old name.")
             params = {}
             old_sample_name_format = sample_names.sample_name_format(sample.name)
             possible_new_name_formats = \
                     settings.SAMPLE_NAME_FORMATS[old_sample_name_format].get("possible_renames", set())
             if possible_new_name_formats:
                 error_message += ungettext("  Alternatively, it must be a valid “%(sample_formats)s” name.",
                                            "  Alternatively, it must be a valid name of one of these types: "
                                            "%(sample_formats)s.", len(possible_new_name_formats))
                 params.update({"sample_formats": format_enumeration(
                     sample_names.verbose_sample_name_format(name_format) for name_format in possible_new_name_formats)})
             if sample_names.valid_new_sample_name(sample.name, self.deposition_number):
                 error_message += _("  Or, the new name must be or begin with the deposition number.")
             self.add_error("new_name", ValidationError(error_message, params=params, code="invalid"))
     return cleaned_data
コード例 #13
0
ファイル: split_and_rename.py プロジェクト: muescha/juliabase
 def clean_new_name(self):
     new_name = self.cleaned_data["new_name"]
     sample_name_format, match = sample_names.sample_name_format(new_name, with_match_object=True)
     if not sample_name_format:
         raise ValidationError(_("The sample name has an invalid format."), code="invalid")
     elif not new_name.startswith(self.parent_name):
         if sample_name_format not in self.possible_new_name_formats:
             error_message = _("The new sample name must start with the parent sample's name.")
             params = {}
             if self.possible_new_name_formats:
                 further_error_message = ungettext("  Alternatively, it must be a valid “%(sample_formats)s” name.",
                                                   "  Alternatively, it must be a valid name of one of these types: "
                                                   "%(sample_formats)s", len(self.possible_new_name_formats))
                 error_message += further_error_message
                 params.update({"sample_formats": format_enumeration(
                     sample_names.verbose_sample_name_format(name_format)
                     for name_format in self.possible_new_name_formats)})
             raise ValidationError(error_message, params=params, code="invalid")
         utils.check_sample_name(match, self.user)
     if sample_names.does_sample_exist(new_name):
         raise ValidationError(_("Name does already exist in database."), code="duplicate")
     return new_name
コード例 #14
0
 def clean_name(self):
     new_name = self.prefix_ + self.cleaned_data["name"]
     name_format, match = sample_names.sample_name_format(
         new_name, with_match_object=True)
     if name_format not in self.possible_new_name_formats:
         error_message = ungettext(
             "New name must be a valid “%(sample_formats)s” name.",
             "New name must be a valid name of one of these types: %(sample_formats)s.",
             len(self.possible_new_name_formats))
         raise ValidationError(
             error_message,
             params={
                 "sample_formats":
                 format_enumeration(
                     sample_names.verbose_sample_name_format(name_format)
                     for name_format in self.possible_new_name_formats)
             },
             code="invalid")
     utils.check_sample_name(match, self.user)
     if sample_names.does_sample_exist(new_name):
         raise ValidationError(_("This sample name exists already."),
                               code="duplicate")
     return new_name
コード例 #15
0
ファイル: split_and_rename.py プロジェクト: msincan/juliabase
 def clean_new_name(self):
     new_name = self.cleaned_data["new_name"]
     sample_name_format, match = utils.sample_name_format(new_name, with_match_object=True)
     if not sample_name_format:
         raise ValidationError(_("The sample name has an invalid format."))
     elif not new_name.startswith(self.parent_name):
         if sample_name_format not in self.possible_new_name_formats:
             error_message = _("The new sample name must start with the parent sample's name.")
             if self.possible_new_name_formats:
                 further_error_message = ungettext("  Alternatively, it must be a valid “{sample_formats}” name.",
                                                   "  Alternatively, it must be a valid name of one of these types: "
                                                   "{sample_formats}", len(self.possible_new_name_formats))
                 further_error_message = further_error_message.format(sample_formats=format_enumeration(
                     utils.verbose_sample_name_format(name_format) for name_format in self.possible_new_name_formats))
                 error_message += further_error_message
             raise ValidationError(error_message)
         utils.check_sample_name(match, self.user)
     if utils.does_sample_exist(new_name):
         raise ValidationError(_("Name does already exist in database."))
     return new_name
コード例 #16
0
ファイル: my_samples.py プロジェクト: colima/juliabase
def is_referentially_valid(current_user, my_samples_form, action_form):
    """Test whether all forms are consistent with each other and with the
    database.  For example, you must not change data for samples for which
    you're not the currently responsible person.

    :param current_user: the currently logged-in user
    :param my_samples_form: the form with the selected “My Samples”
    :param action_form: the form with the things to be done with the selected
        samples.

    :type current_user: django.contrib.auth.models.User
    :type my_samples_form: `MySamplesForm`
    :type action_form: `ActionForm`

    :return:
      whether all forms are consistent with each other and the database

    :rtype: bool
    """
    referentially_valid = True
    if my_samples_form.is_valid() and action_form.is_valid():
        action_data = action_form.cleaned_data
        if not current_user.is_superuser:
            if action_data["new_currently_responsible_person"] or action_data["new_topic"] or \
                        action_data["new_current_location"]:
                try:
                    for sample in my_samples_form.cleaned_data["samples"]:
                        permissions.assert_can_edit_sample(
                            current_user, sample)
                except permissions.PermissionError:
                    action_form.add_error(
                        None,
                        ValidationError(_(
                            "You must be the currently responsible person for samples you'd like to change "
                            "or the topic manager of the samples topics."),
                                        code="forbidden"))
                    referentially_valid = False
        if action_data["clearance"] is None and action_data["copy_to_user"]:
            try:
                action_data["copy_to_user"] = list(action_data["copy_to_user"])
                action_data["copy_to_user"].remove(
                    action_data["new_currently_responsible_person"])
            except ValueError:
                pass
            try:
                for sample in my_samples_form.cleaned_data["samples"]:
                    for user in action_data["copy_to_user"]:
                        permissions.assert_can_fully_view_sample(user, sample)
            except permissions.PermissionError:
                action_form.add_error(
                    "clearance",
                    ValidationError(_(
                        "If you copy samples over to another person who cannot fully view one of the "
                        "samples, you must select a clearance option."),
                                    code="required"))
                referentially_valid = False
        if action_data.get("clearance") is not None:
            failed_samples = []
            for sample in my_samples_form.cleaned_data["samples"]:
                try:
                    permissions.get_sample_clearance(current_user, sample)
                except permissions.PermissionError:
                    failed_samples.append(sample)
            if failed_samples:
                my_samples_form.add_error(
                    "samples",
                    ValidationError(_(
                        "You cannot grant clearances for the following samples: %(failed_samples)s"
                    ),
                                    params={
                                        "failed_samples":
                                        format_enumeration(failed_samples)
                                    },
                                    code="forbidden"))
                referentially_valid = False
    return referentially_valid
コード例 #17
0
ファイル: my_samples.py プロジェクト: muescha/juliabase
def is_referentially_valid(current_user, my_samples_form, action_form):
    """Test whether all forms are consistent with each other and with the
    database.  For example, you must not change data for samples for which
    you're not the currently responsible person.

    :param current_user: the currently logged-in user
    :param my_samples_form: the form with the selected “My Samples”
    :param action_form: the form with the things to be done with the selected
        samples.

    :type current_user: django.contrib.auth.models.User
    :type my_samples_form: `MySamplesForm`
    :type action_form: `ActionForm`

    :return:
      whether all forms are consistent with each other and the database

    :rtype: bool
    """
    referentially_valid = True
    if my_samples_form.is_valid() and action_form.is_valid():
        action_data = action_form.cleaned_data
        if not current_user.is_superuser:
            if action_data["new_currently_responsible_person"] or action_data["new_topic"] or \
                        action_data["new_current_location"]:
                try:
                    for sample in my_samples_form.cleaned_data["samples"]:
                        permissions.assert_can_edit_sample(current_user, sample)
                except permissions.PermissionError:
                    action_form.add_error(None, ValidationError(
                        _("You must be the currently responsible person for samples you'd like to change "
                          "or the topic manager of the samples topics."), code="forbidden"))
                    referentially_valid = False
        if action_data["clearance"] is None and action_data["copy_to_user"]:
            try:
                action_data["copy_to_user"] = list(action_data["copy_to_user"])
                action_data["copy_to_user"].remove(action_data["new_currently_responsible_person"])
            except ValueError:
                pass
            try:
                for sample in my_samples_form.cleaned_data["samples"]:
                    for user in action_data["copy_to_user"]:
                        permissions.assert_can_fully_view_sample(user, sample)
            except permissions.PermissionError:
                action_form.add_error("clearance", ValidationError(
                    _("If you copy samples over to another person who cannot fully view one of the "
                      "samples, you must select a clearance option."), code="required"))
                referentially_valid = False
        if action_data.get("clearance") is not None:
            failed_samples = []
            for sample in my_samples_form.cleaned_data["samples"]:
                try:
                    permissions.get_sample_clearance(current_user, sample)
                except permissions.PermissionError:
                    failed_samples.append(sample)
            if failed_samples:
                my_samples_form.add_error("samples", ValidationError(
                    _("You cannot grant clearances for the following samples: %(failed_samples)s"),
                    params={"failed_samples": format_enumeration(failed_samples)}, code="forbidden"))
                referentially_valid = False
    return referentially_valid