Beispiel #1
0
def validate_subject_hierarchy(subject_hierarchy):
    validated_hierarchy, raw_hierarchy = [], set(subject_hierarchy)
    for subject_id in subject_hierarchy:
        subject = Subject.load(subject_id)
        if not subject:
            raise ValidationValueError(
                'Subject with id <{}> could not be found.'.format(subject_id))

        if subject.parents:
            continue

        raw_hierarchy.remove(subject_id)
        validated_hierarchy.append(subject._id)

        while raw_hierarchy:
            if not set([c._id for c in subject.children]) & raw_hierarchy:
                raise ValidationValueError(
                    'Invalid subject hierarchy: {}'.format(subject_hierarchy))
            else:
                for child in subject.children:
                    if child._id in raw_hierarchy:
                        subject = child
                        validated_hierarchy.append(child._id)
                        raw_hierarchy.remove(child._id)
                        break
        if set(validated_hierarchy) == set(subject_hierarchy):
            return
        else:
            raise ValidationValueError(
                'Invalid subject hierarchy: {}'.format(subject_hierarchy))
    raise ValidationValueError(
        'Unable to find root subject in {}'.format(subject_hierarchy))
Beispiel #2
0
def validate_subject_hierarchy(subject_hierarchy):
    validated_hierarchy, raw_hierarchy = [], set(subject_hierarchy)
    for subject_id in subject_hierarchy:
        subject = Subject.load(subject_id)
        if not subject:
            raise ValidationValueError(
                'Subject with id <{}> could not be found.'.format(subject_id))

        if subject.parents.exists():
            continue

        raw_hierarchy.remove(subject_id)
        validated_hierarchy.append(subject._id)

        while raw_hierarchy:
            if not set(subject.children.values_list(
                    '_id', flat=True)) & raw_hierarchy:
                raise ValidationValueError(
                    'Invalid subject hierarchy: {}'.format(subject_hierarchy))
            else:
                for child in subject.children.filter(_id__in=raw_hierarchy):
                    subject = child
                    validated_hierarchy.append(child._id)
                    raw_hierarchy.remove(child._id)
                    break
        if set(validated_hierarchy) == set(subject_hierarchy):
            return
        else:
            raise ValidationValueError(
                'Invalid subject hierarchy: {}'.format(subject_hierarchy))
    raise ValidationValueError(
        'Unable to find root subject in {}'.format(subject_hierarchy))
Beispiel #3
0
def validate_contributor(guid, contributors):
    OSFUser = apps.get_model('osf.OSFUser')
    user = OSFUser.load(guid)
    if not user or not user.is_claimed:
        raise ValidationValueError('User does not exist or is not active.')
    elif user not in contributors:
        raise ValidationValueError('Mentioned user is not a contributor.')
    return True
Beispiel #4
0
def validate_year(item):
    if item:
        try:
            int(item)
        except ValueError:
            raise ValidationValueError('Please enter a valid year.')
        else:
            if len(item) != 4:
                raise ValidationValueError('Please enter a valid year.')
def _validate_reports(value, *args, **kwargs):
    for key, val in value.iteritems():
        if not User.load(key):
            raise ValidationValueError('Keys must be user IDs')
        if not isinstance(val, dict):
            raise ValidationTypeError('Values must be dictionaries')
        if ('category' not in val or 'text' not in val or 'date' not in val
                or 'retracted' not in val):
            raise ValidationValueError(
                ('Values must include `date`, `category`, ',
                 '`text`, `retracted` keys'))
Beispiel #6
0
def validate_history_item(item):
    string_required(item.get('institution'))
    startMonth = item.get('startMonth')
    startYear = item.get('startYear')
    endMonth = item.get('endMonth')
    endYear = item.get('endYear')
    if startYear and endYear:
        if endYear < startYear:
            raise ValidationValueError('End date must be later than start date.')
        elif endYear == startYear:
            if endMonth and startMonth and endMonth < startMonth:
                raise ValidationValueError('End date must be later than start date.')
Beispiel #7
0
def validate_location(value):
    if value is None:
        return  # Allow for None locations but not broken dicts
    from website.addons.osfstorage import settings
    for key in ('service', settings.WATERBUTLER_RESOURCE, 'object'):
        if key not in value:
            raise ValidationValueError('Location {} missing key "{}"'.format(value, key))
Beispiel #8
0
def validate_title(value):
    """Validator for Node#title. Makes sure that the value exists and is not
    above 200 characters.
    """
    if value is None or not value.strip():
        raise ValidationValueError('Title cannot be blank.')

    value = sanitize.strip_html(value)

    if value is None or not value.strip():
        raise ValidationValueError('Invalid title.')

    if len(value) > 200:
        raise ValidationValueError('Title cannot exceed 200 characters.')

    return True
Beispiel #9
0
    def validator(value):
        reduced_comment = mention_re.sub(link_repl, value)

        # two characters accounts for the \r\n at the end of comments
        if len(reduced_comment) > max_length + 2:
            raise ValidationValueError('Ensure this field has no more than {} characters.'.format(max_length))
        return True
Beispiel #10
0
def new_private_link(name, user, nodes, anonymous):
    """Create a new private link.

    :param str name: private link name
    :param User user: User object
    :param list Node node: a list of node object
    :param bool anonymous: make link anonymous or not
    :return PrivateLink: Created private link

    """
    key = str(uuid.uuid4()).replace('-', '')
    if name:
        name = strip_html(name)
        if name is None or not name.strip():
            raise ValidationValueError('Invalid link name.')
    else:
        name = 'Shared project link'

    private_link = PrivateLink(key=key,
                               name=name,
                               creator=user,
                               nodes=nodes,
                               anonymous=anonymous)

    private_link.save()

    return private_link
