Example #1
0
    def new(self, data=None, errors=None, error_summary=None):
        '''GET to display a form for registering a new user.
           or POST the form data to actually do the user registration.
        '''
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'auth_user_obj': c.userobj,
                   'schema': self._new_form_to_db_schema(),
                   'save': 'save' in request.params}

        try:
            check_access('user_create', context)
        except NotAuthorized:
            abort(401, _('Unauthorized to create a user'))

        if context['save'] and not data:
            return self._save_new(context)

        if not new_authz.is_sysadmin(c.user):
            abort(401, _('Unauthorized to create a user'))

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        c.is_sysadmin = new_authz.is_sysadmin(c.user)
        c.form = render(self.new_user_form, extra_vars=vars)
        return render('user/new.html')
Example #2
0
    def new(self, data=None, errors=None, error_summary=None):
        '''GET to display a form for registering a new user.
           or POST the form data to actually do the user registration.
        '''
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj,
            'schema': self._new_form_to_db_schema(),
            'save': 'save' in request.params
        }

        try:
            check_access('user_create', context)
        except NotAuthorized:
            abort(401, _('Unauthorized to create a user'))

        if context['save'] and not data:
            return self._save_new(context)

        if not new_authz.is_sysadmin(c.user):
            abort(401, _('Unauthorized to create a user'))

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        c.is_sysadmin = new_authz.is_sysadmin(c.user)
        c.form = render(self.new_user_form, extra_vars=vars)
        return render('user/new.html')
Example #3
0
 def conditional_not_empty(key, data, errors, context):
     if is_sysadmin(context['user']) and data[('validation_override',)]:
         ignore_missing(key, data, errors, context)
     elif data[('catalog_type',)] != ctype:
         ignore_missing(key, data, errors, context)
     else:
         not_empty(key, data, errors, context)
Example #4
0
 def preselect(self):
     c.am_sysadmin = new_authz.is_sysadmin(c.user)
     c.organizations_available = helpers.hdx_organizations_available_with_roles()
     if c.organizations_available and len(c.organizations_available) > 0:
         return base.render('organization/organization_preselector.html')
     else:
         return base.render('organization/request_mem_or_org.html')
Example #5
0
def protect_portal_release_date(key, data, errors, context):
    """
    Ensure the portal_release_date is not changed by an unauthorized user.
    """
    if is_sysadmin(context['user']):
        return
    original = ''
    package = context.get('package')
    if package:
        original = package.extras.get('portal_release_date', '')
    value = data.get(key, '')
    if original == value:
        return

    user = context['user']
    user = model.User.get(user)
    if may_publish_datasets(user):
        return

    if value == '':
        # silently replace with the old value when none is sent
        data[key] = original
        return

    raise Invalid('Cannot change value of key from %s to %s. '
                  'This key is read-only' % (original, value))
Example #6
0
def ignore_not_package_admin(key, data, errors, context):
    '''Ignore if the user is not allowed to administer the package specified.'''

    model = context['model']
    user = context.get('user')

    if 'ignore_auth' in context:
        return

    if user and new_authz.is_sysadmin(user):
        return

    authorized = False
    pkg = context.get('package')
    if pkg:
        try:
            logic.check_access('package_change_state',context)
            authorized = True
        except logic.NotAuthorized:
            authorized = False

    if (user and pkg and authorized):
        return

    # allow_state_change in the context will allow the state to be changed
    # FIXME is this the best way to cjeck for state only?
    if key == ('state',) and context.get('allow_state_change'):
        return
    data.pop(key)
Example #7
0
def manage_users(context, data_dict):
    model = context['model']
    user = context.get('user','')
    print "User Logged: ",user
    if new_authz.is_sysadmin(user):
        return { 'success': True}
    return { 'success': False,'msg': _('User %s not authorized to manage users') % (str(user))}
Example #8
0
def user_dictize(user, context):

    if context.get('with_capacity'):
        user, capacity = user
        result_dict = d.table_dictize(user, context, capacity=capacity)
    else:
        result_dict = d.table_dictize(user, context)

    del result_dict['password']

    result_dict['display_name'] = user.display_name
    result_dict['email_hash'] = user.email_hash
    result_dict['number_of_edits'] = user.number_of_edits()
    result_dict[
        'number_administered_packages'] = user.number_administered_packages()

    requester = context.get('user')

    if not (new_authz.is_sysadmin(requester) or requester == user.name
            or context.get('keep_sensitive_data', False)):
        # If not sysadmin or the same user, strip sensible info
        result_dict.pop('apikey', None)
        result_dict.pop('reset_key', None)
        result_dict.pop('email', None)

    model = context['model']
    session = model.Session

    if context.get('with_related'):
        related_items = session.query(model.Related).\
                        filter(model.Related.owner_id==user.id).all()
        result_dict['related_items'] = related_list_dictize(
            related_items, context)

    return result_dict
Example #9
0
 def conditional_not_empty(key, data, errors, context):
     if is_sysadmin(context['user']) and data[('validation_override', )]:
         ignore_missing(key, data, errors, context)
     elif data[('catalog_type', )] != ctype:
         ignore_missing(key, data, errors, context)
     else:
         not_empty(key, data, errors, context)
Example #10
0
    def new(self, data=None, errors=None, error_summary=None):
        """GET to display a form for registering a new user.
           or POST the form data to actually do the user registration.
        """
        context = {
            "model": model,
            "session": model.Session,
            "user": c.user or c.author,
            "schema": self._new_form_to_db_schema(),
            "save": "save" in request.params,
        }

        try:
            check_access("user_create", context)
        except NotAuthorized:
            abort(401, _("Unauthorized to create a user"))

        if context["save"] and not data:
            return self._save_new(context)

        if c.user and not data:
            # #1799 Don't offer the registration form if already logged in
            return render("user/logout_first.html")

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}
        vars = {"data": data, "errors": errors, "error_summary": error_summary}

        c.is_sysadmin = new_authz.is_sysadmin(c.user)
        c.form = render(self.new_user_form, extra_vars=vars)
        return render("user/new.html")
