Пример #1
0
def user_is_term_manager(uuid, user: User):
    if not user or not uuid:
        raise PermissionDenied()
    identity = get_identity(user)
    permission = Permission(ObjectSourceTermManager(uuid))
    if permission.allows(identity):
        return True
    raise PermissionDenied()
Пример #2
0
def user_has_edit_permission(source, user: User):
    if not user or not source:
        raise PermissionDenied()
    try:
        if user_has_manager_permission(source, user):
            return True
    except PermissionDenied as err:
        pass

    identity = get_identity(user)
    perm = Permission(ObjectSourceEditor(source.id))
    if perm.allows(identity):
        return True
    raise PermissionDenied()
Пример #3
0
def set_organization_manager(user, uuid, allow=False):
    """
    Set user as manager of a organization
    :param uuid: organization or term uuid
    :param user: user id
    :param allow: if allow or deny
    :return:
    """
    try:
        userObj = User.query.filter_by(id=user).first()
        if not userObj:
            raise Exception('User not found')
        org = CuorHelper.query_cuor_by_uuid(uuid)
        if not org:
            raise Exception('Organization not found')
        parents = CuorHelper.get_relationships_parent(org)
        print(parents)
        allow_parent = False
        for p in parents:
            try:
                allow_parent = user_is_organization_manager(
                    p['id'], current_user)
            except PermissionDenied:
                pass

        if is_user_sources_admin(current_user) or \
            allow_parent or \
            user_is_organization_manager(org['id'], current_user):
            with db.session.begin_nested():
                ActionUsers.query.filter_by(
                    user_id=user,
                    action='source_organization_manager_actions',
                    argument=uuid).delete()
                if allow:
                    db.session.add(
                        ActionUsers.allow(
                            ObjectSourceOrganizationManager(uuid),
                            user=userObj))
                else:
                    db.session.add(
                        ActionUsers.deny(ObjectSourceOrganizationManager(uuid),
                                         user=userObj))
            db.session.commit()
            return iroko_json_response(IrokoResponseStatus.SUCCESS, 'ok',
                                       'permission', {
                                           'org': uuid,
                                           'user': user,
                                           'permission': 'manager',
                                           'allow': allow
                                       })

        raise PermissionDenied()

    except PermissionDenied as err:
        msg = 'Permission denied'
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
    except Exception as e:
        return iroko_json_response(IrokoResponseStatus.ERROR, str(e), None,
                                   None)
Пример #4
0
	def __enter__(self):
		permission = getattr(Permissions, self.key)
		if permission is None or isinstance(permission, PluginPermissionDecorator):
			raise UnknownPermission(self.key)

		# check the permission here
		if not permission.can():
			if self.http_exception:
				abort(self.http_exception, permission)
			raise PermissionDenied(permission)
Пример #5
0
def set_term_manager(user, uuid, allow=False):
    """
    Set user as manager of a organization
    :param uuid: organization or term uuid
    :param user: user id
    :param allow: if allow or deny
    :return:
    """
    try:
        userObj = User.query.filter_by(id=user).first()
        if not userObj:
            raise Exception('User not found')
        term = Term.query.filter_by(uuid=uuid).first()
        if not term:
            raise Exception('Term not found')
        parent = None
        if term.parent_id:
            parent = Term.query.filter_by(id=term.parent_id).first()

        if is_user_sources_admin(current_user) or \
            user_is_term_manager(term.uuid, current_user) or \
            (parent and user_is_term_manager(parent.uuid, current_user)):

            with db.session.begin_nested():
                ActionUsers.query.filter_by(
                    user_id=user,
                    action='source_term_manager_actions',
                    argument=uuid).delete()
                if allow:
                    db.session.add(
                        ActionUsers.allow(ObjectSourceTermManager(uuid),
                                          user=userObj))
                else:
                    db.session.add(
                        ActionUsers.deny(ObjectSourceTermManager(uuid),
                                         user=userObj))
            db.session.commit()
            return iroko_json_response(
                IrokoResponseStatus.SUCCESS, 'ok', 'permission', {
                    'term': uuid,
                    'user': user,
                    'permission': 'manager',
                    'allow': allow
                })

        raise PermissionDenied()

    except PermissionDenied as err:
        msg = 'Permission denied'
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
    except Exception as e:
        return iroko_json_response(IrokoResponseStatus.ERROR, str(e), None,
                                   None)
