Esempio n. 1
0
 def _process(self):
     regforms = RegistrationForm.find_all(
         RegistrationForm.publish_registrations_enabled,
         event_id=int(self.event.id))
     query = (Registration.find(
         Registration.event_id == self.event.id,
         RegistrationForm.publish_registrations_enabled,
         ~RegistrationForm.is_deleted,
         ~Registration.is_deleted,
         _join=Registration.registration_form).order_by(
             db.func.lower(Registration.last_name),
             db.func.lower(Registration.first_name)))
     registrations = [(reg.get_full_name(), reg.get_personal_data())
                      for reg in query]
     enabled_pd_fields = {
         field.personal_data_type
         for reg in regforms for field in reg.active_fields
     }
     affiliation_enabled = PersonalDataType.affiliation in enabled_pd_fields
     position_enabled = PersonalDataType.position in enabled_pd_fields
     published = bool(
         RegistrationForm.find(
             RegistrationForm.publish_registrations_enabled,
             RegistrationForm.event_id == int(self.event.id)).count())
     return self.view_class.render_template(
         'display/participant_list.html',
         self.event,
         event=self.event,
         regforms=regforms,
         show_affiliation=affiliation_enabled
         and any(pd.get('affiliation') for reg, pd in registrations),
         show_position=position_enabled
         and any(pd.get('position') for reg, pd in registrations),
         registrations=registrations,
         published=published)
Esempio n. 2
0
 def _process(self):
     regforms = RegistrationForm.find_all(RegistrationForm.publish_registrations_enabled,
                                          event_id=int(self.event.id))
     query = (Registration
              .find(Registration.event_id == self.event.id,
                    Registration.state == RegistrationState.complete,
                    RegistrationForm.publish_registrations_enabled,
                    ~RegistrationForm.is_deleted,
                    ~Registration.is_deleted,
                    _join=Registration.registration_form)
              .order_by(db.func.lower(Registration.last_name), db.func.lower(Registration.first_name)))
     registrations = [(reg.get_full_name(), reg.get_personal_data()) for reg in query]
     enabled_pd_fields = {field.personal_data_type for reg in regforms for field in reg.active_fields}
     affiliation_enabled = PersonalDataType.affiliation in enabled_pd_fields
     position_enabled = PersonalDataType.position in enabled_pd_fields
     published = bool(RegistrationForm.find(RegistrationForm.publish_registrations_enabled,
                      RegistrationForm.event_id == int(self.event.id)).count())
     return self.view_class.render_template(
         'display/participant_list.html',
         self.event,
         event=self.event,
         regforms=regforms,
         show_affiliation=affiliation_enabled and any(pd.get('affiliation') for reg, pd in registrations),
         show_position=position_enabled and any(pd.get('position') for reg, pd in registrations),
         registrations=registrations,
         published=published
     )
Esempio n. 3
0
 def _process(self):
     participant_visibility = (PublishRegistrationsMode.hide_all
                               if self.event.type_ == EventType.conference
                               else PublishRegistrationsMode.show_all)
     public_visibility = PublishRegistrationsMode.hide_all
     form = RegistrationFormCreateForm(event=self.event,
                                       visibility=[participant_visibility.name, public_visibility.name, None])
     if form.validate_on_submit():
         regform = RegistrationForm(event=self.event, currency=payment_settings.get('currency'))
         create_personal_data_fields(regform)
         form.populate_obj(regform, skip=['visibility'])
         participant_visibility, public_visibility, visibility_duration = form.visibility.data
         regform.publish_registrations_participants = PublishRegistrationsMode[participant_visibility]
         regform.publish_registrations_public = PublishRegistrationsMode[public_visibility]
         regform.publish_registrations_duration = (timedelta(days=visibility_duration*30)
                                                   if visibility_duration is not None else None)
         db.session.add(regform)
         db.session.flush()
         signals.event.registration_form_created.send(regform)
         flash(_('Registration form has been successfully created'), 'success')
         self.event.log(EventLogRealm.management, LogKind.positive, 'Registration',
                        f'Registration form "{regform.title}" has been created', session.user)
         return redirect(url_for('.manage_regform', regform))
     return WPManageRegistration.render_template('management/regform_create.html', self.event,
                                                 form=form, regform=None)