Example #11
0
def protect_new_dataset_id(key, data, errors, context):
    """
    Allow dataset ids to be set for packages created by a sysadmin
    """
    if is_sysadmin(context['user']):
        return
    empty(key, data, errors, context)
Example #12
0
def ignore_not_package_admin(key, data, errors, context):
    '''Ignore if the user is not allowed to administer the package specified.'''

    model = context['model']
    user = context.get('user')

    if 'ignore_auth' in context:
        return

    if user and new_authz.is_sysadmin(user):
        return

    authorized = False
    pkg = context.get('package')
    if pkg:
        try:
            logic.check_access('package_change_state', context)
            authorized = True
        except logic.NotAuthorized:
            authorized = False

    if (user and pkg and authorized):
        return

    # allow_state_change in the context will allow the state to be changed
    # FIXME is this the best way to cjeck for state only?
    if key == ('state', ) and context.get('allow_state_change'):
        return
    data.pop(key)
def member_requests_list(context, data_dict):
    ''' Organization admins/editors will see a list of member requests to be approved.
    :param group: name of the group (optional)
    :type group: string
    '''
    logic.check_access('member_requests_list', context, data_dict)

    user = context.get('user', None)
    user_object = model.User.get(user)
    is_sysadmin = authz.is_sysadmin(user)

    # ALL members with pending state only
    query = model.Session.query(model.Member).filter(
        model.Member.table_name == "user").filter(model.Member.state == 'pending')

    if not is_sysadmin:
        admin_in_groups = model.Session.query(model.Member).filter(model.Member.state == "active").filter(model.Member.table_name == "user") \
            .filter(model.Member.capacity == 'admin').filter(model.Member.table_id == user_object.id)

        if admin_in_groups.count() <= 0:
            return []
        # members requests for this organization
        query = query.filter(model.Member.group_id.in_(
            admin_in_groups.values(model.Member.group_id)))

    group = data_dict.get('group', None)
    if group:
        group_object = model.Group.get(group)
        if group_object:
            query = query.filter(model.Member.group_id == group_object.id)

    members = query.all()

    return _member_list_dictize(members, context)
Example #14
0
def harvest_jobs_run(context,data_dict):
    model = context['model']
    user = context.get('user')

    # Check user is logged in
    if not user:
        return {'success': False, 'msg': _('Only logged users are authorized to run harvest jobs')}

    user_obj = User.get(user)

    # Checks for non sysadmin users
    if not authz.is_sysadmin(user):
        if not user_obj or len(user_obj.get_groups(u'publisher')) == 0:
            return {'success': False, 'msg': _('User %s must belong to a publisher to run harvest jobs') % str(user)}

        source_id = data_dict.get('source_id',False)
        if not source_id:
            return {'success': False, 'msg': _('Only sysadmins can run all harvest jobs') % str(user)}

        source = HarvestSource.get(source_id)
        if not source:
            raise NotFound

        if not source.publisher_id in [g.id for g in user_obj.get_groups(u'publisher')]:
            return {'success': False, 'msg': _('User %s not authorized to run jobs from source %s') % (str(user),source.id)}

    return {'success': True}
Example #15
0
def datahub_package_create(context, data_dict):
    from ckan.logic.auth.create import _check_group_auth

    if new_authz.is_sysadmin(context.get('user')):
        return {'success': True}

    user = context['user']
    if not new_authz.auth_is_registered_user():
        return {'success': False, 'msg': _('You must login to create a dataset')}
    else:
        check1 = new_authz.check_config_permission('create_dataset_if_not_in_organization') \
            or new_authz.check_config_permission('create_unowned_dataset')

        if not check1 and not new_authz.has_user_permission_for_some_org(user, 'create_dataset'):
            h.redirect_to('/pages/requesting-an-organization')

    if not check1:
        return {'success': False, 'msg': _('User %s not authorized to create packages') % user}

    check2 = _check_group_auth(context,data_dict)
    if not check2:
        return {'success': False, 'msg': _('User %s not authorized to edit these groups') % user}

    # If an organization is given are we able to add a dataset to it?
    data_dict = data_dict or {}
    org_id = data_dict.get('organization_id')
    if org_id and not new_authz.has_user_permission_for_group_or_org(
            org_id, user, 'create_dataset'):
        return {'success': False, 'msg': _('User %s not authorized to add dataset to this organization') % user}
    return {'success': True}
Example #16
0
def protect_new_dataset_id(key, data, errors, context):
    """
    Allow dataset ids to be set for packages created by a sysadmin
    """
    if is_sysadmin(context['user']):
        return
    empty(key, data, errors, context)
Example #17
0
    def new(self, data=None, errors=None, error_summary=None):
        '''This is a modified version of the core user controller

        We have removed the lines redirecting the user the logout page
        if they are already logged in, this allows sysadmins to create
        users as we have disabled user registration unless they are
        sys admins'''
        context = {
            'model': model,
            'session': model.Session,
            'user': toolkit.c.user or toolkit.c.author,
            'auth_user_obj': toolkit.c.userobj,
            'schema': self._new_form_to_db_schema(),
            'save': 'save' in toolkit.request.params
        }

        try:
            toolkit.check_access('user_create', context)
        except toolkit.NotAuthorized:
            toolkit.abort(401, toolkit._('Unauthorized to create a user'))

        if context['save'] and not data:
            return self._save_new(context)

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        toolkit.c.is_sysadmin = new_authz.is_sysadmin(toolkit.c.user)
        toolkit.c.form = toolkit.render(self.new_user_form, extra_vars=vars)
        return toolkit.render('user/new.html')
