def setUp(self): super(TestDraftRegistrationUpdate, self).setUp() self.schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=self.schema, branched_from=self.public_project ) self.prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.prereg_draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=self.prereg_schema, branched_from=self.public_project ) self.registration_metadata = self.prereg_metadata(self.prereg_draft_registration) self.other_project = ProjectFactory(creator=self.user) self.url = '/{}nodes/{}/draft_registrations/{}/'.format(API_BASE, self.public_project._id, self.draft_registration._id) self.payload = { "data": { "id": self.draft_registration._id, "type": "draft_registrations", "attributes": { "registration_metadata": { "datacompletion": { "value": "No, data collection has not begun" }, "looked": { "value": "No" }, "comments": { "value": "This is my first registration." } } } } }
def test_on_complete_embargo_creates_registration_for_draft_initiator( self, mock_enquque): user = factories.UserFactory() end_date = timezone.now() + datetime.timedelta( days=366) # <- leap year approval = DraftRegistrationApproval( meta={ 'registration_choice': 'embargo', 'embargo_end_date': end_date.isoformat() }) approval.save() project = factories.ProjectFactory(creator=user) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2)) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) draft.approval = approval draft.save() approval._on_complete(user) draft.reload() registered_node = draft.registered_node assert registered_node is not None assert registered_node.is_pending_embargo assert registered_node.registered_user == draft.initiator
def test_required_metaschema_questions_not_required_on_post(self): prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) prereg_draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema, branched_from=self.public_project ) url = '/{}nodes/{}/draft_registrations/?embed=initiator&embed=branched_from'.format(API_BASE, self.public_project._id) registration_metadata = self.prereg_metadata(prereg_draft_registration) del registration_metadata['q1'] prereg_draft_registration.registration_metadata = registration_metadata prereg_draft_registration.save() payload = { "data": { "type": "draft_registrations", "attributes": { "registration_supplement": prereg_schema._id, "registration_metadata": registration_metadata } } } res = self.app.post_json_api(url, payload, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 201) data = res.json['data'] assert_equal(res.json['data']['attributes']['registration_metadata']['q2']['value'], 'Test response') assert_equal(data['attributes']['registration_supplement'], prereg_schema._id) assert_equal(data['embeds']['branched_from']['data']['id'], self.public_project._id) assert_equal(data['embeds']['initiator']['data']['id'], self.user._id)
def test_approval_after_initiator_is_merged_into_another_user(self, mock_enqueue): approver = factories.UserFactory() approver.add_system_tag(settings.PREREG_ADMIN_TAG) mergee = factories.UserFactory(fullname='Manny Mergee') merger = factories.UserFactory(fullname='Merve Merger') project = factories.ProjectFactory(creator=mergee) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) merger.merge_user(mergee) approval = DraftRegistrationApproval( meta={ 'registration_choice': 'immediate' } ) approval.save() draft.approval = approval draft.save() approval.approve(approver) draft.reload() registered_node = draft.registered_node assert registered_node.registered_user == merger
def test_on_complete_embargo_creates_registration_for_draft_initiator(self, mock_enquque): user = factories.UserFactory() end_date = timezone.now() + datetime.timedelta(days=366) # <- leap year approval = DraftRegistrationApproval( meta={ 'registration_choice': 'embargo', 'embargo_end_date': end_date.isoformat() } ) approval.save() project = factories.ProjectFactory(creator=user) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) draft.approval = approval draft.save() approval._on_complete(user) draft.reload() registered_node = draft.registered_node assert registered_node is not None assert registered_node.is_pending_embargo assert registered_node.registered_user == draft.initiator
def test_on_complete_immediate_creates_registration_for_draft_initiator(self, mock_enquque): user = factories.UserFactory() project = factories.ProjectFactory(creator=user) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) approval = DraftRegistrationApproval( meta={ 'registration_choice': 'immediate' } ) approval.save() draft.approval = approval draft.save() approval._on_complete(user) draft.reload() registered_node = draft.registered_node assert registered_node is not None assert registered_node.is_pending_registration assert registered_node.registered_user == draft.initiator
def setUp(self): super(TestDraftPreregChallengeRegistrationMetadataValidation, self).setUp() self.prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.prereg_draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=self.prereg_schema, branched_from=self.public_project ) self.other_project = ProjectFactory(creator=self.user) self.url = '/{}nodes/{}/draft_registrations/{}/'.format(API_BASE, self.public_project._id, self.prereg_draft_registration._id) self.payload = { "data": { "id": self.prereg_draft_registration._id, "type": "draft_registrations", "attributes": { "registration_metadata": {} } } }
def test_update_draft_registration(self): metadata = { 'summary': { 'value': 'updated', 'comments': [] } } assert_not_equal(metadata, self.draft.registration_metadata) payload = { 'schema_data': metadata, 'schema_name': 'OSF-Standard Pre-Data Collection Registration', 'schema_version': 1 } url = self.node.api_url_for('update_draft_registration', draft_id=self.draft._id) res = self.app.put_json(url, payload, auth=self.user.auth) assert_equal(res.status_code, http.OK) open_ended_schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', 1) ) self.draft.reload() assert_equal(open_ended_schema, self.draft.registration_schema) assert_equal(metadata, self.draft.registration_metadata)
def test_on_complete_immediate_creates_registration_for_draft_initiator(self, mock_enquque): ensure_schemas() user = factories.UserFactory() project = factories.ProjectFactory(creator=user) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) approval = DraftRegistrationApproval( meta={ 'registration_choice': 'immediate' } ) approval.save() draft.approval = approval draft.save() approval._on_complete(user) draft.reload() registered_node = draft.registered_node assert registered_node is not None assert registered_node.is_pending_registration assert registered_node.registered_user == draft.initiator
def setUp(self): super(TestRegistrationCreate, self).setUp() self.schema = MetaSchema.find_one( Q('name', 'eq', 'Replication Recipe (Brandt et al., 2013): Post-Completion') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=self.schema, branched_from=self.public_project, registration_metadata = { 'item29': {'value': 'Yes'}, 'item33': {'value': 'success'} } ) self.url = '/{}nodes/{}/registrations/'.format(API_BASE, self.public_project._id) self.payload = { "data": { "type": "registrations", "attributes": { "draft_registration": self.draft_registration._id, "registration_choice": "immediate" } } }
def test_approval_after_initiator_is_merged_into_another_user( self, mock_enqueue): approver = factories.UserFactory() approver.add_system_tag(settings.PREREG_ADMIN_TAG) mergee = factories.UserFactory(fullname='Manny Mergee') merger = factories.UserFactory(fullname='Merve Merger') project = factories.ProjectFactory(creator=mergee) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2)) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) merger.merge_user(mergee) approval = DraftRegistrationApproval( meta={'registration_choice': 'immediate'}) approval.save() draft.approval = approval draft.save() approval.approve(approver) draft.reload() registered_node = draft.registered_node assert registered_node.registered_user == merger
def test_required_third_level_questions_must_be_answered_on_draft(self, mock_enqueue): prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) prereg_draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema, branched_from=self.public_project ) registration_metadata = self.prereg_metadata(prereg_draft_registration) registration_metadata['q11'] = {'value': {"question": {}}} prereg_draft_registration.registration_metadata = registration_metadata prereg_draft_registration.save() payload = { "data": { "type": "registrations", "attributes": { "registration_choice": "immediate", "draft_registration": prereg_draft_registration._id, } } } res = self.app.post_json_api(self.url, payload, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 400) assert_equal(res.json['errors'][0]['detail'], "'value' is a required property")
def get_prereg_schema(campaign='prereg'): from osf.models import MetaSchema if campaign not in PREREG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join( PREREG_CAMPAIGNS.keys()))) schema_name = PREREG_CAMPAIGNS[campaign] return MetaSchema.find_one( Q('name', 'eq', schema_name) & Q('schema_version', 'eq', 2))
def get_prereg_schema(campaign='prereg'): from osf.models import MetaSchema if campaign not in PREREG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(PREREG_CAMPAIGNS.keys()))) schema_name = PREREG_CAMPAIGNS[campaign] return MetaSchema.find_one( Q('name', 'eq', schema_name) & Q('schema_version', 'eq', 2) )
def test_registration_metadata_question_values_must_be_dictionaries(self): self.schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.payload['data']['attributes']['registration_supplement'] = self.schema._id self.payload['data']['attributes']['registration_metadata'] = {} self.payload['data']['attributes']['registration_metadata']['datacompletion'] = 'No, data collection has not begun' res = self.app.post_json_api(self.url, self.payload, auth=self.user.auth, expect_errors=True) errors = res.json['errors'][0] assert_equal(res.status_code, 400) assert_equal(errors['detail'], "u'No, data collection has not begun' is not of type 'object'")
def setUp(self): super(TestDraftRegistrationList, self).setUp() self.schema = MetaSchema.find_one( Q('name', 'eq', 'Open-Ended Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=self.schema, branched_from=self.public_project ) self.url = '/{}nodes/{}/draft_registrations/'.format(API_BASE, self.public_project._id)
def test_has_project_and_draft_registration(self): prereg_schema = MetaSchema.find_one(Q('name', 'eq', 'Prereg Challenge')) factories.DraftRegistrationFactory(initiator=self.user, registration_schema=prereg_schema) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': True, 'campaign_long': 'Prereg Challenge', 'campaign_short': 'prereg', 'is_logged_in': True, })
def setUp(self): super(RegistrationsTestBase, self).setUp() self.user = AuthUserFactory() self.auth = Auth(self.user) self.node = ProjectFactory(creator=self.user) self.non_admin = AuthUserFactory() self.node.add_contributor( self.non_admin, permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, auth=self.auth, save=True ) self.non_contrib = AuthUserFactory() self.meta_schema = MetaSchema.find_one( Q('name', 'eq', 'Open-Ended Registration') & Q('schema_version', 'eq', 2) ) self.draft = DraftRegistrationFactory( initiator=self.user, branched_from=self.node, registration_schema=self.meta_schema, registration_metadata={ 'summary': {'value': 'Some airy'} } ) current_month = timezone.now().strftime("%B") current_year = timezone.now().strftime("%Y") valid_date = timezone.now() + dt.timedelta(days=180) self.embargo_payload = { u'embargoEndDate': unicode(valid_date.strftime('%a, %d, %B %Y %H:%M:%S')) + u' GMT', u'registrationChoice': 'embargo' } self.invalid_embargo_date_payload = { u'embargoEndDate': u"Thu, 01 {month} {year} 05:00:00 GMT".format( month=current_month, year=str(int(current_year) - 1) ), u'registrationChoice': 'embargo' } self.immediate_payload = { 'registrationChoice': 'immediate' } self.invalid_payload = { 'registrationChoice': 'foobar' }
def test_question_in_registration_metadata_must_be_in_schema(self): self.schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.payload['data']['attributes']['registration_supplement'] = self.schema._id self.payload['data']['attributes']['registration_metadata'] = {} self.payload['data']['attributes']['registration_metadata']['q11'] = { "value": "No, data collection has not begun" } res = self.app.post_json_api(self.url, self.payload, auth=self.user.auth, expect_errors=True) errors = res.json['errors'][0] assert_equal(res.status_code, 400) assert_equal(errors['detail'], "Additional properties are not allowed (u'q11' was unexpected)")
def setUp(self): super(TestSearchSerializer, self).setUp() self.user = AuthUserFactory() self.project = ProjectFactory(creator=self.user, is_public=True) self.component = NodeFactory(parent=self.project, creator=self.user, is_public=True) self.file = utils.create_test_file(self.component, self.user) self.schema = MetaSchema.find_one( Q('name', 'eq', 'Replication Recipe (Brandt et al., 2013): Post-Completion') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) with mock_archive(self.project, autocomplete=True, autoapprove=True, schema=self.schema) as registration: self.registration = registration
def setUp(self): super(TestDraftRegistrationDelete, self).setUp() schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.draft_registration = DraftRegistrationFactory( initiator=self.user, registration_schema=schema, branched_from=self.public_project ) self.other_project = ProjectFactory(creator=self.user) self.url = '/{}nodes/{}/draft_registrations/{}/'.format(API_BASE, self.public_project._id, self.draft_registration._id)
def test_multiple_choice_question_value_must_match_value_in_schema(self): self.schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.payload['data']['attributes']['registration_supplement'] = self.schema._id self.payload['data']['attributes']['registration_metadata'] = {} self.payload['data']['attributes']['registration_metadata']['datacompletion'] = { "value": "Nope, data collection has not begun" } res = self.app.post_json_api(self.url, self.payload, auth=self.user.auth, expect_errors=True) errors = res.json['errors'][0] assert_equal(res.status_code, 400) assert_equal(errors['detail'], "u'Nope, data collection has not begun' is not one of [u'No, data collection has not begun', u'Yes, data collection is underway or complete']")
def test_registration_supplement_must_be_most_recent_metaschema(self): schema = MetaSchema.find_one( Q('name', 'eq', 'Open-Ended Registration') & Q('schema_version', 'eq', 1) ) draft_data = { "data": { "type": "draft_registrations", "attributes": { "registration_supplement": schema._id } } } res = self.app.post_json_api(self.url, draft_data, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 400) assert_equal(res.json['errors'][0]['detail'], 'Registration supplement must be an active schema.')
def setUp(self): super(TestDraftRegistrationCreate, self).setUp() self.url = '/{}nodes/{}/draft_registrations/'.format(API_BASE, self.public_project._id) self.open_ended_metaschema = MetaSchema.find_one( Q('name', 'eq', 'Open-Ended Registration') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) self.payload = { "data": { "type": "draft_registrations", "attributes": { "registration_supplement": self.open_ended_metaschema._id } } }
def test_drafts_for_user_omits_registered(self): prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2)) d1 = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema) d2 = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema) d3 = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema) d1.registered_node = factories.RegistrationFactory() d1.save() drafts = drafts_for_user(self.user, 'prereg') for d in drafts: assert_in(d._id, (d2._id, d3._id)) assert_not_equal(d._id, d1._id)
def test_on_reject(self, mock_send_mail): user = factories.UserFactory() approval = DraftRegistrationApproval( meta={'registration_choice': 'immediate'}) approval.save() project = factories.ProjectFactory(creator=user) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2)) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) draft.approval = approval draft.save() approval._on_reject(user) assert approval.meta == {} assert mock_send_mail.call_count == 1
def node_register_template_page(auth, node, metaschema_id, **kwargs): if node.is_registration and bool(node.registered_schema): try: meta_schema = MetaSchema.find_one(Q('_id', 'eq', metaschema_id)) except NoResultsFound: # backwards compatability for old urls, lookup by name try: meta_schema = MetaSchema.find( Q('name', 'eq', _id_to_name(metaschema_id))).order_by( '-schema_version').first() except IndexError: raise HTTPError( http.NOT_FOUND, data={ 'message_short': 'Invalid schema name', 'message_long': 'No registration schema with that name could be found.' }) if not node.registered_schema.filter(id=meta_schema.id).exists(): raise HTTPError( http.BAD_REQUEST, data={ 'message_short': 'Invalid schema', 'message_long': 'This registration has no registration supplment with that name.' }) ret = _view_project(node, auth, primary=True) my_meta = serialize_meta_schema(meta_schema) if has_anonymous_link(node, auth): for indx, schema_page in enumerate(my_meta['schema']['pages']): for idx, schema_question in enumerate( schema_page['questions']): if schema_question['title'] in settings.ANONYMIZED_TITLES: del my_meta['schema']['pages'][indx]['questions'][idx] ret['node']['registered_schema'] = serialize_meta_schema(meta_schema) return ret else: status.push_status_message( 'You have been redirected to the project\'s registrations page. From here you can initiate a new Draft Registration to complete the registration process', trust=False) return redirect( node.web_url_for('node_registrations', view=kwargs.get('template')))
def test_has_project_and_draft_registration(self): prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') ) factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema ) assert_equal( landing_page(user=self.user), { 'has_projects': True, 'has_draft_registrations': True, 'campaign_long': 'Prereg Challenge', 'campaign_short': 'prereg', } )
def setUp(self): super(RegistrationsTestBase, self).setUp() self.user = AuthUserFactory() self.auth = Auth(self.user) self.node = ProjectFactory(creator=self.user) self.non_admin = AuthUserFactory() self.node.add_contributor(self.non_admin, permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, auth=self.auth, save=True) self.non_contrib = AuthUserFactory() self.meta_schema = MetaSchema.find_one( Q('name', 'eq', 'Open-Ended Registration') & Q('schema_version', 'eq', 2)) self.draft = DraftRegistrationFactory( initiator=self.user, branched_from=self.node, registration_schema=self.meta_schema, registration_metadata={'summary': { 'value': 'Some airy' }}) current_month = timezone.now().strftime("%B") current_year = timezone.now().strftime("%Y") valid_date = timezone.now() + dt.timedelta(days=180) self.embargo_payload = { u'embargoEndDate': unicode(valid_date.strftime('%a, %d, %B %Y %H:%M:%S')) + u' GMT', u'registrationChoice': 'embargo' } self.invalid_embargo_date_payload = { u'embargoEndDate': u"Thu, 01 {month} {year} 05:00:00 GMT".format( month=current_month, year=str(int(current_year) - 1)), u'registrationChoice': 'embargo' } self.immediate_payload = {'registrationChoice': 'immediate'} self.invalid_payload = {'registrationChoice': 'foobar'}
def test_update_draft_registration(self): metadata = {'summary': {'value': 'updated', 'comments': []}} assert_not_equal(metadata, self.draft.registration_metadata) payload = { 'schema_data': metadata, 'schema_name': 'OSF-Standard Pre-Data Collection Registration', 'schema_version': 1 } url = self.node.api_url_for('update_draft_registration', draft_id=self.draft._id) res = self.app.put_json(url, payload, auth=self.user.auth) assert_equal(res.status_code, http.OK) open_ended_schema = MetaSchema.find_one( Q('name', 'eq', 'OSF-Standard Pre-Data Collection Registration') & Q('schema_version', 'eq', 1)) self.draft.reload() assert_equal(open_ended_schema, self.draft.registration_schema) assert_equal(metadata, self.draft.registration_metadata)
def setUp(self): super(TestCheckPreregAuth, self).setUp() self.prereg_challenge_admin_user = AuthUserFactory() self.prereg_challenge_admin_user.add_system_tag(settings.PREREG_ADMIN_TAG) self.prereg_challenge_admin_user.save() prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) self.user = AuthUserFactory() self.node = factories.ProjectFactory(creator=self.user) self.parent = factories.ProjectFactory() self.child = factories.NodeFactory(parent=self.parent) self.draft_registration = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema, branched_from=self.parent )
def test_on_reject(self, mock_send_mail): user = factories.UserFactory() approval = DraftRegistrationApproval( meta={ 'registration_choice': 'immediate' } ) approval.save() project = factories.ProjectFactory(creator=user) registration_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) draft = factories.DraftRegistrationFactory( branched_from=project, registration_schema=registration_schema, ) draft.approval = approval draft.save() approval._on_reject(user) assert approval.meta == {} assert mock_send_mail.call_count == 1
def node_register_template_page(auth, node, metaschema_id, **kwargs): if node.is_registration and bool(node.registered_schema): try: meta_schema = MetaSchema.find_one( Q('_id', 'eq', metaschema_id) ) except NoResultsFound: # backwards compatability for old urls, lookup by name try: meta_schema = MetaSchema.find( Q('name', 'eq', _id_to_name(metaschema_id)) ).order_by('-schema_version').first() except IndexError: raise HTTPError(http.NOT_FOUND, data={ 'message_short': 'Invalid schema name', 'message_long': 'No registration schema with that name could be found.' }) if not node.registered_schema.filter(id=meta_schema.id).exists(): raise HTTPError(http.BAD_REQUEST, data={ 'message_short': 'Invalid schema', 'message_long': 'This registration has no registration supplment with that name.' }) ret = _view_project(node, auth, primary=True) my_meta = serialize_meta_schema(meta_schema) if has_anonymous_link(node, auth): for indx, schema_page in enumerate(my_meta['schema']['pages']): for idx, schema_question in enumerate(schema_page['questions']): if schema_question['title'] in settings.ANONYMIZED_TITLES: del my_meta['schema']['pages'][indx]['questions'][idx] ret['node']['registered_schema'] = serialize_meta_schema(meta_schema) return ret else: status.push_status_message( 'You have been redirected to the project\'s registrations page. From here you can initiate a new Draft Registration to complete the registration process', trust=False ) return redirect(node.web_url_for('node_registrations', view=kwargs.get('template')))
def test_drafts_for_user_omits_registered(self): prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) d1 = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema ) d2 = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema ) d3 = factories.DraftRegistrationFactory( initiator=self.user, registration_schema=prereg_schema ) d1.registered_node = factories.RegistrationFactory() d1.save() drafts = drafts_for_user(self.user, 'prereg') for d in drafts: assert_in(d._id, (d2._id, d3._id)) assert_not_equal(d._id, d1._id)
def setUp(self): super(TestSearchRegistrations, self).setUp() self.url = '/{}search/registrations/'.format(API_BASE) self.schema = MetaSchema.find_one( Q('name', 'eq', 'Replication Recipe (Brandt et al., 2013): Post-Completion') & Q('schema_version', 'eq', LATEST_SCHEMA_VERSION) ) with mock_archive(self.project, autocomplete=True, autoapprove=True, schema=self.schema) as registration: self.registration = registration with mock_archive(self.project_two, autocomplete=True, autoapprove=True, schema=self.schema) as registration_two: self.registration_two = registration_two with mock_archive(self.private_project, autocomplete=True, autoapprove=True, schema=self.schema) as private_registration: self.private_registration = private_registration self.private_registration.is_public = False self.private_registration.save() # TODO: This shouldn't be necessary, but tests fail if we don't do this. Investigate further. self.private_registration.update_search()
def check_access(node, auth, action, cas_resp): """Verify that user can perform requested action on resource. Raise appropriate error code if action cannot proceed. """ permission = permission_map.get(action, None) if permission is None: raise HTTPError(httplib.BAD_REQUEST) if cas_resp: if permission == 'read': if node.is_public: return True required_scope = oauth_scopes.CoreScopes.NODE_FILE_READ else: required_scope = oauth_scopes.CoreScopes.NODE_FILE_WRITE if not cas_resp.authenticated \ or required_scope not in oauth_scopes.normalize_scopes(cas_resp.attributes['accessTokenScope']): raise HTTPError(httplib.FORBIDDEN) if permission == 'read': if node.can_view(auth): return True # The user may have admin privileges on a parent node, in which # case they should have read permissions if node.is_registration and node.registered_from.can_view(auth): return True if permission == 'write' and node.can_edit(auth): return True # Users attempting to register projects with components might not have # `write` permissions for all components. This will result in a 403 for # all `copyto` actions as well as `copyfrom` actions if the component # in question is not public. To get around this, we have to recursively # check the node's parent node to determine if they have `write` # permissions up the stack. # TODO(hrybacki): is there a way to tell if this is for a registration? # All nodes being registered that receive the `copyto` action will have # `node.is_registration` == True. However, we have no way of telling if # `copyfrom` actions are originating from a node being registered. # TODO This is raise UNAUTHORIZED for registrations that have not been archived yet if action == 'copyfrom' or (action == 'copyto' and node.is_registration): parent = node.parent_node while parent: if parent.can_edit(auth): return True parent = parent.parent_node # Users with the PREREG_ADMIN_TAG should be allowed to download files # from prereg challenge draft registrations. try: prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) allowed_nodes = [node] + node.parents prereg_draft_registration = DraftRegistration.find( Q('branched_from', 'in', [n for n in allowed_nodes]) & Q('registration_schema', 'eq', prereg_schema) ) if action == 'download' and \ auth.user is not None and \ prereg_draft_registration.count() > 0 and \ settings.PREREG_ADMIN_TAG in auth.user.system_tags: return True except NoResultsFound: pass raise HTTPError(httplib.FORBIDDEN if auth.user else httplib.UNAUTHORIZED)
def draft_reg_util(): DraftRegistration.remove() return MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) )
def check_access(node, auth, action, cas_resp): """Verify that user can perform requested action on resource. Raise appropriate error code if action cannot proceed. """ permission = permission_map.get(action, None) if permission is None: raise HTTPError(httplib.BAD_REQUEST) if cas_resp: if permission == 'read': if node.is_public: return True required_scope = oauth_scopes.CoreScopes.NODE_FILE_READ else: required_scope = oauth_scopes.CoreScopes.NODE_FILE_WRITE if not cas_resp.authenticated \ or required_scope not in oauth_scopes.normalize_scopes(cas_resp.attributes['accessTokenScope']): raise HTTPError(httplib.FORBIDDEN) if permission == 'read': if node.can_view(auth): return True # The user may have admin privileges on a parent node, in which # case they should have read permissions if node.is_registration and node.registered_from.can_view(auth): return True if permission == 'write' and node.can_edit(auth): return True # Users attempting to register projects with components might not have # `write` permissions for all components. This will result in a 403 for # all `copyto` actions as well as `copyfrom` actions if the component # in question is not public. To get around this, we have to recursively # check the node's parent node to determine if they have `write` # permissions up the stack. # TODO(hrybacki): is there a way to tell if this is for a registration? # All nodes being registered that receive the `copyto` action will have # `node.is_registration` == True. However, we have no way of telling if # `copyfrom` actions are originating from a node being registered. # TODO This is raise UNAUTHORIZED for registrations that have not been archived yet if action == 'copyfrom' or (action == 'copyto' and node.is_registration): parent = node.parent_node while parent: if parent.can_edit(auth): return True parent = parent.parent_node # Users with the PREREG_ADMIN_TAG should be allowed to download files # from prereg challenge draft registrations. try: prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2)) allowed_nodes = [node] + node.parents prereg_draft_registration = DraftRegistration.find( Q('branched_from', 'in', [n for n in allowed_nodes]) & Q('registration_schema', 'eq', prereg_schema)) if action == 'download' and \ auth.user is not None and \ prereg_draft_registration.count() > 0 and \ settings.PREREG_ADMIN_TAG in auth.user.system_tags: return True except NoResultsFound: pass raise HTTPError(httplib.FORBIDDEN if auth.user else httplib.UNAUTHORIZED)
def generate_schema_from_data(data): def from_property(id, prop): if isinstance(prop.get('value'), dict): return { 'id': id, 'type': 'object', 'properties': [ from_property(pid, sp) for pid, sp in prop['value'].items() ] } else: return { 'id': id, 'type': 'osf-upload' if prop.get('extra') else 'string' } def from_question(qid, question): if q.get('extra'): return { 'qid': qid, 'type': 'osf-upload' } elif isinstance(q.get('value'), dict): return { 'qid': qid, 'type': 'object', 'properties': [ from_property(id, value) for id, value in question.get('value').items() ] } else: return { 'qid': qid, 'type': 'string' } _schema = { 'name': 'Test', 'version': 2, 'config': { 'hasFiles': True }, 'pages': [{ 'id': 'page1', 'questions': [ from_question(qid, q) for qid, q in data.items() ] }] } schema = MetaSchema( name=_schema['name'], schema_version=_schema['version'], schema=_schema ) try: schema.save() except KeyExistsException: # Unfortunately, we don't have db isolation between test cases for some # reason. Update the doc currently in the db rather than saving a new # one. schema = MetaSchema.find_one( Q('name', 'eq', _schema['name']) & Q('schema_version', 'eq', _schema['version']) ) schema.schema = _schema schema.save() return schema
def draft_reg_util(): DraftRegistration.remove() return MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2))