Esempio n. 4
0
    def _process(self):
        regform = self.event.participation_regform
        registration_enabled = self.event.has_feature('registration')
        participant_visibility = (PublishRegistrationsMode.show_with_consent
                                  if self.event.type_ == EventType.lecture
                                  else PublishRegistrationsMode.show_all)
        public_visibility = (PublishRegistrationsMode.show_with_consent
                             if self.event.type_ == EventType.lecture
                             else PublishRegistrationsMode.show_all)
        form = RegistrationFormCreateForm(title='Participants',
                                          visibility=[participant_visibility.name, public_visibility.name, None])
        if form.validate_on_submit():
            set_feature_enabled(self.event, 'registration', True)
            if not regform:
                regform = RegistrationForm(event=self.event, is_participation=True,
                                           currency=payment_settings.get('currency'))
                create_personal_data_fields(regform)
                form.populate_obj(regform, skip=['visibility'])
                participant_visibility, public_visibility, visibility_duration = form.visibility.data
                regform.publish_registrations_participants = PublishRegistrationsMode[participant_visibility]
                regform.publish_registrations_public = PublishRegistrationsMode[public_visibility]
                regform.publish_registrations_duration = (timedelta(days=visibility_duration*30)
                                                          if visibility_duration is not None else None)
                db.session.add(regform)
                db.session.flush()
                signals.event.registration_form_created.send(regform)
                self.event.log(EventLogRealm.management, LogKind.positive, 'Registration',
                               f'Registration form "{regform.title}" has been created', session.user)
            return redirect(url_for('event_registration.manage_regform', regform))

        if not regform or not registration_enabled:
            return WPManageParticipants.render_template('management/participants.html', self.event, form=form,
                                                        regform=regform, registration_enabled=registration_enabled)
        return redirect(url_for('event_registration.manage_regform', regform))
Esempio n. 5
0
    def migrate_regforms(self):
        try:
            self.old_participation = self.conf._participation
        except AttributeError:
            self.print_info('Event has no participation')
            return
        if not self.old_participation._participantList and not self.old_participation._pendingParticipantList:
            self.print_info('Participant lists are empty')
            return

        set_feature_enabled(self.event, 'registration', True)

        with db.session.no_autoflush:
            self.regform = RegistrationForm(
                event_id=self.event.id,
                title=PARTICIPATION_FORM_TITLE,
                is_participation=True,
                currency=payment_settings.get('currency'))
            if not self.quiet:
                self.print_success('%[cyan]{}'.format(self.regform.title))
            self._migrate_settings()
            self._create_form()
            self._migrate_participants()

        db.session.add(self.regform)
        db.session.flush()
Esempio n. 6
0
def _get_open_regforms(event):
    if not event.has_feature('registration'):
        return []
    from indico.modules.events.registration.models.forms import RegistrationForm
    return (RegistrationForm.find(RegistrationForm.is_open, event_id=int(event.id))
                            .order_by(db.func.lower(RegistrationForm.title))
                            .all())
Esempio n. 7
0
    def _process(self):
        regforms = (self.event_new.registration_forms
                    .filter(RegistrationForm.publish_registrations_enabled,
                            ~RegistrationForm.is_deleted)
                    .options(subqueryload('registrations').subqueryload('data').joinedload('field_data'))
                    .all())
        if registration_settings.get(self.event, 'merge_registration_forms'):
            tables = [self._merged_participant_list_table()]
        else:
            tables = []
            regforms_dict = {regform.id: regform for regform in regforms if regform.publish_registrations_enabled}
            for form_id in registration_settings.get_participant_list_form_ids(self.event):
                try:
                    regform = regforms_dict.pop(form_id)
                except KeyError:
                    # The settings might reference forms that are not available
                    # anymore (publishing was disabled, etc.)
                    continue
                tables.append(self._participant_list_table(regform))
            # There might be forms that have not been sorted by the user yet
            tables += map(self._participant_list_table, regforms_dict.viewvalues())

        published = bool(RegistrationForm.find(RegistrationForm.publish_registrations_enabled,
                                               RegistrationForm.event_id == int(self.event.id)).count())
        num_participants = sum(len(table['rows']) for table in tables)

        return self.view_class.render_template(
            'display/participant_list.html',
            self.event,
            event=self.event,
            regforms=regforms,
            tables=tables,
            published=published,
            num_participants=num_participants
        )