Example #18
0
    def dataset_facets(self, facets_dict, package_type):

        if package_type == 'article':
            return {
                'tags': _('Tags'),
            }
        elif package_type == 'application':
            if (new_authz.is_sysadmin(c.user)):
                return {
                    'status': _('Status'),
                    'tags': _('Tags'),
                }
            else:
                return {
                    'tags': _('Tags'),
                }

        ordered_facets_dict = collections.OrderedDict()
        ordered_facets_dict['organization'] = _('Organizations')
        ordered_facets_dict['institution_type'] = _('Organization type')
        ordered_facets_dict['groups'] = _('Groups')
        ordered_facets_dict['tags'] = _('Tags')
        ordered_facets_dict['api'] = _('API provided')
        ordered_facets_dict['res_format'] = _('Formats')
        ordered_facets_dict['res_type'] = _('Resource types')
        ordered_facets_dict['update_frequency'] = _('Update frequency')
        ordered_facets_dict['res_extras_openness_score'] = _('Openess Score')
        ordered_facets_dict['has_any_reuse_conditions'] = _(
            'Restrictions on reuse')
        return ordered_facets_dict
Example #19
0
def datahub_package_create(context, data_dict):
    from ckan.logic.auth.create import _check_group_auth

    if authz.is_sysadmin(context.get('user')):
        return {'success': True}

    user = context['user']
    if not authz.auth_is_registered_user():
        if '/new' in c.environ['PATH_INFO']:
            h.redirect_to(CREATE_DATASET_HELP_PAGE)
        else:
            return {'success': False, 'msg': _('You must login to create a dataset')}

    check1 = authz.check_config_permission('create_dataset_if_not_in_organization') \
        or authz.check_config_permission('create_unowned_dataset')

    #if not authorized and not a part of any org, redirect to help page on how to join one
    if not check1 and not authz.has_user_permission_for_some_org(user, 'create_dataset'):
        if '/new' in c.environ['PATH_INFO']:
            h.redirect_to(CREATE_DATASET_HELP_PAGE)
        else:
            return {'success': False, 'msg': _('User %s not authorized to create packages') % user}

    check2 = _check_group_auth(context,data_dict)
    if not check2 and not check1:
        return {'success': False, 'msg': _('User %s not authorized to edit these groups') % user}

    # If an organization is given are we able to add a dataset to it?
    data_dict = data_dict or {}
    org_id = data_dict.get('organization_id')
    if org_id and not authz.has_user_permission_for_group_or_org(
            org_id, user, 'create_dataset'):
        return {'success': False, 'msg': _('User %s not authorized to add dataset to this organization') % user}
    return {'success': True}
Example #20
0
def hdx_organizations_available_with_roles():
    organizations_available = h.organizations_available('read')
    if organizations_available and len(organizations_available) > 0:
        orgs_where_editor = []
        orgs_where_admin = []
    am_sysadmin = new_authz.is_sysadmin(c.user)
    if not am_sysadmin:
        orgs_where_editor = set(
            [org['id'] for org in h.organizations_available('create_dataset')])
        orgs_where_admin = set([org['id']
                                for org in h.organizations_available('admin')])

    for org in organizations_available:
        org['has_add_dataset_rights'] = True
        if am_sysadmin:
            org['role'] = 'sysadmin'
        elif org['id'] in orgs_where_admin:
            org['role'] = 'admin'
        elif org['id'] in orgs_where_editor:
            org['role'] = 'editor'
        else:
            org['role'] = 'member'
            org['has_add_dataset_rights'] = False

    organizations_available.sort(key=lambda y:
                                 y['display_name'].lower())
    return organizations_available
Example #21
0
def ignore_not_package_admin(key, data, errors, context):
    """Ignore if the user is not allowed to administer the package specified."""

    model = context["model"]
    user = context.get("user")

    if "ignore_auth" in context:
        return

    if user and new_authz.is_sysadmin(user):
        return

    authorized = False
    pkg = context.get("package")
    if pkg:
        try:
            logic.check_access("package_change_state", context)
            authorized = True
        except logic.NotAuthorized:
            authorized = False

    if user and pkg and authorized:
        return

    # allow_state_change in the context will allow the state to be changed
    # FIXME is this the best way to cjeck for state only?
    if key == ("state",) and context.get("allow_state_change"):
        return
    data.pop(key)
Example #22
0
File: logic.py Project: haphut/ytp
def member_request_list(context, data_dict):
    ''' List my member requests.

    :param group: name of the group (optional)
    :type group: string
    '''
    check_access('member_request_list', context, data_dict)

    user = context['user']
    user_object = model.User.get(user)
    sysadmin = new_authz.is_sysadmin(user)

    query = model.Session.query(model.Member).filter(model.Member.table_name == "user").filter(model.Member.state == 'pending')

    if not sysadmin:
        admin_in_groups = model.Session.query(model.Member).filter(model.Member.state == "active").filter(model.Member.table_name == "user") \
            .filter(model.Member.capacity == 'admin').filter(model.Member.table_id == user_object.id)

        if admin_in_groups.count() <= 0:
            return []

        query = query.filter(model.Member.group_id.in_(admin_in_groups.values(model.Member.group_id)))

    group = data_dict.get('group', None)
    if group:
        group_object = model.Group.get(group)
        if group_object:
            query = query.filter(model.Member.group_id == group_object.id)

    members = query.all()

    return _member_list_dictize(members, context)
