Exemplo n.º 1
0
def verify_password(user, plaintext):
    """Check password of user, rehash if necessary.

    It is possible that the password is None, e.g. if the user is authenticated
    via LDAP. In this case default to "not verified".

    Args:
        user (dict): the user in question.
        plaintext (string): password to check

    Returns:
        bool: True if password matches. False if it doesn't or if there is no
            password set and/or provided.
    """
    password_context = app.config['PASSWORD_CONTEXT']

    if (plaintext is None) or (user['password'] is None):
        return False

    is_valid = password_context.verify(plaintext, user['password'])

    if is_valid and password_context.needs_update(user['password']):
        # update password - hook will handle hashing
        update = {'password': plaintext}
        with admin_permissions():
            patch_internal("users", payload=update, _id=user['_id'])
    return is_valid
Exemplo n.º 2
0
def verify_password(user, plaintext):
    """Check password of user, rehash if necessary.

    It is possible that the password is None, e.g. if the user is authenticated
    via LDAP. In this case default to "not verified".

    Args:
        user (dict): the user in question.
        plaintext (string): password to check

    Returns:
        bool: True if password matches. False if it doesn't or if there is no
            password set and/or provided.
    """
    password_context = app.config['PASSWORD_CONTEXT']

    if (plaintext is None) or (user['password'] is None):
        return False

    is_valid = password_context.verify(plaintext, user['password'])

    if is_valid and password_context.needs_update(user['password']):
        # update password - hook will handle hashing
        update = {'password': plaintext}
        with admin_permissions():
            patch_internal("users", payload=update, _id=user['_id'])
    return is_valid
Exemplo n.º 3
0
def cascade_delete(resource, item):
    """Cascade DELETE.

    Hook to delete all objects, which have the 'cascade_delete' option set
    in the data_relation and relate to the object, which was just deleted.
    """
    domain = current_app.config['DOMAIN']
    deleted_id = item[domain[resource]['id_field']]

    for res, res_domain in domain.items():
        # Filter schema of `res` to get all fields containing references
        # to the resource of the deleted item
        relations = ((field, field_def['data_relation'])
                     for field, field_def in res_domain['schema'].items()
                     if 'data_relation' in field_def and
                     field_def['data_relation'].get('resource') == resource)
        for field, data_relation in relations:
            # All items in `res` with reference to the deleted item
            lookup = {field: deleted_id}
            with admin_permissions():
                try:
                    if data_relation.get('cascade_delete'):
                        # Delete the item as well
                        deleteitem_internal(res, concurrency_check=False,
                                            **lookup)
                    else:
                        # Don't delete, only remove reference
                        patch_internal(res, payload={field: None},
                                       concurrency_check=False,
                                       **lookup)
                except NotFound:
                    pass
Exemplo n.º 4
0
def _create_or_update_user(ldap_data):
    """Try to find user in database. Update if it exists, create otherwise."""
    query = {'nethz': ldap_data['nethz']}
    db_data = current_app.data.driver.db['users'].find_one(query)

    with admin_permissions():
        if db_data:
            # Membership will not be downgraded and email not be overwritten
            ldap_data.pop('email', None)
            if db_data.get('membership') != u"none":
                ldap_data.pop('membership', None)

            user = patch_internal('users', ldap_data, _id=db_data['_id'])[0]
        else:
            user = post_internal('users', ldap_data)[0]

    return user
Exemplo n.º 5
0
def _create_or_update_user(ldap_data):
    """Try to find user in database. Update if it exists, create otherwise."""
    query = {'nethz': ldap_data['nethz']}
    db_data = current_app.data.driver.db['users'].find_one(query)

    with admin_permissions():
        if db_data:
            # Membership will not be downgraded and email not be overwritten
            # Newletter settings will also not be adjusted
            ldap_data.pop('email', None)
            ldap_data.pop('send_newsletter', None)
            if db_data.get('membership') != u"none":
                ldap_data.pop('membership', None)

            user = patch_internal('users',
                                  ldap_data,
                                  _id=db_data['_id'])[0]
        else:
            # For new members,

            user = post_internal('users', ldap_data)[0]

    return user