Esempio n. 8
0
    def _process(self):
        regforms = (RegistrationForm.query.with_parent(self.event)
                    .filter(RegistrationForm.is_participant_list_visible(self.event.is_user_registered(session.user)))
                    .options(subqueryload('registrations').subqueryload('data').joinedload('field_data'))
                    .all())
        if registration_settings.get(self.event, 'merge_registration_forms'):
            tables = [self._merged_participant_list_table()]
        else:
            tables = []
            regforms_dict = {regform.id: regform for regform in regforms}
            for form_id in registration_settings.get_participant_list_form_ids(self.event):
                try:
                    regform = regforms_dict.pop(form_id)
                except KeyError:
                    # The settings might reference forms that are not available
                    # anymore (publishing was disabled, etc.)
                    continue
                tables.append(self._participant_list_table(regform))
            # There might be forms that have not been sorted by the user yet
            tables.extend(map(self._participant_list_table, regforms_dict.values()))

        num_participants = sum(table['num_participants'] for table in tables)

        return self.view_class.render_template(
            'display/participant_list.html',
            self.event,
            tables=tables,
            published=bool(regforms),
            num_participants=num_participants
        )
Esempio n. 9
0
 def _process(self):
     form = RegistrationFormForm(
         event=self.event,
         publish_registrations_enabled=(self.event.type_ !=
                                        EventType.conference))
     if form.validate_on_submit():
         regform = RegistrationForm(event=self.event)
         create_personal_data_fields(regform)
         form.populate_obj(regform)
         db.session.add(regform)
         db.session.flush()
         signals.event.registration_form_created.send(regform)
         flash(_('Registration form has been successfully created'),
               'success')
         self.event.log(
             EventLogRealm.management, EventLogKind.positive,
             'Registration',
             'Registration form "{}" has been created'.format(
                 regform.title), session.user)
         return redirect(url_for('.manage_regform', regform))
     return WPManageRegistration.render_template(
         'management/regform_edit.html',
         self.event,
         form=form,
         regform=None)
Esempio n. 10
0
def _get_open_regforms(event):
    if not event.has_feature('registration'):
        return []
    from indico.modules.events.registration.models.forms import RegistrationForm
    return (RegistrationForm.find(RegistrationForm.is_open, event_id=int(event.id))
                            .order_by(db.func.lower(RegistrationForm.title))
                            .all())
Esempio n. 11
0
    def _form_validated(self, form, **kwargs):
        """
        Forbid to disable the tickets when access to CERN is requested and
        to use CERN access ticket template with regforms without active CERN access request.
        """
        if not isinstance(form, TicketsForm):
            return

        regform = RegistrationForm.get_one(request.view_args['reg_form_id'])
        if regform.cern_access_request and regform.cern_access_request.is_active and form.tickets_enabled.data is False:
            err = _(
                'This form is used to grant CERN site access so ticketing must be enabled'
            )
            form.tickets_enabled.errors.append(err)
            return False
        access_tpl = self.settings.get('access_ticket_template')
        ticket_template = DesignerTemplate.get_one(
            form.ticket_template_id.data)
        if not access_tpl:
            return
        if ticket_template == access_tpl or ticket_template.backside_template == access_tpl:
            if (not regform.cern_access_request
                    or (regform.cern_access_request
                        and regform.cern_access_request.request_state !=
                        CERNAccessRequestState.active)):
                form.ticket_template_id.errors.append(
                    _('The selected template can only be used with an '
                      'active CERN access request'))
                return False
Esempio n. 12
0
def dummy_regform(dummy_event, db):
    # event has to be in the future (badge request)
    dummy_event.start_dt += timedelta(days=1)
    dummy_event.end_dt += timedelta(days=1)
    regform = RegistrationForm(event=dummy_event, title="Dummy Registration Form", currency="CHF")
    create_personal_data_fields(regform)
    db.session.flush()
    return regform