Example #23
0
        def query_for_datasets():
            query = ''

            if not new_authz.is_sysadmin(c.user):
                organisation_ids = self.__get_users_organizations_ids(c.user)

                if not organisation_ids:
                    # return an empty query result with the needed (i.e.: accessed later) elements
                    return {'results': [], 'count': 0}

                query = build_owner_filter(organisation_ids)

            if c.q != u'':
                search = c.q.strip().split(' ')
                result = ''
                if request.params.get('ext_boolean') == 'any':
                    result = build_search_for_any_words(search)
                elif request.params.get('ext_boolean') == 'all':
                    result = build_search_for_all_words(search)
                elif request.params.get('ext_boolean') == 'exact':
                    result = '("%s")' % (c.q)
                    log.info("%s" % (request.params.get('ext_boolean')))

                query = query + " + title:" + result

            return query
Example #24
0
    def new (self, data=None, errors=None, error_summary=None):
        #q = model.Session.query(model.User).filter(model.User.sysadmin==True)
        #c.sysadmins = [a.name for a in q.all()]

        '''GET to display a form for registering a new user.
           or POST the form data to actually do the user registration.
        '''
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'auth_user_obj': c.userobj,
                   'schema': self._new_form_to_db_schema(),
                   'save': 'save' in request.params}
        c.is_sysadmin = new_authz.is_sysadmin(c.user)
        if not c.user or not c.is_sysadmin:
            return base.render('user/logout_first.html')

        try:
            logic.check_access('user_create', context)
        except logic.NotAuthorized:
            base.abort(401, _('Unauthorized to create a user'))

        if context['save'] and not data:
            return self._save_new(context)

        c.data = data or {}
        c.errors = errors or {}
        c.error_summary = error_summary or {}
        #vars = {'data': data, 'errors': errors, 'error_summary': error_summary}


        #c.form = render(self.new_user_form, extra_vars=vars)
        #return render('user/new.html')

        return base.render('muser/new.html')
    def register(self, data=None, errors=None, error_summary=None):
        '''GET to display a form for registering a new user.
           or POST the form data to actually do the user registration.

           The bulk of this code is pulled directly from ckan/controlllers/user.py
        '''
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': schema.user_new_form_schema(),
                   'save': 'save' in request.params}

        try:
            check_access('user_create', context)
        except NotAuthorized:
            abort(401, _('Unauthorized to create a user'))

        if context['save'] and not data:
            uc = UserController()
            return uc._save_new(context)

        if c.user and not data:
            # #1799 Don't offer the registration form if already logged in
            return render('user/logout_first.html')

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}

        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}
        c.is_sysadmin = new_authz.is_sysadmin(c.user)
        c.form = render('user/new_user_form.html', extra_vars=vars)
        return render('user/new.html')
    def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop('lang', None)
        session.save()

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        i18n.set_lang(lang)

        if c.user:
            is_new = False
            is_sysadmin = new_authz.is_sysadmin(c.user)

            # Retrieve information about the current user
            context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': schema.user_new_form_schema()}
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            # This check is not needed (or correct) for sys admins
            if not is_sysadmin:

                # Get all organizations and all groups the user belongs to
                orgs_q = model.Session.query(model.Group) \
                    .filter(model.Group.is_organization == True) \
                    .filter(model.Group.state == 'active')
                q = model.Session.query(model.Member) \
                    .filter(model.Member.table_name == 'user') \
                    .filter(model.Member.table_id == user_dict['id'])

                group_ids = []
                for row in q.all():
                    group_ids.append(row.group_id)

                if not group_ids:
                    is_new = True
                else:
                    orgs_q = orgs_q.filter(model.Group.id.in_(group_ids))

                    orgs_list = model_dictize.group_list_dictize(orgs_q.all(), context)

                    if len(orgs_list) == 0:
                        is_new = True

            h.flash_success(_("<p><strong>Note</strong></p>"
                "<p>%s is now logged in</p>") %
                user_dict['display_name'], allow_html=True)

            if is_new:
                return h.redirect_to(controller='ckanext.canada.controller:CanadaController',
                                         action='view_new_user', locale=lang)
            else:
                return h.redirect_to(controller='package',
                    action='search', locale=lang)
        else:
            h.flash_error(_('Login failed. Bad username or password.'))
            return h.redirect_to(controller='user',
                action='login', locale=lang)
def protect_portal_release_date(key, data, errors, context):
    """
    Ensure the portal_release_date is not changed by an unauthorized user.
    """
    if is_sysadmin(context['user']):
        return
    original = ''
    package = context.get('package')
    if package:
        original = package.extras.get('portal_release_date', '')
    value = data.get(key, '')
    if original == value:
        return

    user = context['user']
    user = model.User.get(user)
    if may_publish_datasets(user):
        return

    if value == '':
        # silently replace with the old value when none is sent
        data[key] = original
        return

    raise Invalid('Cannot change value of key from %s to %s. '
                  'This key is read-only' % (original, value))
Example #28
0
def user_dictize(user, context):

    if context.get('with_capacity'):
        user, capacity = user
        result_dict = d.table_dictize(user, context, capacity=capacity)
    else:
        result_dict = d.table_dictize(user, context)

    del result_dict['password']

    result_dict['display_name'] = user.display_name
    result_dict['email_hash'] = user.email_hash
    result_dict['number_of_edits'] = user.number_of_edits()
    result_dict['number_administered_packages'] = user.number_administered_packages()

    requester = context.get('user')

    if not (new_authz.is_sysadmin(requester) or
            requester == user.name or
            context.get('keep_sensitive_data', False)):
        # If not sysadmin or the same user, strip sensible info
        result_dict.pop('apikey', None)
        result_dict.pop('reset_key', None)
        result_dict.pop('email', None)

    model = context['model']
    session = model.Session

    if context.get('with_related'):
        related_items = session.query(model.Related).\
                        filter(model.Related.owner_id==user.id).all()
        result_dict['related_items'] = related_list_dictize(related_items,
                                                            context)

    return result_dict