Exemplo n.º 6
0
    def load_fixture(self, fixture):
        """Load a dictionary as initial database state.

        Missing fields are filled in using defaults, or if not available with
        random values. Note that this describes post requests, so for example
        a session will need username and password, not user and token.

        Returns:
            A list of all created objects

        Example:
        self.load_fixture({
            'users': [
                {
                    'nethz': 'pablo',
                    'rfid': '132432'
                }
            ],
            'events': [
                {
                    'title': 'mytestevent'
                }
            ]
        })
        """
        added_objects = []

        # Check that all resources are valid
        fixture_resources = set(fixture.keys())
        all_resources = set(self.app.config['DOMAIN'].keys())
        if not set(fixture_resources).issubset(all_resources):
            raise BadFixtureException("Unknown resources: %s" %
                                      (fixture_resources - all_resources))

        # We need to sort in the order of dependencies. It is for example
        # not possible to add sessions before we have users, as we need valid
        # object IDs for the relations.
        for resource, obj in self.sorted_by_dependencies(fixture):
            schema = self.app.config['DOMAIN'][resource]['schema']

            # Note that we pass the current state of the fixture to resolve
            # fields, which depend on already inserted content
            self.preprocess_fixture_object(resource, schema, obj, fixture)

            # Add it to the database
            with self.app.test_request_context("/" + resource, method='POST'):
                with admin_permissions():
                    response, _, _, return_code, _ = post_internal(
                        resource, obj)
                if return_code != 201:
                    raise BadFixtureException(
                        "Fixture could not be loaded:\n"
                        "%s\nProblem was caused by:\n%s" %
                        (repr(response), obj))
            added_objects.append(response)

        # Check that everything went fine
        if len(added_objects) < sum([len(v) for v in fixture.values()]):
            raise BadFixtureException(
                "Not all objects in the fixture could be "
                "added! Check your dictionary!")

        return added_objects
Exemplo n.º 7
0
    def load_fixture(self, fixture):
        """Load a dictionary as initial database state.

        Missing fields are filled in using defaults, or if not available with
        random values. Note that this describes post requests, so for example
        a session will need username and password, not user and token.

        Returns:
            A list of all created objects

        Example:
        self.load_fixture({
            'users': [
                {
                    'nethz': 'pablo',
                    'rfid': '132432'
                }
            ],
            'events': [
                {
                    'title': 'mytestevent'
                }
            ]
        })
        """
        added_objects = []

        # Check that all resources are valid
        fixture_resources = set(fixture.keys())
        all_resources = set(self.app.config['DOMAIN'].keys())
        if not set(fixture_resources).issubset(all_resources):
            raise BadFixtureException("Unknown resources: %s"
                                      % (fixture_resources - all_resources))

        # We need to sort in the order of dependencies. It is for example
        # not possible to add sessions before we have users, as we need valid
        # object IDs for the relations.
        for resource, obj in self.sorted_by_dependencies(fixture):
            schema = self.app.config['DOMAIN'][resource]['schema']

            # Note that we pass the current state of the fixture to resolve
            # fields, which depend on already inserted content
            self.preprocess_fixture_object(resource, schema, obj, fixture)

            # Add it to the database
            with self.app.test_request_context("/" + resource, method='POST'):
                with admin_permissions(), self.writeable_id(schema):
                    response, _, _, return_code, _ = post_internal(resource,
                                                                   obj)
                if return_code != 201:
                    raise BadFixtureException("Fixture could not be loaded:\n"
                                              "%s\nProblem was caused by:\n%s"
                                              % (repr(response), obj))
            added_objects.append(response)

        # Check that everything went fine
        if len(added_objects) < sum([len(v) for v in fixture.values()]):
            raise BadFixtureException("Not all objects in the fixture could be "
                                      "added! Check your dictionary!")

        return added_objects