Beispiel #11
0
def validate_user(value):
    OSFUser = apps.get_model('osf.OSFUser')
    if value != {}:
        user_id = value.iterkeys().next()
        if OSFUser.find(Q('_id', 'eq', user_id)).count() != 1:
            raise ValidationValueError('User does not exist.')
    return True
Beispiel #12
0
def validate_category(value):
    """Validator for Node#category. Makes sure that the value is one of the
    categories defined in NODE_CATEGORY_MAP.
    """
    if value not in settings.NODE_CATEGORY_MAP.keys():
        raise ValidationValueError('Invalid value for category.')
    return True
Beispiel #13
0
    def validator(value):

        if not isinstance(value, collections.Hashable):
            raise ValidationError('Must specify a single choice; value cannot be a collection')
        if ignore_case and isinstance(value, basestring):
            value = value.upper()

        if value in choice_set:
            return True
        else:
            raise ValidationValueError('Value must be one of these options: {}'.format(choices))
Beispiel #14
0
def new_private_link(name, user, nodes, anonymous):
    """Create a new private link.

    :param str name: private link name
    :param User user: User object
    :param list Node node: a list of node object
    :param bool anonymous: make link anonymous or not
    :return PrivateLink: Created private link

    """
    PrivateLink = apps.get_model('osf.PrivateLink')
    NodeLog = apps.get_model('osf.NodeLog')

    key = str(uuid.uuid4()).replace('-', '')
    if name:
        name = strip_html(name)
        if name is None or not name.strip():
            raise ValidationValueError('Invalid link name.')
    else:
        name = 'Shared project link'

    private_link = PrivateLink(key=key,
                               name=name,
                               creator=user,
                               anonymous=anonymous)

    private_link.save()

    private_link.nodes.add(*nodes)

    auth = Auth(user)
    for node in nodes:
        log_dict = {
            'project': node.parent_id,
            'node': node._id,
            'user': user._id,
            'anonymous_link': anonymous,
        }

        node.add_log(NodeLog.VIEW_ONLY_LINK_ADDED, log_dict, auth=auth)

    private_link.save()

    return private_link
Beispiel #15
0
def string_required(value):
    if value is None or value == '':
        raise ValidationValueError('Value must not be empty.')
Beispiel #16
0
def deserialize_contributors(node, user_dicts, auth, validate=False):
    """View helper that returns a list of User objects from a list of
    serialized users (dicts). The users in the list may be registered or
    unregistered users.

    e.g. ``[{'id': 'abc123', 'registered': True, 'fullname': ..},
            {'id': None, 'registered': False, 'fullname'...},
            {'id': '123ab', 'registered': False, 'fullname': ...}]

    If a dict represents an unregistered user without an ID, creates a new
    unregistered User record.

    :param Node node: The node to add contributors to
    :param list(dict) user_dicts: List of serialized users in the format above.
    :param Auth auth:
    :param bool validate: Whether to validate and sanitize fields (if necessary)
    """

    # Add the registered contributors
    contribs = []
    for contrib_dict in user_dicts:
        fullname = contrib_dict['fullname']
        visible = contrib_dict['visible']
        email = contrib_dict.get('email')

        if validate is True:
            # Validate and sanitize inputs as needed. Email will raise error if invalid.
            # TODO Edge case bug: validation and saving are performed in same loop, so all in list
            # up to the invalid entry will be saved. (communicate to the user what needs to be retried)
            fullname = sanitize.strip_html(fullname)
            if not fullname:
                raise ValidationValueError('Full name field cannot be empty')
            if email is not None:
                validate_email(
                    email)  # Will raise a ValidationError if email invalid

        if contrib_dict['id']:
            contributor = User.load(contrib_dict['id'])
        else:
            try:
                contributor = User.create_unregistered(fullname=fullname,
                                                       email=email)
                contributor.save()
            except ValidationValueError:
                ## FIXME: This suppresses an exception if ID not found & new validation fails; get_user will return None
                contributor = get_user(email=email)

        # Add unclaimed record if necessary
        if (not contributor.is_registered
                and node._primary_key not in contributor.unclaimed_records):
            contributor.add_unclaimed_record(node=node,
                                             referrer=auth.user,
                                             given_name=fullname,
                                             email=email)
            contributor.save()
            unreg_contributor_added.send(node,
                                         contributor=contributor,
                                         auth=auth)

        contribs.append({
            'user':
            contributor,
            'visible':
            visible,
            'permissions':
            expand_permissions(contrib_dict.get('permission'))
        })
    return contribs
Beispiel #17
0
 def __call__(self, value):
     cleaned = self.clean(value)
     params = {'limit_value': self.limit_value, 'show_value': cleaned}
     if self.compare(cleaned, self.limit_value):
         raise ValidationValueError(self.message.format(**params))
Beispiel #18
0
def sanitized(value):
    if value != sanitize_pattern.sub('', value):
        raise ValidationValueError('Unsanitary string')
Beispiel #19
0
def validate_circular_reference(schema, instance):
    """Prevent node from forwarding to itself."""
    if instance.url and instance.owner._id in instance.url:
        raise ValidationValueError('Circular URL')
Beispiel #20
0
def validate_doi(value):
    if value and not re.match(
            r'\b(10\.\d{4,}(?:\.\d+)*/\S+(?:(?!["&\'<>])\S))\b', value):
        raise ValidationValueError('"{}" is not a valid DOI'.format(value))
    return True