Esempio n. 13
0
 def _visible_participant_list(event):
     if not event.has_feature('registration'):
         return False
     if not (RegistrationForm.query.with_parent(event)
             .filter(RegistrationForm.is_participant_list_visible(event.is_user_registered(session.user)))
             .has_rows()):
         return False
     return not any(values_from_signal(signals.event.hide_participant_list.send(event)))
Esempio n. 14
0
def dummy_regform(db, dummy_event):
    regform = RegistrationForm(event=dummy_event, title='Registration Form', currency='USD')
    create_personal_data_fields(regform)

    # enable all fields
    for field in regform.sections[0].fields:
        field.is_enabled = True
    db.session.add(regform)
    db.session.flush()
    return regform
Esempio n. 15
0
 def run(self):
     self.regform = RegistrationForm(event_id=int(self.event.id),
                                     title=PARTICIPATION_FORM_TITLE,
                                     is_participation=True)
     if not self.importer.quiet:
         self.importer.print_success(cformat('%{cyan}{}').format(
             self.regform.title),
                                     event_id=self.event.id)
     self._migrate_settings()
     self._create_form()
     self._migrate_participants()
Esempio n. 16
0
 def _visible_registration(event):
     if not event.has_feature('registration'):
         return False
     if RegistrationForm.find(RegistrationForm.is_scheduled, RegistrationForm.event_id == int(event.id)).count():
         return True
     if not session.user:
         return False
     return bool(Registration.find(Registration.user == session.user,
                                   Registration.event_id == int(event.id),
                                   ~Registration.is_deleted,
                                   ~RegistrationForm.is_deleted,
                                   _join=Registration.registration_form).count())
Esempio n. 17
0
 def _process_POST(self):
     regform = self.event_new.participation_regform
     set_feature_enabled(self.event_new, 'registration', True)
     if not regform:
         regform = RegistrationForm(event_new=self.event_new, title="Participants", is_participation=True,
                                    currency=payment_settings.get('currency'))
         create_personal_data_fields(regform)
         db.session.add(regform)
         db.session.flush()
         signals.event.registration_form_created.send(regform)
         self.event_new.log(EventLogRealm.management, EventLogKind.positive, 'Registration',
                            'Registration form "{}" has been created'.format(regform.title), session.user)
     return redirect(url_for('event_registration.manage_regform', regform))
Esempio n. 18
0
File: util.py Progetto: javfg/indico
def count_hidden_registrations(event, is_participant):
    """Get the number of hidden registrations for an event.

    :param event: the `Event` to get registrations for
    :param is_participant: whether the user accessing the registrations is a participant of the event
    :return: number of registrations
    """
    query = (Registration.query.with_parent(event).filter(
        Registration.is_state_publishable,
        ~Registration.is_publishable(is_participant),
        RegistrationForm.is_participant_list_visible(is_participant)).join(
            Registration.registration_form))

    return query.count()
Esempio n. 19
0
 def _visible_registration(event):
     if not event.has_feature('registration'):
         return False
     if RegistrationForm.find(RegistrationForm.is_scheduled,
                              RegistrationForm.event_id == int(
                                  event.id)).count():
         return True
     if not session.user:
         return False
     return bool(
         Registration.find(Registration.user == session.user,
                           Registration.event_id == int(event.id),
                           ~Registration.is_deleted,
                           ~RegistrationForm.is_deleted,
                           _join=Registration.registration_form).count())
Esempio n. 20
0
 def run(self, new_event, cloners, shared_data):
     # if the registration cloner is also enabled, we have to keep
     # all revisions since they are likely to be in use
     clone_all_revisions = 'registrations' in cloners
     attrs = get_simple_column_attrs(RegistrationForm) - {'start_dt', 'end_dt', 'modification_end_dt'}
     self._field_data_map = {}
     self._form_map = {}
     for old_form in self.old_event.registration_forms:
         new_form = RegistrationForm(**{attr: getattr(old_form, attr) for attr in attrs})
         self._clone_form_items(old_form, new_form, clone_all_revisions)
         new_event.registration_forms.append(new_form)
         db.session.flush()
         self._form_map[old_form] = new_form
     return {'form_map': self._form_map,
             'field_data_map': self._field_data_map}