Example #29
0
    def new(self, data=None, errors=None, error_summary=None):
        '''This is a modified version of the core user controller

        We have removed the lines redirecting the user the logout page
        if they are already logged in, this allows sysadmins to create
        users as we have disabled user registration unless they are
        sys admins'''
        context = {'model': model, 'session': model.Session,
                   'user': toolkit.c.user or toolkit.c.author,
                   'auth_user_obj': toolkit.c.userobj,
                   'schema': self._new_form_to_db_schema(),
                   'save': 'save' in toolkit.request.params}

        try:
            toolkit.check_access('user_create', context)
        except toolkit.NotAuthorized:
            toolkit.abort(401, toolkit._('Unauthorized to create a user'))

        if context['save'] and not data:
            return self._save_new(context)

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        toolkit.c.is_sysadmin = new_authz.is_sysadmin(toolkit.c.user)
        toolkit.c.form = toolkit.render(self.new_user_form, extra_vars=vars)
        return toolkit.render('user/new.html')
Example #30
0
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {'save': 'save' in request.params,
                   'schema': self._edit_form_to_db_schema(),
                   'model': model, 'session': model.Session,
                   'user': c.user, 'auth_user_obj': c.userobj
                   }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _('No user specified'))
        data_dict = {'id': id}

        try:
            check_access('user_update', context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to edit a user.'))

        if (context['save']) and not data:
            return self._save_edit(id, context)

        try:
            old_data = get_action('user_show')(context, data_dict)

            schema = self._db_to_edit_form_schema()
            if schema:
                old_data, errors = validate(old_data, schema)

            c.display_name = old_data.get('display_name')
            c.user_name = old_data.get('name')

            data = data or old_data

        except NotAuthorized:
            abort(401, _('Unauthorized to edit user %s') % '')
        except NotFound:
            abort(404, _('User not found'))

        user_obj = context.get('user_obj')

        if not (new_authz.is_sysadmin(c.user)
                or c.user == user_obj.name):
            abort(401, _('User %s not authorized to edit %s') %
                  (str(c.user), id))

        errors = errors or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        self._setup_template_variables({'model': model,
                                        'session': model.Session,
                                        'user': c.user or c.author},
                                       data_dict)

        c.is_myself = True
        c.show_email_notifications = h.asbool(
            config.get('ckan.activity_streams_email_notifications'))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render('user/edit.html')
Example #31
0
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {'save': 'save' in request.params,
                   'schema': self._edit_form_to_db_schema(),
                   'model': model, 'session': model.Session,
                   'user': c.user,
                   }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _('No user specified'))
        data_dict = {'id': id}

        try:
            check_access('user_update', context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to edit a user.'))

        if (context['save']) and not data:
            return self._save_edit(id, context)

        try:
            old_data = get_action('user_show')(context, data_dict)

            schema = self._db_to_edit_form_schema()
            if schema:
                old_data, errors = validate(old_data, schema)

            c.display_name = old_data.get('display_name')
            c.user_name = old_data.get('name')

            data = data or old_data

        except NotAuthorized:
            abort(401, _('Unauthorized to edit user %s') % '')
        except NotFound:
            abort(404, _('User not found'))

        user_obj = context.get('user_obj')

        if not (new_authz.is_sysadmin(c.user)
                or c.user == user_obj.name):
            abort(401, _('User %s not authorized to edit %s') %
                  (str(c.user), id))

        errors = errors or {}
        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}

        self._setup_template_variables({'model': model,
                                        'session': model.Session,
                                        'user': c.user or c.author},
                                       data_dict)

        c.is_myself = True
        c.show_email_notifications = h.asbool(
            config.get('ckan.activity_streams_email_notifications'))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render('user/edit.html')
Example #32
0
def execute_bulkupload(context, data_dict):

    model = context['model']
    user = context.get('user','')
    print "User Logged: ",user
    if new_authz.is_sysadmin(user):
        return { 'success': True}
    return { 'success': False,'msg': _('User %s not authorized to execute the bulk upload process') % (str(user))}    
Example #33
0
def harvesters_info_show(context,data_dict):
    model = context['model']
    user = context.get('user')

    if not authz.is_sysadmin(user):
        return {'success': False, 'msg': _('User %s not authorized to see the harvesters information') % str(user)}
    else:
        return {'success': True}
Example #34
0
def harvest_object_list(context,data_dict):
    model = context['model']
    user = context.get('user')

    if not authz.is_sysadmin(user):
        return {'success': False, 'msg': _('User %s not authorized to see the harvest objects') % str(user)}
    else:
        return {'success': True}
Example #35
0
def harvest_source_show(context,data_dict):
    model = context['model']
    user = context.get('user')

    if not authz.is_sysadmin(user):
        return {'success': False, 'msg': _('User %s not authorized to read this harvest source') % str(user)}
    else:
        return {'success': True}
Example #36
0
def harvest_job_create_all(context,data_dict):
    model = context['model']
    user = context.get('user')

    if not authz.is_sysadmin(user):
        return {'success': False, 'msg': _('User %s not authorized to create harvest jobs for all sources') % str(user)}
    else:
        return {'success': True}
Example #37
0
def harvest_job_create_all(context, data_dict):
    model = context["model"]
    user = context.get("user")

    if not authz.is_sysadmin(user):
        return {"success": False, "msg": _("Only sysadmins can create harvest jobs for all sources") % str(user)}
    else:
        return {"success": True}
Example #38
0
def harvest_jobs_run(context,data_dict):
    model = context['model']
    user = context.get('user')

    if not authz.is_sysadmin(user):
        return {'success': False, 'msg': _('User %s not authorized to run the pending harvest jobs') % str(user)}
    else:
        return {'success': True}