Пример #6
0
def user_has_manager_permission(source, user: User):
    if not user or not source:
        raise PermissionDenied()

    identity = get_identity(user)

    permission = Permission(source_full_manager_actions)
    if permission.allows(identity):
        return True

    permiso = Permission(ObjectSourceManager(source.id))
    if permiso.allows(identity):
        return True

    if 'classifications' in source.model.json:
        for term in source.model.json['classifications']:
            if 'id' in term:
                try:
                    permiso = Permission(ObjectSourceTermManager(term['id']))
                    if permiso.allows(identity):
                        return True
                except Exception as e:
                    pass

    if 'organizations' in source.model.json:
        for org in source.model.json['organizations']:
            if 'id' in org:
                try:
                    permiso = Permission(
                        ObjectSourceOrganizationManager(org['id']))
                    if permiso.allows(identity):
                        return True
                except Exception as e:
                    pass

    raise PermissionDenied()
Пример #7
0
def set_source_editor(user, uuid, allow=False):
    """
    Set user as editor of a source
    :param uuid: source uuid
    :param user: user id
    :param allow: if allow or deny
    :return:
    """
    try:
        offset = request.args.get('offset') if request.args.get(
            'offset') else 3
        source = SourceRecord.get_record(uuid)
        if not source:
            raise Exception('Not source found')
        userObj = User.query.filter_by(id=user).first()
        if not userObj:
            raise Exception('User not found')

        if source.user_has_manager_permission(current_user):
            with db.session.begin_nested():
                ActionUsers.query.filter_by(user_id=user,
                                            action='source_editor_actions',
                                            argument=uuid).delete()
                if allow:
                    db.session.add(
                        ActionUsers.allow(ObjectSourceEditor(uuid),
                                          user=userObj))
                else:
                    db.session.add(
                        ActionUsers.deny(ObjectSourceEditor(uuid),
                                         user=userObj))
            db.session.commit()
            return iroko_json_response(
                IrokoResponseStatus.SUCCESS, 'ok', 'permission', {
                    'source': uuid,
                    'user': user,
                    'permission': 'editor',
                    'allow': allow
                })
        raise PermissionDenied()

    except PermissionDenied as err:
        msg = 'Permission denied'
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
    except Exception as e:
        return iroko_json_response(IrokoResponseStatus.ERROR, str(e), None,
                                   None)
Пример #8
0
def get_source_by_uuid(uuid):
    """Get all source versions by source UUID, with permission checking"""
    # source = SourcesDeprecated.get_source_by_id(uuid=uuid)
    # return iroko_json_response(IrokoResponseStatus.SUCCESS, \
    #                             'ok','versions', \
    #                             source_schema.dump(source))
    try:
        source = SourceRecord.get_record(uuid)
        # SourcesDeprecated.get_source_by_id(uuid=uuid)
        if not source:
            raise Exception('Source not found')

        terms = helper_get_classifications_string(source)
        #
        # # print(source.model.json)
        # if 'classifications' in source.model.json:
        #     for term in source.model.json['classifications']:
        #         if 'id' in term:
        #             terms = terms + str(term['id']) + ','
        # if terms:
        #     terms = terms[0:-1]

        if user_has_editor_or_manager_permissions({
                'terms': terms,
                'uuid': uuid
        }):
            # # # print(source.data)
            # for v in source.term_sources:
            #     # print(v.term_id, v.sources_id, v.data)
            #     # # print(v.data)
            versions = IrokoSourceVersions.get_versions(uuid)
            return iroko_json_response(
                IrokoResponseStatus.SUCCESS, \
                'ok', 'versions', \
                source_version_schema_many.dump(versions)
                )

        raise PermissionDenied('No tiene permiso')

    except Exception as e:
        # print(traceback.format_exc())
        return iroko_json_response(IrokoResponseStatus.ERROR, str(e), None,
                                   None)
Пример #9
0
def source_organization_manager_permission_factory(obj):
    permission = Permission(source_full_manager_actions)
    current_identity = get_identity(current_user)
    if permission.allows(current_identity):
        return permission

    permiso = None
    permiso = Permission(ObjectSourceManager(obj['uuid']))
    if permiso:
        return permiso

    aux = obj['orgs']
    orgs = aux.split(',')
    permiso = None

    for org_uuid in orgs:
        try:
            permiso = Permission(ObjectSourceOrganizationManager(org_uuid))
            if permiso:
                return permiso
        except Exception as e:
            raise e
    raise PermissionDenied('No tiene permisos de gestión')