Esempio n. 21
0
 def clone(self, new_event, options):
     if not options:
         return
     self._clone_with_registrations = 'registrations' in options
     attrs = get_simple_column_attrs(RegistrationForm) - {
         'start_dt', 'end_dt', 'modification_end_dt'
     }
     with db.session.no_autoflush:
         for old_form in self._find_registration_forms():
             new_form = RegistrationForm(
                 event_new=new_event.as_event,
                 **{attr: getattr(old_form, attr)
                    for attr in attrs})
             self._clone_form_items(old_form, new_form)
             if self._clone_with_registrations:
                 self._clone_registrations(old_form, new_form, new_event)
             db.session.add(new_form)
             db.session.flush()
Esempio n. 22
0
    def _process(self):
        regforms = (self.event_new.registration_forms.filter(
            RegistrationForm.publish_registrations_enabled,
            ~RegistrationForm.is_deleted).options(
                subqueryload('registrations').subqueryload('data').joinedload(
                    'field_data')).all())
        if registration_settings.get(self.event, 'merge_registration_forms'):
            tables = [self._merged_participant_list_table()]
        else:
            tables = []
            regforms_dict = {
                regform.id: regform
                for regform in regforms
                if regform.publish_registrations_enabled
            }
            for form_id in registration_settings.get_participant_list_form_ids(
                    self.event):
                try:
                    regform = regforms_dict.pop(form_id)
                except KeyError:
                    # The settings might reference forms that are not available
                    # anymore (publishing was disabled, etc.)
                    continue
                tables.append(self._participant_list_table(regform))
            # There might be forms that have not been sorted by the user yet
            tables += map(self._participant_list_table,
                          regforms_dict.viewvalues())

        published = bool(
            RegistrationForm.find(
                RegistrationForm.publish_registrations_enabled,
                RegistrationForm.event_id == int(self.event.id)).count())
        num_participants = sum(len(table['rows']) for table in tables)

        return self.view_class.render_template(
            'display/participant_list.html',
            self.event,
            event=self.event,
            regforms=regforms,
            tables=tables,
            published=published,
            num_participants=num_participants)
Esempio n. 23
0
 def _process(self):
     regforms = RegistrationForm.find_all(RegistrationForm.publish_registrations_enabled,
                                          event_id=int(self.event.id))
     query = (Registration
              .find(Registration.event_id == self.event.id,
                    RegistrationForm.publish_registrations_enabled,
                    ~RegistrationForm.is_deleted,
                    ~Registration.is_deleted,
                    _join=Registration.registration_form)
              .order_by(db.func.lower(Registration.last_name), db.func.lower(Registration.first_name)))
     registrations = [(reg.get_full_name(), reg.get_personal_data()) for reg in query]
     return self.view_class.render_template(
         'display/participant_list.html',
         self.event,
         event=self.event,
         regforms=regforms,
         show_affiliation=any(pd.get('affiliation') for reg, pd in registrations),
         show_position=any(pd.get('position') for reg, pd in registrations),
         registrations=registrations
     )
Esempio n. 24
0
 def has_data(self):
     return RegistrationForm.find(title=PARTICIPATION_FORM_TITLE).has_rows()
