Ejemplo n.º 1
0
    def before_search(self, data_dict):
        if toolkit.get_endpoint() == ('organization', 'read'):

            data_dict['fq'] = RE_ORG_FQ.sub(
                _id_expander,
                data_dict.get('fq', ''),
            )

        return data_dict
Ejemplo n.º 2
0
def hierarchy_enable_tree_search():
    if not tk.request:
        return False
    endpoint = ".".join(tk.get_endpoint())
    supported_endpoints = tk.aslist(
        tk.config.get(
            CONFIG_TREE_SEARCH_EDNPOINTS, DEFAULT_TREE_SEARCH_ENDPOINTS
        )
    )
    return endpoint in supported_endpoints
def user_password_validator(key, data, errors, context):
    # Don't perform this validation under certain conditions, i.e. adding a new member to an organisation
    blueprint, action = get_endpoint()
    if get_endpoint()[0] in ['organization'
                             ] and get_endpoint()[1] in ['member_new']:
        return

    value = data[key]

    if isinstance(value, Missing):
        pass  # Already handled in core
    elif not isinstance(value, string_types):
        errors[('password', )].append(_('Passwords must be strings'))
    elif value == '':
        pass  # Already handled in core
    else:
        if user_password_has_repeated_chars(value):
            errors[('password', )].append(_(REPEATING_CHAR_ERROR))
        if user_password_noncompliant(value):
            errors[('password', )].append(
                _(MIN_LEN_ERROR.format(MIN_PASSWORD_LENGTH)))
def _check_group_auth(context, data_dict):
    ''' Copied from ckan.logic.auth.create._check_group_auth
        Has this user got update permission for all of the given groups?
        If there is a package in the context then ignore that package's groups.
        (owner_org is checked elsewhere.)
        :returns: False if not allowed to update one (or more) of the given groups.
                True otherwise. i.e. True is the default. A blank data_dict
                mentions no groups, so it returns True.
    '''
    # FIXME This code is shared amoung other logic.auth files and should be
    # somewhere better
    if not data_dict:
        return True

    model = context['model']
    user = context['user']
    pkg = context.get("package")

    api_version = context.get('api_version') or '1'

    group_blobs = data_dict.get('groups', [])
    groups = set()
    for group_blob in group_blobs:
        # group_blob might be a dict or a group_ref
        if isinstance(group_blob, dict):
            # use group id by default, but we can accept name as well
            id = group_blob.get('id') or group_blob.get('name')
            if not id:
                continue
        else:
            id = group_blob
        grp = model.Group.get(id)
        if grp is None:
            raise toolkit.ObjectNotFound(toolkit._('Group was not found.'))
        groups.add(grp)

    if pkg:
        pkg_groups = pkg.get_groups()

        groups = groups - set(pkg_groups)

    for group in groups:
        # QDES Modification.
        # Only check user permission if group is not an organisation and is not coming from clone_dataset
        # When we a cloning a dataset we need to ignore group (categories)
        # Any user can add their organisation datasets to a category
        if group.is_organization or not toolkit.get_endpoint() == (
                'clone_dataset', 'clone'):
            if not authz.has_user_permission_for_group_or_org(
                    group.id, user, 'manage_group'):
                return False

    return True
Ejemplo n.º 5
0
    def identify(self):
        """This does drupal authorization.
        The drupal session contains the drupal id of the logged in user.
        We need to convert this to represent the ckan user."""

        static = {
            ("static", "index"),
            ("webassets", "index"),
        }
        if tk.asbool(tk.config.get(
                CONFIG_SKIP_STATIC,
                DEFAULT_SKIP_STATIC)) and tk.get_endpoint() in static:
            log.debug("Skip static route")
            return

        cookie_sid = tk.request.cookies.get(utils.session_cookie_name())
        if not cookie_sid:
            log.debug("No session cookie found")
            return
        sid = utils.decode_sid(cookie_sid)
        details = utils.get_user_details(sid)
        if not details:
            log.debug("No user details for SID %s", sid)
            return
        try:
            user = utils.get_or_create_from_details(details)
        except tk.ValidationError as e:
            log.error(f"Cannot create user {details.name}<{details.email}>:"
                      f" {e.error_summary}")
            return

        if utils.is_synchronization_enabled():
            force = tk.asbool(
                tk.config.get(CONFIG_FOCE_SYNC, DEFAULT_FORCE_SYNC))
            try:
                user = utils.synchronize(user, details, force)
            except tk.ValidationError as e:
                log.error(
                    f"Cannot synchronize user details {details.name}<{details.email}>:"
                    f" {e.error_summary}")
                return

        tk.c.user = user["name"]
Ejemplo n.º 6
0
def page_authorized():
    blueprint, view = toolkit.get_endpoint()

    if (blueprint == 'error' and view == 'document' and toolkit.c.code
            and toolkit.c.code[0] != '403'):
        return True

    allowed_blueprints = [
        'user',  # most actions are defined in the core 'user' blueprint
        'unhcr_user',  # we override some actions in the 'unhcr_user' blueprint
    ]
    allowed_views = [
        'logged_in',
        'logged_out',
        'logged_out_page',
        'logged_out_redirect',
        'login',
        'perform_reset',
        'register',
        'request_reset',
    ]
    return (toolkit.c.userobj
            or (blueprint in allowed_blueprints and view in allowed_views))
Ejemplo n.º 7
0
def test_get_endpoint_with_context():
    """with_request_context fixture mocks request to the homepage."""
    assert tk.get_endpoint() == ("home", "index")
Ejemplo n.º 8
0
def test_get_endpoint_without_context():
    """Do not fail in CLI and tests."""
    assert tk.get_endpoint() == (None, None)