Example #39
0
    def edit(self, id=None, data=None, errors=None, error_summary=None):
        context = {
            "save": "save" in request.params,
            "schema": self._edit_form_to_db_schema(),
            "model": model,
            "session": model.Session,
            "user": c.user,
            "auth_user_obj": c.userobj,
        }
        if id is None:
            if c.userobj:
                id = c.userobj.id
            else:
                abort(400, _("No user specified"))
        data_dict = {"id": id}

        try:
            check_access("user_update", context, data_dict)
        except NotAuthorized:
            abort(401, _("Unauthorized to edit a user."))

        if (context["save"]) and not data:
            return self._save_edit(id, context)

        try:
            old_data = get_action("user_show")(context, data_dict)

            schema = self._db_to_edit_form_schema()
            if schema:
                old_data, errors = validate(old_data, schema)

            c.display_name = old_data.get("display_name")
            c.user_name = old_data.get("name")

            data = data or old_data

        except NotAuthorized:
            abort(401, _("Unauthorized to edit user %s") % "")
        except NotFound:
            abort(404, _("User not found"))

        user_obj = context.get("user_obj")

        if not (new_authz.is_sysadmin(c.user) or c.user == user_obj.name):
            abort(401, _("User %s not authorized to edit %s") % (str(c.user), id))

        errors = errors or {}
        vars = {"data": data, "errors": errors, "error_summary": error_summary}

        self._setup_template_variables(
            {"model": model, "session": model.Session, "user": c.user or c.author}, data_dict
        )

        c.is_myself = True
        c.show_email_notifications = h.asbool(config.get("ckan.activity_streams_email_notifications"))
        c.form = render(self.edit_user_form, extra_vars=vars)

        return render("user/edit.html")
Example #40
0
def organization_list_for_user(context, data_dict):
    perm = data_dict.get('permission')
    if perm in ['create_dataset', 'update_dataset', 'delete_dataset']:
        # Create a copy of the data dict, and change the request permission to
        # 'read' which will be granted to all members of a group.
        data_dict = dict(data_dict.items() + {'permission': 'read'}.items())

    #return fb(context, data_dict)
    #return core_org_list_for_user(context, data_dict)
    '''Return the list of organizations that the user is a member of.

    :param permission: the permission the user has against the returned organizations
      (optional, default: ``edit_group``)
    :type permission: string

    :returns: list of dictized organizations that the user is authorized to edit
    :rtype: list of dicts

    '''
    model = context['model']
    user = context['user']

    _check_access('organization_list_for_user', context, data_dict)
    sysadmin = new_authz.is_sysadmin(user)

    orgs_q = model.Session.query(model.Group) \
        .filter(model.Group.is_organization == True) \
        .filter(model.Group.state == 'active')

    if not sysadmin:
        # for non-Sysadmins check they have the required permission

        permission = data_dict.get('permission', 'edit_group')

        roles = ckan.new_authz.get_roles_with_permission(permission)

        if not roles:
            return []
        user_id = new_authz.get_user_id_for_username(user, allow_none=True)
        if not user_id:
            return []

        q = model.Session.query(model.Member) \
            .filter(model.Member.table_name == 'user') \
            .filter(model.Member.capacity.in_(roles)) \
            .filter(model.Member.table_id == user_id)

        group_ids = []
        for row in q.all():
            group_ids.append(row.group_id)

        if not group_ids:
            return []

        orgs_q = orgs_q.filter(model.Group.id.in_(group_ids))

    orgs_list = model_dictize.group_list_dictize(orgs_q.all(), context)
    return orgs_list
Example #41
0
def not_empty_allow_override(key, data, errors, context):
    """
    Not empty, but allow sysadmins to override the validation error
    by setting a value in data[(validation_override,)].
    """
    if is_sysadmin(context['user']) and data.get(('validation_override', )):
        ignore_missing(key, data, errors, context)
    else:
        not_empty(key, data, errors, context)
Example #42
0
def not_empty_allow_override(key, data, errors, context):
    """
    Not empty, but allow sysadmins to override the validation error
    by setting a value in data[(validation_override,)].
    """
    if is_sysadmin(context['user']) and data.get(('validation_override',)):
        ignore_missing(key, data, errors, context)
    else:
        not_empty(key, data, errors, context)
Example #43
0
def organization_list_for_user(context, data_dict):
    '''Return the organizations that the user has a given permission for.
    By default this returns the list of organizations that the currently
    authorized user can edit, i.e. the list of organizations that the user is an
    admin of.
    Specifically it returns the list of organizations that the currently
    authorized user has a given permission (for example: "edit_group") against.
    When a user becomes a member of an organization in CKAN they're given a
    "capacity" (sometimes called a "role"), for example "member", "editor" or
    "admin".
    Each of these roles has certain permissions associated with it. For example
    the admin role has the "admin" permission (which means they have permission
    to do anything). The editor role has permissions like "create_dataset",
    "update_dataset" and "delete_dataset". The member role has the "read"
    permission.
    This function returns the list of organizations that the authorized user has
    a given permission for. For example the list of organizations that the user
    is an admin of, or the list of organizations that the user can create
    datasets in.
    :param permission: the permission the user has against the
    returned organizations, for example ``"read"`` or ``"create_dataset"``
    (optional, default: ``"edit_group"``)
    :type permission: string
    :returns: list of organizations that the user has the given permission for
    :rtype: list of dicts
    '''
    model = context['model']
    user = context['user']
    logic.check_access('organization_list_for_user', context, data_dict)
    sysadmin = new_authz.is_sysadmin(user)
    orgs_q = model.Session.query(model.Group) \
    .filter(model.Group.is_organization == True) \
    .filter(model.Group.state == 'active')
    user_roles = user_custom_roles(context, data_dict)
    if not sysadmin and not Roles.MOD_R_DATA in user_roles:
        # for non-Sysadmins check they have the required permission
        permission = data_dict.get('permission', 'edit_group')
        roles = new_authz.get_roles_with_permission(permission)
        if not roles:
            return []
        user_id = new_authz.get_user_id_for_username(user, allow_none=True)
        if not user_id:
            return []
        q = model.Session.query(model.Member) \
        .filter(model.Member.table_name == 'user') \
        .filter(model.Member.capacity.in_(roles)) \
        .filter(model.Member.table_id == user_id) \
        .filter(model.Member.state == 'active')
        group_ids = []
        for row in q.all():
            group_ids.append(row.group_id)
        if not group_ids:
            return []
        orgs_q = orgs_q.filter(model.Group.id.in_(group_ids))
    orgs_list = model_dictize.group_list_dictize(orgs_q.all(), context)
    return orgs_list