Esempio n. 25
0
def test_filter_contrib_entries(app, db, dummy_event, create_user,
                                create_contribution, create_registration):
    registered_user = create_user(1)
    registered_speaker = create_user(2)
    unregistered_user = create_user(3)
    dummy_regform = RegistrationForm(event=dummy_event,
                                     title='Registration Form',
                                     currency='USD')
    dummy_event.registrations.append(
        create_registration(registered_user, dummy_regform))
    dummy_event.registrations.append(
        create_registration(registered_speaker, dummy_regform))
    registered_speaker_contribution = create_contribution(
        dummy_event,
        'Registered Speaker',
        person_links=[
            ContributionPersonLink(person=EventPerson.create_from_user(
                registered_speaker, dummy_event),
                                   is_speaker=True)
        ])
    registered_speaker_author_contribution = create_contribution(
        dummy_event,
        'Registered Speaker Author',
        person_links=[
            ContributionPersonLink(person=EventPerson.for_user(
                registered_speaker, dummy_event),
                                   is_speaker=True,
                                   author_type=AuthorType.primary)
        ])
    unregistered_speaker_registered_author_contribution = create_contribution(
        dummy_event,
        'Unregistered Speaker, Registered Author',
        person_links=[
            ContributionPersonLink(person=EventPerson.for_user(
                unregistered_user, dummy_event),
                                   is_speaker=True),
            ContributionPersonLink(person=EventPerson.for_user(
                registered_user, dummy_event),
                                   author_type=AuthorType.primary)
        ])
    registered_speaker_unregistered_author_contribution = create_contribution(
        dummy_event,
        'Registered Speaker, Unregistered Author',
        person_links=[
            ContributionPersonLink(person=EventPerson.for_user(
                registered_user, dummy_event),
                                   is_speaker=True),
            ContributionPersonLink(person=EventPerson.for_user(
                unregistered_user, dummy_event),
                                   author_type=AuthorType.primary)
        ])
    # Filter contributions with registered users
    with app.test_request_context():
        list_gen = ContributionListGenerator(dummy_event)
        list_gen.list_config['filters'] = {'items': {'people': {'registered'}}}
        result = list_gen.get_list_kwargs()
    assert result['contribs'] == [
        registered_speaker_contribution,
        registered_speaker_author_contribution,
        unregistered_speaker_registered_author_contribution,
        registered_speaker_unregistered_author_contribution
    ]

    # Filter contributions with registered speakers
    list_gen.list_config['filters'] = {'items': {'speakers': {'registered'}}}
    with app.test_request_context():
        result = list_gen.get_list_kwargs()
    assert result['contribs'] == [
        registered_speaker_contribution,
        registered_speaker_author_contribution,
        registered_speaker_unregistered_author_contribution
    ]

    # Filter contributions with unregistered speakers and registered users
    list_gen.list_config['filters'] = {
        'items': {
            'speakers': {'not_registered'},
            'people': {'registered'}
        }
    }
    with app.test_request_context():
        result = list_gen.get_list_kwargs()
    assert result['contribs'] == [
        unregistered_speaker_registered_author_contribution
    ]
Esempio n. 26
0
 def _find_registration_forms(self):
     return RegistrationForm.find(~RegistrationForm.is_deleted,
                                  RegistrationForm.event_id == int(self.event.id))
Esempio n. 27
0
 def has_data(self):
     return bool(
         RegistrationForm.find(title=PARTICIPATION_FORM_TITLE).count())
Esempio n. 28
0
 def has_data(self):
     return RegistrationForm.find(title=PARTICIPATION_FORM_TITLE).has_rows()
Esempio n. 29
0
 def _checkParams(self):
     self.regform = (
         RegistrationForm.find(id=request.view_args["reg_form_id"], is_deleted=False)
         .options(defaultload("form_items").joinedload("children").joinedload("current_data"))
         .one()
     )
Esempio n. 30
0
 def _find_registration_forms(self):
     return RegistrationForm.find(
         ~RegistrationForm.is_deleted,
         RegistrationForm.event_id == int(self.event.id))
Esempio n. 31
0
File: user.py Progetto: javfg/indico
        else:
            category_role = CategoryRole.get_category_role_by_id(
                category, category_role_id)
        if category_role is None:
            raise ValueError(f'Invalid category role: {category_role_id}')
        return category_role
    elif type_ == 'RegistrationForm':
        if not allow_registration_forms:
            raise ValueError('Registration forms are not allowed')

        try:
            reg_form_id = int(data)
        except ValueError:
            raise ValueError('Invalid data')

        registration_form = RegistrationForm.get(
            reg_form_id, is_deleted=(None if soft_fail else False))
        if registration_form is None or registration_form.event_id != event_id:
            raise ValueError(f'Invalid registration form: {reg_form_id}')
        return registration_form
    elif type_ == 'Email':
        if not allow_emails:
            raise ValueError('Emails are not allowed')
        return EmailPrincipal(data)
    elif type_ == 'IPNetworkGroup':
        if not allow_networks:
            raise ValueError('Network groups are not allowed')
        try:
            netgroup_id = int(data)
        except ValueError:
            raise ValueError('Invalid data')
        netgroup = IPNetworkGroup.get(netgroup_id)
