How to use the girder.exceptions.ValidationException function in girder

To help you get started, we’ve selected a few girder examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github girder / girder / girder / models / model_base.py View on Github external
included from the document, or dict for an inclusion or exclusion
            projection`.
        :type fields: `str, list, set, or tuple`
        :param exc: Whether to raise a ValidationException if there is no
                    document with the given id.
        :type exc: bool
        :returns: The matching document, or None.
        """
        if not id:
            raise ValidationException('Attempt to load null ObjectId: %s' % id)

        if objectId and not isinstance(id, ObjectId):
            try:
                id = ObjectId(id)
            except InvalidId:
                raise ValidationException('Invalid ObjectId: %s' % id,
                                          field='id')
        doc = self.findOne({'_id': id}, fields=fields)

        if doc is None and exc is True:
            raise ValidationException('No such %s: %s' % (self.name, id),
                                      field='id')

        return doc
github girder / girder / girder / models / user.py View on Github external
cur_config = config.getConfig()

        if 'salt' not in doc:  # pragma: no cover
            # Internal error, this should not happen
            raise Exception('Tried to save user document with no salt.')

        if not doc['firstName']:
            raise ValidationException('First name must not be empty.',
                                      'firstName')

        if not doc['lastName']:
            raise ValidationException('Last name must not be empty.',
                                      'lastName')

        if doc['status'] not in ('pending', 'enabled', 'disabled'):
            raise ValidationException(
                'Status must be pending, enabled, or disabled.', 'status')

        if '@' in doc['login']:
            # Hard-code this constraint so we can always easily distinguish
            # an email address from a login
            raise ValidationException('Login may not contain "@".', 'login')

        if not re.match(cur_config['users']['login_regex'], doc['login']):
            raise ValidationException(
                cur_config['users']['login_description'], 'login')

        if not re.match(cur_config['users']['email_regex'], doc['email']):
            raise ValidationException('Invalid email address.', 'email')

        # Ensure unique logins
        q = {'login': doc['login']}
github girder / girder / girder / settings.py View on Github external
def _validateRouteTable(doc):
        nonEmptyRoutes = [route for route in doc['value'].values() if route]
        if GIRDER_ROUTE_ID not in doc['value'] or not doc['value'][GIRDER_ROUTE_ID]:
            raise ValidationException('Girder root must be routable.', 'value')

        for key in doc['value']:
            if (doc['value'][key] and not doc['value'][key].startswith('/')):
                raise ValidationException('Routes must begin with a forward slash.', 'value')

        if len(nonEmptyRoutes) > len(set(nonEmptyRoutes)):
            raise ValidationException('Routes must be unique.', 'value')
github girder / girder / girder / models / password.py View on Github external
:param user: The user document.
        :type user: dict
        :param password: The attempted password.
        :type password: str
        :returns: Whether authentication succeeded (bool).
        """
        if not self.hasPassword(user):
            e = events.trigger('no_password_login_attempt', {
                'user': user,
                'password': password
            })

            if len(e.responses):
                return e.responses[-1]

            raise ValidationException(
                'This user does not have a password. You must log in with an '
                'external service, or reset your password.')

        hash = self._digest(salt=user['salt'], alg=user['hashAlg'],
                            password=password)

        if user['hashAlg'] == 'bcrypt':
            if isinstance(user['salt'], six.text_type):
                user['salt'] = user['salt'].encode('utf8')
            return hash == user['salt']
        else:
            return self.load(hash, False) is not None
github girder / large_image / girder_annotation / girder_large_image_annotation / __init__.py View on Github external
def validateBoolean(doc):
    val = doc['value']
    if str(val).lower() not in ('false', 'true', ''):
        raise ValidationException('%s must be a boolean.' % doc['key'], 'value')
    doc['value'] = (str(val).lower() != 'false')
github girder / girder / girder / models / model_base.py View on Github external
def validateKeys(self, keys):
        """
        Validate a set of keys to make sure they are able to be used in the
        database. This enforces MongoDB rules about key names.
        @TODO Add recurse=True argument if ``keys`` is a dict.

        :param keys: An iterable of keys to validate.
        :type keys: iterable
        :raises: ValidationException
        """
        for k in keys:
            if not k:
                raise ValidationException('Key names must not be empty.')
            if '.' in k:
                raise ValidationException(
                    'Invalid key %s: keys must not contain the "." character.' % k)
            if k[0] == '$':
                raise ValidationException(
                    'Invalid key %s: keys must not start with the "$" character.' % k)
github girder / girder / plugins / jobs / girder_jobs / models / job.py View on Github external
def _validateChild(self, parentJob, childJob):
        if str(parentJob['_id']) == str(childJob['_id']):
            raise ValidationException('Child Id cannot be equal to Parent Id')
        if childJob['parentId']:
            raise ValidationException('Cannot overwrite the Parent Id')
github girder / girder / plugins / item_tasks / girder_item_tasks / rest.py View on Github external
})

        if len(event.responses):
            spec = event.responses[-1]

        if event.defaultPrevented:
            return spec, handler

        if not isinstance(spec, dict):
            raise ValidationException('Task spec should be a JSON object.')

        inputs = spec.get('inputs', [])
        outputs = spec.get('outputs', [])

        if not isinstance(inputs, (list, tuple)):
            raise ValidationException('Task inputs must be a list.')

        if not isinstance(outputs, (list, tuple)):
            raise ValidationException('Task outputs must be a list.')

        if 'mode' not in spec:
            raise ValidationException('Task must contain a "mode" field.')

        # Ensure that format and type keys exist in every task IO spec,
        # the worker complains otherwise.
        for ioSpec in inputs + outputs:
            ioSpec['format'] = ioSpec.get('format', 'none')
            ioSpec['type'] = ioSpec.get('type', 'none')

        return spec, handler
github girder / large_image / girder / girder_large_image / girder_tilesource.py View on Github external
pass
                if not largeImagePath:
                    try:
                        largeImagePath = File().getGirderMountFilePath(largeImageFile)
                    except FilePathException:
                        pass
            if not largeImagePath:
                try:
                    largeImagePath = File().getLocalFilePath(largeImageFile)
                except AttributeError as e:
                    raise TileSourceException(
                        'No local file path for this file: %s' % e.args[0])
            return largeImagePath
        except (TileSourceAssetstoreException, FilePathException):
            raise
        except (KeyError, ValidationException, TileSourceException) as e:
            raise TileSourceException(
                'No large image file in this item: %s' % e.args[0])
github girder / girder / girder / settings.py View on Github external
def _validateCorsExposeHeaders(doc):
        if not isinstance(doc['value'], six.string_types):
            raise ValidationException('CORS exposed headers must be a string', 'value')