Example #44
0
def ignore_not_sysadmin(key, data, errors, context):
    '''Ignore the field if user not sysadmin or ignore_auth in context.'''

    user = context.get('user')
    ignore_auth = context.get('ignore_auth')

    if ignore_auth or (user and new_authz.is_sysadmin(user)):
        return

    data.pop(key)
Example #45
0
 def _sysadmin_or_abort(self):
     user = tk.c.user
     if not user:
         return base.abort(401, 'Not signed in')
     is_admin = new_authz.is_sysadmin(unicode(user))
     if not is_admin:
         return base.abort(
             401,
             'You are not authorized to access search cloud administation'
         )
Example #46
0
def empty_if_not_sysadmin(key, data, errors, context):
    '''Only sysadmins may pass this value'''
    from ckan.lib.navl.validators import empty

    user = context.get('user')

    ignore_auth = context.get('ignore_auth')
    if ignore_auth or (user and new_authz.is_sysadmin(user)):
        return

    empty(key, data, errors, context)
Example #47
0
 def _setup_template_variables(self, context, data_dict):
     c.is_sysadmin = new_authz.is_sysadmin(c.user)
     try:
         user_dict = get_action('user_show')(context, data_dict)
     except NotFound:
         abort(404, _('User not found'))
     except NotAuthorized:
         abort(401, _('Not authorized to see this page'))
     c.user_dict = user_dict
     c.is_myself = user_dict['name'] == c.user
     c.about_formatted = h.render_markdown(user_dict['about'])
Example #48
0
 def _setup_template_variables(self, context, data_dict):
     c.is_sysadmin = new_authz.is_sysadmin(c.user)
     try:
         user_dict = get_action('user_show')(context, data_dict)
     except NotFound:
         h.redirect_to(controller='user', action='login', id=None)
     except NotAuthorized:
         abort(401, _('Not authorized to see this page'))
     c.user_dict = user_dict
     c.is_myself = user_dict['name'] == c.user
     c.about_formatted = self._format_about(user_dict['about'])
Example #49
0
def moderation_queue_show(context, data_dict):
    model = context['model']
    user = context['user']

    if new_authz.is_sysadmin(user):
        return {'success': True}

    return {
        'success': False,
        'msg': _('You do not have permission to view the moderation queue')
    }
Example #50
0
def comment_delete(context, data_dict):
    model = context['model']
    user = context['user']

    # If sysadmin.
    if new_authz.is_sysadmin(user):
        return {'success': True}

    return {
        'success': False,
        'msg': _('You do not have permission to delete this comment')
    }
Example #51
0
def iati_publisher_state_validator(key, data, errors, context):
    user = context.get('user')

    if 'ignore_auth' in context:
        return

    if user and new_authz.is_sysadmin(user):
        return

    # If the user is not a sysadmin but we are creating the publisher,
    # we need to keep the state = pending value, otherwise ignore it.
    if not context.get('__iati_state_pending'):
        data.pop(key)
Example #52
0
def issue_list(context, data_dict=None):
    import ckan.new_authz as new_authz
    model = context['model']
    user = context.get('user')
    if user:
        user_obj = model.User.get(user)
        if user_obj and new_authz.is_sysadmin(user_obj):
            return {'success': True}

    return {
        'success': False,
        'msg': _('User %s not authorized to list issues') % user
    }
Example #53
0
def comment_update(context, data_dict):
    model = context['model']
    user = context['user']

    # If sysadmin, then yes.
    if new_authz.is_sysadmin(user):
        return {'success': True}

    # If owner, then yes in theory but we don't really want people changing
    # the contents of earlier posts. We should restrict update to not changing
    # the content itself.

    return {'success': False, 'msg': _('You do not have permission to update this comment')}
Example #54
0
def datahub_package_create(context, data_dict):
    from ckan.logic.auth.create import _check_group_auth

    if new_authz.is_sysadmin(context.get('user')):
        return {'success': True}

    user = context['user']
    if not new_authz.auth_is_registered_user():
        if '/new' in c.environ['PATH_INFO']:
            h.redirect_to(CREATE_DATASET_HELP_PAGE)
        else:
            return {
                'success': False,
                'msg': _('You must login to create a dataset')
            }

    check1 = new_authz.check_config_permission('create_dataset_if_not_in_organization') \
        or new_authz.check_config_permission('create_unowned_dataset')

    #if not authorized and not a part of any org, redirect to help page on how to join one
    if not check1 and not new_authz.has_user_permission_for_some_org(
            user, 'create_dataset'):
        if '/new' in c.environ['PATH_INFO']:
            h.redirect_to(CREATE_DATASET_HELP_PAGE)
        else:
            return {
                'success': False,
                'msg': _('User %s not authorized to create packages') % user
            }

    check2 = _check_group_auth(context, data_dict)
    if not check2 and not check1:
        return {
            'success': False,
            'msg': _('User %s not authorized to edit these groups') % user
        }

    # If an organization is given are we able to add a dataset to it?
    data_dict = data_dict or {}
    org_id = data_dict.get('organization_id')
    if org_id and not new_authz.has_user_permission_for_group_or_org(
            org_id, user, 'create_dataset'):
        return {
            'success':
            False,
            'msg':
            _('User %s not authorized to add dataset to this organization') %
            user
        }
    return {'success': True}