Esempio n. 32
0
 def has_data(self):
     return bool(RegistrationForm.find(title=PARTICIPATION_FORM_TITLE).count())
Esempio n. 33
0
 def _visible_participant_list(event):
     if not event.has_feature('registration'):
         return False
     return bool(RegistrationForm.find(RegistrationForm.publish_registrations_enabled,
                                       RegistrationForm.event_id == int(event.id)).count())
Esempio n. 34
0
File: user.py Progetto: wdbm/indico
def principal_from_fossil(fossil, allow_pending=False, allow_groups=True, allow_missing_groups=False,
                          allow_emails=False, allow_networks=False, allow_registration_forms=False,
                          existing_data=None, event=None, category=None):
    from indico.modules.networks.models.networks import IPNetworkGroup
    from indico.modules.events.models.roles import EventRole
    from indico.modules.categories.models.roles import CategoryRole
    from indico.modules.events.registration.models.forms import RegistrationForm
    from indico.modules.groups import GroupProxy
    from indico.modules.users import User

    if event and category is None:
        category = event.category

    if existing_data is None:
        existing_data = set()

    type_ = fossil['_type']
    id_ = fossil['id']
    if type_ == 'Avatar':
        if isinstance(id_, int) or id_.isdigit():
            # regular user
            user = User.get(int(id_))
        elif allow_pending:
            data = GenericCache('pending_identities').get(id_)
            if not data:
                raise ValueError("Cannot find user '{}' in cache".format(id_))

            data = {k: '' if v is None else v for k, v in data.items()}
            email = data['email'].lower()

            # check if there is not already a (pending) user with that e-mail
            # we need to check for non-pending users too since the search may
            # show a user from external results even though the email belongs
            # to an indico account in case some of the search criteria did not
            # match the indico account
            user = User.query.filter(User.all_emails == email, ~User.is_deleted).first()
            if not user:
                user = User(first_name=data.get('first_name') or '', last_name=data.get('last_name') or '',
                            email=email,
                            address=data.get('address', ''), phone=data.get('phone', ''),
                            affiliation=data.get('affiliation', ''), is_pending=True)
                db.session.add(user)
                db.session.flush()
        else:
            raise ValueError("Id '{}' is not a number and allow_pending=False".format(id_))
        if user is None:
            raise ValueError('User does not exist: {}'.format(id_))
        return user
    elif allow_emails and type_ == 'Email':
        return EmailPrincipal(id_)
    elif allow_networks and type_ == 'IPNetworkGroup':
        group = IPNetworkGroup.get(int(id_))
        if group is None or (group.hidden and group not in existing_data):
            raise ValueError('IP network group does not exist: {}'.format(id_))
        return group
    elif allow_groups and type_ in {'LocalGroupWrapper', 'LocalGroup'}:
        group = GroupProxy(int(id_))
        if group.group is None:
            raise ValueError('Local group does not exist: {}'.format(id_))
        return group
    elif allow_groups and type_ in {'LDAPGroupWrapper', 'MultipassGroup'}:
        provider = fossil['provider']
        group = GroupProxy(id_, provider)
        if group.group is None and not allow_missing_groups:
            raise ValueError('Multipass group does not exist: {}:{}'.format(provider, id_))
        return group
    elif category and type_ == 'CategoryRole':
        role = CategoryRole.get_category_role_by_id(category, id_)
        role_name = fossil.get('name')
        if role is None:
            raise ValueError('Category role "{}" is not available in "{}"'.format(role_name, category.title))
        return role
    elif event and type_ == 'EventRole':
        role = EventRole.get(id_)
        role_name = fossil.get('name')
        if role is None:
            raise ValueError('Event role "{}" does not exist'.format(role_name))
        if role.event != event:
            raise ValueError('Event role "{}" does not belong to "{}"'.format(role_name, event.title))
        return role
    elif allow_registration_forms and type_ == 'RegistrationForm':
        registration_form = RegistrationForm.get(id_)
        reg_form_name = fossil.get('title')
        if registration_form is None:
            raise ValueError('Registration form "{}" does not exist'.format(reg_form_name))
        if registration_form.event != event:
            raise ValueError('Registration form "{}" does not belong to "{}"'.format(reg_form_name, event.title))
        return registration_form
    else:
        raise ValueError('Unexpected fossil type: {}'.format(type_))