Пример #10
0
 def __enter__(self):
     # check the permission here
     if not self.can():
         if self.http_exception:
             abort(self.http_exception, self.permission)
         raise PermissionDenied(self.permission)
Пример #11
0
    def dispatch_request(self):
        period = request.args.get('period') or get_default_period()
        subject = request.args.get('subject')
        group = request.args.get('group')
        region = request.args.get('region')
        action = request.args.get('action')
        rowid = request.args.get('rowid')
        fresh_new_record = False

        self.objects = []
        self.restricted_countries = []
        self.auto_objects = []
        self.manual_objects = []
        self.setup_objects_and_data(period, subject, region)
        group = group or self.get_group_for_subject(subject)

        regions = self.get_regions(period, subject)
        summary_filter_form = SummaryFilterForm(
            MultiDict(
                dict(period=period,
                     group=group,
                     subject=subject,
                     region=region)))
        summary_filter_form.group.choices = self.get_groups(period)
        summary_filter_form.subject.choices = self.get_subjects(period, group)
        summary_filter_form.region.choices = regions

        manual_form, manual_assessment = self.get_manual_form(
            request.form,
            period=period,
            action=action,
        )
        manual_form.region.choices = self.get_regions(period, subject, True)
        if period != '4':
            manual_form.region.choices = manual_form.region.choices[1:]
        if not request.form.get('region'):
            manual_form.region.process_data(region or manual_form.region.data)
        if hasattr(manual_form, 'MS'):
            manual_form.kwargs = dict(subject=subject, period=period)
            manual_form.MS.choices = self.get_user_MS(subject, region, period)

        if request.method == 'POST':
            home_url = url_for(self.summary_endpoint,
                               period=period,
                               subject=subject,
                               region=region)
            if manual_form.validate(subject=subject, period=period):
                if not can_touch(manual_assessment):
                    raise PermissionDenied()

                if not manual_assessment:
                    manual_assessment = self.model_manual_cls(subject=subject)
                    manual_form.populate_obj(manual_assessment)
                    manual_assessment.last_update = datetime.now().strftime(
                        DATE_FORMAT)
                    if EU_ASSESSMENT_MODE:
                        user = RegisteredUser.query.filter_by(
                            id='test_for_eu_assessment').first()
                        if not user:

                            user = RegisteredUser(
                                id='test_for_eu_assessment',
                                name='Test_for_eu_assessment',
                                account_date=datetime.now())
                            db.session.add(user)
                            db.session.commit()
                        manual_assessment.user_id = user.id

                    else:
                        manual_assessment.user_id = current_user.id
                    manual_assessment.dataset_id = period
                    db.session.flush()
                    db.session.add(manual_assessment)
                    try:
                        db.session.commit()
                    except IntegrityError:
                        db.session.rollback()
                        flash('A record with the same keys exist. Cannot add',
                              'error')
                    else:
                        flash('Conclusion added successfully')
                        fresh_new_record = manual_assessment
                    manual_assessment = None
                else:
                    manual_form.populate_obj(manual_assessment)
                    manual_assessment.last_update = datetime.now().strftime(
                        DATE_FORMAT)
                    db.session.add(manual_assessment)
                    db.session.commit()
                    flash('Conclusion edited successfully')
                    if rowid:
                        home_url += '#man-row-' + rowid
                    return redirect(home_url)
            else:
                flash('Please correct the errors below and try again.')

        self.dataset = Dataset.query.get(period)
        period_name = self.dataset.name if self.dataset else ''

        current_selection = self.get_current_selection(period_name, group,
                                                       subject, region, period)
        annexes = self.get_annexes(subject, period)
        default_ms = DEFAULT_MS if not nat_perm.can() else current_user.MS
        context = self.get_context()
        context.update({
            'objects':
            self.objects,
            'auto_objects':
            self.auto_objects,
            'manual_objects':
            self.filter_conclusions(self.manual_objects),
            'restricted_countries':
            self.restricted_countries,
            'regions':
            regions,
            'summary_filter_form':
            summary_filter_form,
            'manual_form':
            manual_form,
            'manual_assessment':
            manual_assessment,
            'edit_ref':
            must_edit_ref(manual_assessment),
            'current_selection':
            current_selection,
            'annexes':
            annexes,
            'group':
            group,
            'subject':
            subject,
            'region':
            region,
            'period_name':
            period_name,
            'dataset':
            self.dataset,
            'default_ms':
            default_ms,
            'fresh_new_record':
            fresh_new_record,
        })

        return render_template(self.template_name, **context)