Example #55
0
def user_dictize(user, context):

    if context.get('with_capacity'):
        user, capacity = user
        result_dict = d.table_dictize(user, context, capacity=capacity)
    else:
        result_dict = d.table_dictize(user, context)

    del result_dict['password']
    del result_dict['reset_key']

    result_dict['display_name'] = user.display_name
    result_dict['email_hash'] = user.email_hash
    result_dict['number_of_edits'] = user.number_of_edits()
    result_dict['number_created_packages'] = user.number_created_packages(
        include_private_and_draft=context.get(
            'count_private_and_draft_datasets', False))

    requester = context.get('user')

    reset_key = result_dict.pop('reset_key', None)
    apikey = result_dict.pop('apikey', None)
    email = result_dict.pop('email', None)

    if context.get('keep_email', False):
        result_dict['email'] = email

    if context.get('keep_apikey', False):
        result_dict['apikey'] = apikey

    if requester == user.name:
        result_dict['apikey'] = apikey
        result_dict['email'] = email

    ## this should not really really be needed but tests need it
    if new_authz.is_sysadmin(requester):
        result_dict['apikey'] = apikey
        result_dict['email'] = email

    model = context['model']
    session = model.Session

    if context.get('with_related'):
        related_items = session.query(model.Related).\
                        filter(model.Related.owner_id==user.id).all()
        result_dict['related_items'] = related_list_dictize(related_items,
                                                            context)

    return result_dict
Example #56
0
def user_show(context, data_dict):
    '''
    Return a user account and extra profile info.

    Minor rewrite to add additional user profile information (acquired eg. from
    shibboleth) from the user_extra table to the c.user_dict for templates.
    NOTE: 'revision_show' method still references to default
    ckan.logic.action.get.revision_show while 'package_show' declaration is
    resolved with standard 'get_action' hook. Not sure which to use so these
    are tried.

    Either the ``id`` or the ``user_obj`` parameter must be given in data_dict.

    :param id: the id or name of the user (optional)
    :type id: string
    :param user_obj: the user dictionary of the user (optional)
    :type user_obj: user dictionary

    :rtype: dictionary

    '''
    # In some places, this user_show is used almost like a check access function
    # thus we are returning something instead of modifying the authorisation function
    if context.get('user', '') == data_dict.get('id', None):
        hide = False
    elif context.get('user', False) and new_authz.is_sysadmin(context['user']):
        hide = False
    # Dashboard:
    elif data_dict.get('user_obj', False) and not data_dict.get('id', False) and \
            (context.get('user', '') == data_dict['user_obj'].name):
        hide = False
    else:
        hide = True

    user_dict = get.user_show(context, data_dict)

    # Added in ckanext-shibboleth
    extra_dict = utils.fetch_user_extra(user_dict['id'])
    user_dict.update(extra_dict)

    if hide:
        return {
            'name': user_dict.get('name', ''),
            'about': user_dict.get('about', ''),
            'id': user_dict.get('id', '')
        }

    return user_dict
Example #57
0
    def new(self, data=None, errors=None, error_summary=None):
        '''GET to display a form for registering a new user.
           or POST the form data to actually do the user registration.
        '''

        temp_schema = self._new_form_to_db_schema()
        if temp_schema.has_key('name'):
            temp_schema['name'] = [
                name_validator_with_changed_msg
                if var == name_validator else var
                for var in temp_schema['name']
            ]

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj,
            'schema': temp_schema,
            'save': 'save' in request.params
        }

        try:
            check_access('user_create', context)
        except NotAuthorized:
            abort(401, _('Unauthorized to create a user'))

        if context['save'] and not data:
            return self._save_new(context)

        if c.user and not data:
            # #1799 Don't offer the registration form if already logged in
            return render('user/logout_first.html')

        data = data or {}
        errors = errors or {}
        error_summary = error_summary or {}
        vars = {
            'data': data,
            'errors': errors,
            'error_summary': error_summary,
            'capcha_api_key':
            configuration.config.get('ckan.recaptcha.publickey')
        }

        c.is_sysadmin = new_authz.is_sysadmin(c.user)
        c.form = render(self.new_user_form, extra_vars=vars)
        return render('user/new.html')
Example #58
0
def _user_has_minumum_role(context):
    """
    Determines whether the user has the minimum required role
    as specific in configuration. This is deliberately verbose.
    """
    roles = ['editor', 'admin', 'sysadmin']
    user = context['user']
    userobj = model.User.get(user)

    # Do we have a configured minimum role, if not just say ok now.
    minimum_role = config.get('ckanext.webhooks.minimum_auth', '').lower()
    if not minimum_role or minimum_role.lower() == 'none':
        return {'success': True}

    # Validate that the config option is valid and refuse, if we added
    # the option we probably wanted it to be *something*.
    if not minimum_role in roles:
        log.warning("ckanext.webhooks.minimum_auth has an invalid option")
        return {'success': False}

    # Always let sysadmins do their thing.
    if new_authz.is_sysadmin(user):
        return {'success': True}

    # We let sysadmins in just not, so just refuse if we get here.
    if minimum_role == 'sysadmin':
        return {'success': False}

    # Determine if the user has the required role in any organization
    q = model.Session.query(model.Member) \
        .filter(model.Member.table_name == 'user') \
        .filter(model.Member.table_id == userobj.id) \
        .filter(model.Member.state == 'active')
    roles_for_user = [m.capacity for m in q.all()]

    # If we want admins, let in anyone who has admin
    if minimum_role == 'admin':
        if 'admin' in roles_for_user:
            return {'success': True}

    # Only allow users who have editor
    if minimum_role == 'editor':
        if 'editor' in roles_for_user  or 'admin' in roles_for_user:
            return {'success': True}

    return {'success': False}