Esempio n. 35
0
File: user.py Progetto: wdbm/indico
def principal_from_identifier(identifier, allow_groups=False, allow_external_users=False, allow_event_roles=False,
                              allow_category_roles=False, allow_registration_forms=False, allow_emails=False,
                              event_id=None, soft_fail=False):
    from indico.modules.events.models.events import Event
    from indico.modules.events.models.roles import EventRole
    from indico.modules.categories.models.roles import CategoryRole
    from indico.modules.events.registration.models.forms import RegistrationForm
    from indico.modules.groups import GroupProxy
    from indico.modules.users import User

    try:
        type_, data = identifier.split(':', 1)
    except ValueError:
        raise ValueError('Invalid data')
    if type_ == 'User':
        try:
            user_id = int(data)
        except ValueError:
            raise ValueError('Invalid data')
        user = User.get(user_id, is_deleted=(None if soft_fail else False))
        if user is None:
            raise ValueError('Invalid user: {}'.format(user_id))
        return user
    elif type_ == 'ExternalUser':
        if not allow_external_users:
            raise ValueError('External users are not allowed')
        cache = GenericCache('external-user')
        external_user_data = cache.get(data)
        if not external_user_data:
            raise ValueError('Invalid data')
        user = User.query.filter(User.all_emails == external_user_data['email'], ~User.is_deleted).first()
        if user:
            return user
        # create a pending user. this user isn't sent to the DB unless it gets added
        # to the sqlalchemy session somehow (e.g. by adding it to an ACL).
        # like this processing form data does not result in something being stored in
        # the database, which is good!
        return User(first_name=external_user_data['first_name'], last_name=external_user_data['last_name'],
                    email=external_user_data['email'], affiliation=external_user_data['affiliation'],
                    address=external_user_data['address'], phone=external_user_data['phone'], is_pending=True)
    elif type_ == 'Group':
        if not allow_groups:
            raise ValueError('Groups are not allowed')
        try:
            provider, name = data.split(':', 1)
        except ValueError:
            raise ValueError('Invalid data')
        if not provider:
            # local group
            try:
                group_id = int(name)
            except ValueError:
                raise ValueError('Invalid data')
            group = GroupProxy(group_id)
        else:
            # multipass group
            group = GroupProxy(name, provider)
        if not soft_fail and group.group is None:
            raise ValueError('Invalid group: {}'.format(data))
        return group
    elif type_ == 'EventRole':
        if not allow_event_roles:
            raise ValueError('Event roles are not allowed')
        try:
            event_role_id = int(data)
        except ValueError:
            raise ValueError('Invalid data')
        event_role = EventRole.get(event_role_id)
        if event_role is None or event_role.event_id != event_id:
            raise ValueError('Invalid event role: {}'.format(event_role_id))
        return event_role
    elif type_ == 'CategoryRole':
        if not allow_category_roles:
            raise ValueError('Category roles are not allowed')
        event = Event.get(event_id)
        if event is None:
            raise ValueError('Invalid event id: {}'.format(event_id))
        try:
            category_role_id = int(data)
        except ValueError:
            raise ValueError('Invalid data')
        if soft_fail:
            category_role = CategoryRole.get(category_role_id)
        else:
            category_role = CategoryRole.get_category_role_by_id(event.category, category_role_id)
        if category_role is None:
            raise ValueError('Invalid category role: {}'.format(category_role_id))
        return category_role
    elif type_ == 'RegistrationForm':
        if not allow_registration_forms:
            raise ValueError('Registration forms are not allowed')

        try:
            reg_form_id = int(data)
        except ValueError:
            raise ValueError('Invalid data')

        registration_form = RegistrationForm.get(reg_form_id, is_deleted=(None if soft_fail else False))
        if registration_form is None or registration_form.event_id != event_id:
            raise ValueError('Invalid registration form: {}'.format(reg_form_id))
        return registration_form
    elif type_ == 'Email':
        if not allow_emails:
            raise ValueError('Emails are not allowed')
        return EmailPrincipal(data)
    else:
        raise ValueError('Invalid data')