def test_forbidden(self): # Forbidden tile root = get_root() model = root['model'] = BaseNode() request = self.layer.new_request() self.checkOutput(""" \n\n <div>\n <h1>Unauthorized</h1>\n <p>You are not allowed to access this resource.</p>\n </div>\n\n\n """, render_tile(model, request, 'unauthorized')) del root['model'] # Forbidden view root = get_root() model = root['model'] = BaseNode() request = self.layer.new_request() request.context = model res = forbidden_view(request).text self.assertTrue(res.find('id="input-loginform-login"') > -1) with self.layer.authenticated('admin'): request = self.layer.new_request() request.context = model res = forbidden_view(request).text self.assertTrue(res.find('<h1>Unauthorized</h1>') > -1) del root['model']
def test_not_found(self): # Not Found tile root = get_root() model = root['model'] = BaseNode() request = self.layer.new_request() self.checkOutput(""" \n\n <div>\n <h1>Not Found</h1>\n <p>The requested resource cannot be found.</p>\n </div>\n\n\n """, render_tile(model, request, 'not_found')) del root['model'] # Not Found view root = get_root() model = root['model'] = BaseNode() request = self.layer.new_request() request.context = model res = not_found_view(request).text self.assertTrue(res.find('<h1>Not Found</h1>') > -1) with self.layer.authenticated('admin'): request = self.layer.new_request() request.context = model res = not_found_view(request).text self.assertTrue(res.find('<h1>Not Found</h1>') > -1) del root['model']
def test_edit_user(self): root = get_root() users = root['users'] user = users['user_1'] self.assertEqual(user.attrs['fullname'], 'Max Mustermann') self.assertEqual(user.attrs['email'], '*****@*****.**') request = self.layer.new_request() events_called = [] @classhandler.handler(UserModifiedEvent) def on_user_modified(event): events_called.append('UserModifiedEvent') with self.layer.authenticated('manager'): res = render_tile(user, request, 'edit') expected = '<form action="http://example.com/users/user_1/edit"' self.assertTrue(res.find(expected) > -1) request.params['userform.password'] = '******' request.params['userform.fullname'] = 'Susi Musterfrau' request.params['userform.email'] = '*****@*****.**' request.params['userform.principal_roles'] = [] request.params['action.userform.save'] = '1' with self.layer.authenticated('manager'): res = render_tile(user, request, 'edit') self.assertEqual(res, '') self.assertEqual(user.attrs['fullname'], 'Susi Musterfrau') self.assertEqual(user.attrs['email'], '*****@*****.**') self.assertTrue('UserModifiedEvent' in events_called)
def test_GeneralSettingsForm(self, tempdir): config_file = os.path.join(tempdir, 'ugm.xml') ugm_cfg.ugm_settings = config_file with open(config_file, 'w') as f: f.write('<properties></properties>') model = get_root()['settings']['ugm_general'] request = self.layer.new_request() tile = GeneralSettingsForm() tile.model = model tile.request = request tile.prepare() form = tile.form self.assertEqual(form.keys(), [ 'users_heading', 'users_account_expiration', 'users_expires_attr', 'users_expires_unit', 'user_id_autoincrement', 'user_id_autoincrement_prefix', 'user_id_autoincrement_start', 'users_portrait', 'users_portrait_attr', 'users_portrait_accept', 'users_portrait_width', 'users_portrait_height', 'users_local_management_enabled', 'users_login_name_attr', 'users_exposed_attributes', 'users_form_attrmap', 'users_listing_columns', 'users_listing_default_column', 'groups_heading', 'groups_form_attrmap', 'groups_listing_columns', 'groups_listing_default_column', 'roles_heading', 'roles_principal_roles_enabled', 'save' ])
def wrapper(inst): try: w(inst) finally: settings = general_settings(get_root()) settings.attrs.users_portrait = u'True' settings()
def __call__(self): settings = get_root()['settings'] server_settings = settings['ugm_server'] if not server_settings.ldap_connectivity: logger.error(u"Could not initialize authentication implementation. " u"LDAP Server is not available or invalid credentials.") return props = server_settings.ldap_props users_settings = settings['ugm_users'] if not users_settings.ldap_users_container_valid: logger.error(u"Could not initialize authentication implementation. " u"Configured users container invalid.") return ucfg = users_settings.ldap_ucfg groups_settings = settings['ugm_groups'] gcfg = None if groups_settings.ldap_groups_container_valid: gcfg = groups_settings.ldap_gcfg else: logger.warning(u"Configured groups container invalid.") roles_settings = settings['ugm_roles'] rcfg = None if roles_settings.ldap_roles_container_valid: rcfg = roles_settings.ldap_rcfg else: logger.warning(u"Configured roles container invalid.") return LdapUgm( name='ldap_ugm', props=props, ucfg=ucfg, gcfg=gcfg, rcfg=rcfg )
def _invalidate_settings(): settings = get_root()['settings'] settings['ugm_general'].invalidate() settings['ldap_server'].invalidate() settings['ldap_users'].invalidate() settings['ldap_groups'].invalidate() settings['ldap_roles'].invalidate()
def download(request): suid = request.matchdict['suid'] rev = request.matchdict.get('rev') root = get_root() config = solr_config(root) query = Term('suid', suid) if rev: query = query & Term('revision', rev) else: query = query & Term('state', 'active') query = query & Term('visibility', 'anonymous') md = Metadata(config, SOLR_FIELDS) fl = 'effective,expires,physical_path,mimetype,filename' result = md.query(q=query, fl=fl) if len(result) != 1: raise MDBError(u'Dataset not found in SOLR. Query: %s' % query) md = result[0] if not chk_publication(md): raise MDBError(u'Item not effective or already expired') physical_path = u'/xsendfile%s.binary' % md['physical_path'] response = Response() response.content_type = md['mimetype'] response.content_disposition = \ 'attachment; filename=%s' % md['filename'] response.headers.add('X-Accel-Redirect', physical_path) return response
def search(request): root = get_root() config = solr_config(root) result = list() term = '%s*~' % request.matchdict['term'] query = Term('type', 'Media') \ & Group(Term('title', term) \ | Term('description', term) \ | Term('creator', term)) fl = 'uid,title,description,repository' for md in Metadata(config, SOLR_FIELDS).query(q=query, fl=fl): suid = str(base62(int(uuid.UUID(md.uid)))) result.append({ 'suid': suid, 'uid': md.uid, 'title': md.title, 'description': md.description, 'repository': md.repository, 'revisions': list(), }) rev_query = Term('suid', suid) & Term('visibility', 'anonymous') fl = revision_info_fl for rev_md in Metadata(config, SOLR_FIELDS).query(q=rev_query, fl=fl): if not chk_publication(rev_md): continue result[-1]['revisions'].append(revision_info(rev_md)) return result
def test_sql_session_setup(self): # Resgister entry register_entry('integer_as_key_container', IntegerAsKeyContainer) # Test ``sql_session_setup``. The SQL session setup handler is defined # in ``cone.sql.testing`` and registers a callback to ``after_flush`` # event. Patch desired callback reference and test whether it's called. class Callback(object): session = None flush_context = None def __call__(self, session, flush_context): self.session = session self.flush_context = flush_context callback = Callback() testing.test_after_flush = callback root = get_root() container = root['integer_as_key_container'] node = container['1236'] = IntegerAsKeyNode() node.attrs['field'] = u'Value' container() self.assertTrue(isinstance(callback.session, Session)) self.assertTrue(isinstance(callback.flush_context, UOWTransaction)) testing.test_after_flush = None
def test_int_as_primary_key(self): # Resgister entry register_entry('integer_as_key_container', IntegerAsKeyContainer) # Get container from root root = get_root() container = root['integer_as_key_container'] # Add node to container node = container['1234'] = IntegerAsKeyNode() node.attrs['field'] = u'Value' # Persist data container() # Query data record using SQLAlchemy directly request = self.layer.new_request() session = get_session(request) rec = session.query(IntegerAsPrimaryKeyRecord).get('1234') self.assertTrue(isinstance(rec, IntegerAsPrimaryKeyRecord)) # Get children via node API node = container['1234'] self.assertTrue(isinstance(node, IntegerAsKeyNode)) self.assertEqual(container.keys(), ['1234']) self.assertEqual(len(container.values()), 1) self.assertEqual(container.values()[0].name, '1234') self.assertEqual(len(container.items()), 1) self.assertEqual(container.items()[0][0], '1234') self.assertEqual(container.items()[0][1].name, '1234') self.assertEqual(sorted(node.attrs.items()), [('field', u'Value'), ('integer_key', 1234)])
def test_edit_group(self): root = get_root() groups = root['groups'] group = groups['group_1'] self.assertEqual(group.attrs['groupname'], 'Group 1') request = self.layer.new_request() events_called = [] @classhandler.handler(GroupModifiedEvent) def on_user_created(event): events_called.append('GroupModifiedEvent') with self.layer.authenticated('manager'): res = render_tile(group, request, 'edit') expected = '<form action="http://example.com/groups/group_1/edit"' self.assertTrue(res.find(expected) > -1) request.params['groupform.groupname'] = 'Groupname Changed' request.params['groupform.principal_roles'] = [] request.params['action.groupform.save'] = '1' with self.layer.authenticated('manager'): res = render_tile(group, request, 'edit') self.assertEqual(res, '') self.assertEqual(group.attrs['groupname'], 'Groupname Changed') self.assertTrue('GroupModifiedEvent' in events_called)
def test_ajax_continue(self): with self.layer.hook_tile_reg(): @tile(name='testtile2') class TestTile(Tile): def render(self): ajax_continue( self.request, AjaxAction('target', 'name', 'mode', 'selector')) return u'' root = get_root() request = self.layer.new_request() request.params['bdajax.action'] = 'testtile2' request.params['bdajax.mode'] = 'replace' request.params['bdajax.selector'] = '.foo' with self.layer.authenticated('max'): self.assertEqual( ajax_tile(root, request), { 'continuation': [{ 'mode': 'mode', 'selector': 'selector', 'type': 'action', 'target': 'target', 'name': 'name' }], 'payload': u'', 'mode': 'replace', 'selector': '.foo' })
def test_GroupExistsExtractor(self): root = get_root() groups = root['groups'] add_model = BaseNode(parent=groups) extractor = GroupExistsExtractor(add_model) widget = factory( '*exists:text', name='group_id', custom={'exists': {'extractors': [extractor]}} ) # test already exists request = {'group_id': 'group_exists'} data = widget.extract(request=request) self.assertTrue(data.has_errors) self.assertEqual( data.errors, [ExtractionError('group_already_exists')] ) # test not already exists request = {'group_id': 'new_group_id'} data = widget.extract(request=request) self.assertFalse(data.has_errors) self.assertEqual(data.extracted, 'new_group_id')
def test_settings_tab_content(self): root = get_root() settings = root['settings'] settings.factories.clear() register_plugin_config('foo', SomeSettings) register_plugin_config('baz', OtherSettings) with self.layer.hook_tile_reg(): @tile(name='content', interface=SomeSettings) class SomeSettingsTile(Tile): def render(self): return '<div>Settings Contents</div>' @tile(name='content', interface=OtherSettings) class OtherSettingsTile(Tile): def render(self): msg = 'This tile can not be rendered for some reason' raise Exception(msg) # Ajax view for tabs request = self.layer.new_request() with self.layer.authenticated('manager'): response = settings_tab_content(settings['foo'], request) self.assertEqual( response.text, '<div class="foo"><div>Settings Contents</div></div>' ) with self.layer.authenticated('manager'): response = settings_tab_content(settings['baz'], request) self.checkOutput(""" <div class="baz">...Exception: This tile can not be rendered for some reason\n</pre></div></div> """, response.text)
def __call__(self): settings = get_root()['settings'] server_settings = settings['ldap_server'] if not server_settings.ldap_connectivity: logger.error( 'Could not initialize authentication implementation. ' 'LDAP Server is not available or invalid credentials.') return props = server_settings.ldap_props users_settings = settings['ldap_users'] if not users_settings.container_exists: logger.error('Could not initialize authentication implementation. ' 'Configured users container invalid.') return ucfg = users_settings.ldap_ucfg groups_settings = settings['ldap_groups'] gcfg = None if groups_settings.container_exists: gcfg = groups_settings.ldap_gcfg else: logger.warning(u"Configured groups container invalid.") roles_settings = settings['ldap_roles'] rcfg = None if roles_settings.container_exists: rcfg = roles_settings.ldap_rcfg else: logger.warning(u"Configured roles container invalid.") return Ugm(name='ldap_ugm', props=props, ucfg=ucfg, gcfg=gcfg, rcfg=rcfg)
def test_LDAPContainerSettings(self): settings = LDAPContainerSettings() settings.__parent__ = get_root()['settings'] self.assertTrue( isinstance(settings.server_settings, LDAPServerSettings)) settings.container_dn = None err = self.expect_error(LDAPContainerError, settings.create_container) self.assertEqual(err.error_message, 'no_container_dn_defined') self.assertFalse(settings.container_exists) settings.container_dn = 'uid=foo,dc=my-domain,dc=com' err = self.expect_error(LDAPContainerError, settings.create_container) self.assertEqual(err.error_message, 'expected_ou_as_rdn') self.assertFalse(settings.container_exists) settings.container_dn = 'ou=container,#' err = self.expect_error(LDAPContainerError, settings.create_container) self.assertEqual(err.error_message, 'invalid_dn') self.assertFalse(settings.container_exists) settings.container_dn = 'ou=container,ou=inexistent,dc=my-domain,dc=com' err = self.expect_error(LDAPContainerError, settings.create_container) self.assertEqual(err.error_message, 'parent_not_found') self.assertFalse(settings.container_exists) settings.container_dn = 'ou=container,dc=my-domain,dc=com' settings.create_container() self.assertTrue(settings.container_exists)
def __init__(self, settings): # cone.ugm active, users and groups attributes are read from ugm config if settings.get('cone.plugins').find('cone.ugm') > -1: from cone.ugm.utils import general_settings model = get_root() ugm_settings = general_settings(model).attrs self.user_attrs = ugm_settings.users_form_attrmap.keys() self.group_attrs = ugm_settings.groups_form_attrmap.keys() # users and groups attributes are read from application ini file else: self.user_attrs = [ attr.strip() for attr in settings.get('sql.user_attrs', '').split(',') if attr.strip() ] self.group_attrs = [ attr.strip() for attr in settings.get('sql.group_attrs', '').split(',') if attr.strip() ] self.binary_attrs = [ attr.strip() for attr in settings.get('sql.binary_attrs', '').split(',') if attr.strip() ] self.log_auth = settings.get('sql.log_auth') in ['true', 'True', '1']
def wrapper(inst): w(inst) cfg = ugm_general(get_root()) cfg.attrs.user_id_autoincrement = 'False' cfg.attrs.user_id_autoincrement_prefix = '' cfg()
def wrap_ajax_target(rendered, widget, data): target = widget.attrs['target'] if not target: request = data.request.request request = request if request else get_current_request() target = make_url(request, node=get_root()) if callable(target): target = target(widget, data) referencable = widget.attrs['referencable'] if callable(referencable): referencable = referencable(widget, data) if type(referencable) in compat.ITER_TYPES: referencable = ','.join(referencable) if not referencable: referencable = '' root = widget.attrs['root'] if callable(root): root = root(widget, data) value = fetch_reference_value(widget, data) selected = '' if widget.attrs['multivalued'] and value: selected = ','.join(value) elif value: selected = value query = make_query(**{ 'root': root, 'referencable': referencable, 'selected': selected, }) target = '{}{}'.format(target, query) attrs = { 'ajax:target': target, } return tag('span', rendered, **attrs)
def test_group_remove_user_action(self): root = get_root() groups = root['groups'] group = groups['group_1'] request = self.layer.new_request(type='json') with self.layer.authenticated('viewer'): self.expectError( HTTPForbidden, render_view_to_response, group, request, name='remove_item' ) request.params['id'] = 'user_2' with self.layer.authenticated('editor'): res = render_view_to_response(group, request, name='remove_item') json_res = json.loads(res.text) self.assertFalse(json_res['success']) self.assertTrue(json_res['message'].find("'user_2'") > -1) request.params['id'] = 'user_1' with self.layer.authenticated('editor'): res = render_view_to_response(group, request, name='remove_item') self.assertEqual(json.loads(res.text), { 'message': "Removed user 'user_1' from group 'group_1'.", 'success': True }) self.assertEqual(group.model.users, [])
def test_user_add_to_group_action(self): root = get_root() users = root['users'] user = users['user_1'] request = self.layer.new_request(type='json') with self.layer.authenticated('viewer'): self.expectError( HTTPForbidden, render_view_to_response, user, request, name='add_item' ) request.params['id'] = 'group_1' with self.layer.authenticated('editor'): res = render_view_to_response(user, request, name='add_item') self.assertEqual(json.loads(res.text), { 'message': "Added user 'user_1' to group 'group_1'.", 'success': True }) request.params['id'] = 'group_2' with self.layer.authenticated('editor'): res = render_view_to_response(user, request, name='add_item') json_res = json.loads(res.text) self.assertFalse(json_res['success']) self.assertTrue(json_res['message'].find("'group_2'") > -1) self.assertEqual(user.model.group_ids, ['group_1'])
def wrapper(*a, **kw): root = get_root() factories = set(root.factories.keys()) try: fn(*a, **kw) finally: for key in set(root.factories.keys()).difference(factories): del root.factories[key]
def wrapper(inst): try: w(inst) finally: settings = general_settings(get_root()) settings.attrs.user_id_autoincrement = 'False' settings.attrs.user_id_autoincrement_prefix = '' settings()
def test_use_tm(self): # Resgister entry register_entry('integer_as_key_container', IntegerAsKeyContainer) root = get_root() container = root['integer_as_key_container'] # create a base entry for direct node modification test request = self.layer.new_request() node = container['1'] = IntegerAsKeyNode() node.attrs['field'] = 'Value' node() # transaction manager used, calling nodes flushes session os.environ['CONE_SQL_USE_TM'] = '1' self.assertTrue(use_tm()) # modify existing node node.attrs['field'] = 'New' node() # create new node container['2'] = IntegerAsKeyNode() container() session = get_session(request) res = session.query(IntegerAsPrimaryKeyRecord).all() self.assertEqual(len(res), 2) self.assertEqual(res[0].field, 'New') # rollback works, session was just flushed session.rollback() res = session.query(IntegerAsPrimaryKeyRecord).all() self.assertEqual(len(res), 1) self.assertEqual(res[0].field, 'Value') # no transaction manager used, calling nodes commits session os.environ['CONE_SQL_USE_TM'] = '0' self.assertFalse(use_tm()) # modify existing node node.attrs['field'] = 'New' node() # create new node container['2'] = IntegerAsKeyNode() container() session = get_session(request) res = session.query(IntegerAsPrimaryKeyRecord).all() self.assertEqual(len(res), 2) self.assertEqual(res[0].field, 'New') # rollback has not effect, session was commited session.rollback() res = session.query(IntegerAsPrimaryKeyRecord).all() self.assertEqual(len(res), 2) self.assertEqual(res[0].field, 'New')
def test_autoincrement(self): root = get_root() users = root['users'] settings = general_settings(users) self.assertEqual(settings.attrs.user_id_autoincrement, 'False') self.assertEqual(settings.attrs.user_id_autoincrement_prefix, '') vessel = user_vessel(users) request = self.layer.new_request() with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.checkOutput(""" ...<input class="form-control required text" id="input-userform-id" name="userform.id" required="required" type="text" value="" />... """, res) settings.attrs.user_id_autoincrement = 'True' settings() vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.checkOutput(""" ...<input class="form-control text" disabled="disabled" id="input-userform-id" name="userform.id" type="text" value="auto_incremented" />... """, res) request = user_request(self.layer) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), ['100', 'manager']) request = user_request(self.layer) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), ['100', '101', 'manager']) settings.attrs.user_id_autoincrement_prefix = 'uid' settings() request = user_request(self.layer) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), [ '100', '101', 'manager', 'uid100' ]) request = user_request(self.layer) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), [ '100', '101', 'manager', 'uid100', 'uid101' ])
def test_LDAPGroupsSettings(self): settings = get_root()['settings']['ldap_groups'] self.assertTrue(isinstance(settings, LDAPGroupsSettings)) md = settings.metadata self.assertEqual(md.title, 'group_settings_node') self.assertEqual(md.description, 'group_settings_node_description') attrs = settings.attrs self.assertEqual(sorted(attrs.keys()), [ 'groups_aliases_attrmap', 'groups_dn', 'groups_object_classes', 'groups_query', 'groups_relation', 'groups_scope' ]) attrs.groups_dn = 'ou=groups,dc=my-domain,dc=com' attrs.groups_scope = '1' attrs.groups_query = '' attrs.groups_object_classes = ['groupOfNames'] attrs.groups_aliases_attrmap = {'rdn': 'cn', 'id': 'cn'} attrs.groups_relation = '' ugm_settings = settings.parent['ugm_general'] ugm_attrs = ugm_settings.attrs ugm_attrs.groups_form_attrmap = {'description': 'Description'} ldap_gcfg = settings.ldap_gcfg self.assertEqual(isinstance(ldap_gcfg, GroupsConfig), True) self.assertEqual(ldap_gcfg.baseDN, 'ou=groups,dc=my-domain,dc=com') self.assertEqual(sorted(ldap_gcfg.attrmap.items()), [('description', 'description'), ('id', 'cn'), ('rdn', 'cn')]) self.assertEqual(ldap_gcfg.scope, 1) self.assertEqual(ldap_gcfg.queryFilter, '') self.assertEqual(ldap_gcfg.objectClasses, ['groupOfNames']) self.assertEqual(ldap_gcfg.defaults, {}) self.assertTrue(settings.attrs is attrs) self.assertTrue(settings.ldap_gcfg is ldap_gcfg) settings.invalidate() self.assertFalse(settings.attrs is attrs) self.assertFalse(settings.ldap_gcfg is ldap_gcfg) ldap_settings = settings.parent['ldap_server'] ldap_settings.invalidate() settings.invalidate() settings.attrs.groups_dn = 'ou=groups-container,dc=my-domain,dc=com' self.assertFalse(settings.container_exists) settings.create_container() self.assertTrue(settings.container_exists) ldap_settings.invalidate() settings.invalidate() ldap_settings.attrs.cache = None self.assertFalse(settings.container_exists)
def test_CreateContainerTrigger(self): settings = get_root()['settings']['ldap_users'] cct = CreateContainerTrigger() cct.model = settings cct.request = self.layer.new_request() self.assertTrue(cct.ldap_connectivity) self.assertEqual(cct.creation_target, 'http://example.com/settings/ldap_users')
def test_content_tile(self): root = get_root() users = root['users'] user = users['user_1'] request = self.layer.new_request() # Unauthenticated content tile renders login form expected = '<form action="http://example.com/users/user_1/login"' res = render_tile(user, request, 'content') self.assertTrue(res.find(expected) > -1)
def test_content_tile(self): root = get_root() groups = root['groups'] group = groups['group_1'] request = self.layer.new_request() # Unauthenticated content tile renders login form expected = '<form action="http://example.com/groups/group_1/login"' res = render_tile(group, request, 'content') self.assertTrue(res.find(expected) > -1)
def test_logout_tile(self): root = get_root() request = self.layer.new_request() with self.layer.authenticated('admin'): render_tile(root, request, 'logout') self.checkOutput(""" ResponseHeaders([('Set-Cookie', 'auth_tkt=; Max-Age=0; Path=/; expires=...'), ('Set-Cookie', 'auth_tkt=; Domain=example.com; Max-Age=0; Path=/; expires=...'), ('Set-Cookie', 'auth_tkt=; Domain=.example.com; Max-Age=0; Path=/; expires=...')]) """, str(request.response.headers))
def test_ajax_tile(self): # ``ajax_tile`` is the server side bdajax implementation for cone. # Using ``bdajax.action`` with cone renders tiles by action name. with self.layer.hook_tile_reg(): @tile(name='testtile') class TestTile(Tile): def render(self): return 'rendered test tile' root = get_root() request = self.layer.new_request() request.params['bdajax.action'] = 'testtile' request.params['bdajax.mode'] = 'replace' request.params['bdajax.selector'] = '.foo' # Fails unauthenticated, since default permission for tiles is 'view' self.assertEqual(ajax_tile(root, request), {}) self.assertEqual(request.response.status, '403 Forbidden') # Authenticate and test again with self.layer.authenticated('max'): res = ajax_tile(root, request) self.assertEqual( res, { 'continuation': False, 'payload': 'rendered test tile', 'mode': 'replace', 'selector': '.foo' }) # Test with error raising tile with self.layer.hook_tile_reg(): @tile(name='errortile') class ErrorTile(Tile): def render(self): raise Exception('Error while rendering') request = self.layer.new_request() request.params['bdajax.action'] = 'errortile' request.params['bdajax.mode'] = 'replace' request.params['bdajax.selector'] = '.foo' with self.layer.authenticated('max'): res = ajax_tile(root, request) self.assertEqual(res['payload'], '') self.assertEqual(res['mode'], 'NONE') self.assertEqual(res['selector'], 'NONE') self.assertEqual(res['continuation'][0]['flavor'], 'error') self.assertEqual(res['continuation'][0]['type'], 'message') self.assertEqual(res['continuation'][0]['selector'], None) expected = 'Exception: Error while rendering' self.assertTrue(res['continuation'][0]['payload'].find(expected) > -1)
def test_logout_tile(self): root = get_root() request = self.layer.new_request() with self.layer.authenticated('admin'): render_tile(root, request, 'logout') self.checkOutput( """ ResponseHeaders([('Set-Cookie', 'auth_tkt=; Max-Age=0; Path=/; expires=...'), ('Set-Cookie', 'auth_tkt=; Domain=example.com; Max-Age=0; Path=/; expires=...'), ('Set-Cookie', 'auth_tkt=; Domain=.example.com; Max-Age=0; Path=/; expires=...')]) """, str(request.response.headers))
def test_portrait(self): root = get_root() users = root['users'] user = users['user_1'] # Portrait related config properties settings = general_settings(users) self.assertEqual(settings.attrs.users_portrait, 'True') self.assertEqual(settings.attrs.users_portrait_attr, 'portrait') self.assertEqual(settings.attrs.users_portrait_accept, 'image/jpeg') self.assertEqual(settings.attrs.users_portrait_width, '50') self.assertEqual(settings.attrs.users_portrait_height, '50') # Portrait enabled, widget is rendered request = self.layer.new_request() with self.layer.authenticated('manager'): res = render_tile(user, request, 'editform') self.assertTrue(res.find('id="input-userform-portrait"') > -1) # No portrait, default portrait is shown expected = ('src="http://example.com/cone.ugm.static/images/' 'default_portrait.jpg?nocache=') self.assertTrue(res.find(expected) > -1) # Submit portrait dummy_jpg = dummy_file_data('dummy.jpg') portrait = { 'file': BytesIO(dummy_jpg), 'mimetype': 'image/jpeg', } request = user_portrait_request(self.layer, user, portrait) with self.layer.authenticated('manager'): res = render_tile(user, request, 'editform') # New portrait set on user expected = b'\xff\xd8\xff\xe0\x00\x10JFIF' self.assertTrue(user.attrs['portrait'].startswith(expected)) # Portrait present, link to user portrait is shown request = self.layer.new_request() with self.layer.authenticated('manager'): res = render_tile(user, request, 'editform') expected = 'src="http://example.com/users/user_1/portrait_image?nocache=' self.assertTrue(res.find(expected) > -1) # Portrait disabled, widget is skipped settings.attrs.users_portrait = u'False' settings() request = self.layer.new_request() with self.layer.authenticated('manager'): res = render_tile(user, request, 'editform') self.assertFalse(res.find('id="input-userform-portrait"') > -1)
def test_leftcolumn_tile(self): root = get_root() users = root['users'] user = users['user_1'] request = self.layer.new_request() self.expectError(HTTPForbidden, render_tile, user, request, 'leftcolumn') with self.layer.authenticated('manager'): res = render_tile(user, request, 'leftcolumn') expected = '<div class="column left_column col-md-6">' self.assertTrue(res.find(expected) > -1)
def test_rightcolumn_tile(self): root = get_root() groups = root['groups'] group = groups['group_1'] request = self.layer.new_request() self.expectError(HTTPForbidden, render_tile, group, request, 'rightcolumn') with self.layer.authenticated('manager'): res = render_tile(group, request, 'rightcolumn') expected = '<div class="column right_column col-md-6">' self.assertTrue(res.find(expected) > -1)
def info(request): root = get_root() config = solr_config(root) uid = request.matchdict['uid'] query = Term('uid', uid) & Term('visibility', 'anonymous') md = Metadata(config, SOLR_FIELDS) result = md.query(q=query, fl=revision_info_fl) if len(result) != 1: return {} md = result[0] if not chk_publication(md): return {} return revision_info(md)
def access(request): root = get_root() config = solr_config(root) uid = request.matchdict['uid'] query = Term('uid', uid) & Term('visibility', 'anonymous') md = Metadata(config, SOLR_FIELDS) fl = 'effective,expires' result = md.query(q=query, fl=fl) if len(result) != 1: return False md = result[0] if not chk_publication(md): return False return True
def test_settings_content_tile(self): root = get_root() settings = root['settings'] settings.factories.clear() register_plugin_config('foo', SomeSettings) register_plugin_config('bar', SomeSettings) register_plugin_config('baz', OtherSettings) request = self.layer.new_request() # Login and render 'content' tile on ``Settings`` node with self.layer.authenticated('manager'): res = render_tile(settings, request, 'content') self.assertTrue(res.find('foo</a>') > -1) self.assertTrue(res.find('bar</a>') > -1) self.assertTrue(res.find('baz</a>') > -1) # 'content' tile for ``SomeSettings`` with self.layer.hook_tile_reg(): @tile(name='content', interface=SomeSettings) class SomeSettingsTile(Tile): def render(self): return '<div>Settings Contents</div>' with self.layer.authenticated('manager'): res = render_tile(settings['foo'], request, 'content') self.assertEqual(res, '<div>Settings Contents</div>') # 'content' tile for ``OtherSettings`` which raises an exception at # render time with self.layer.hook_tile_reg(): @tile(name='content', interface=OtherSettings) class OtherSettingsTile(Tile): def render(self): msg = 'This tile can not be rendered for some reason' raise Exception(msg) with self.layer.authenticated('manager'): err = self.expectError( Exception, render_tile, settings['baz'], request, 'content' ) self.assertEqual( str(err), 'This tile can not be rendered for some reason' )
def test_register_plugin_config(self): root = get_root() settings = root['settings'] settings.factories.clear() register_plugin_config('foo', SomeSettings) register_plugin_config('bar', SomeSettings) register_plugin_config('baz', OtherSettings) self.assertEqual(settings.factories.keys(), ['foo', 'bar', 'baz']) err = self.expectError( ValueError, register_plugin_config, 'baz', OtherSettings ) self.assertEqual(str(err), "Config with name 'baz' already registered.")
def test_SettingsBehavior(self): root = get_root() settings = root['settings'] settings.factories.clear() register_plugin_config('foo', SomeSettings) with self.layer.hook_tile_reg(): @tile(name='editform', interface=SomeSettings) @plumbing(SettingsBehavior) class SomeSettingsForm(Form): def prepare(self): form = factory( u'form', name='editform', props={ 'action': self.nodeurl }) form['foo'] = factory( 'field:label:text', props={ 'label': 'Foo', }) form['save'] = factory( 'submit', props={ 'action': 'save', 'expression': True, 'handler': None, 'next': self.next, 'label': 'Save', }) self.form = form request = self.layer.new_request() request.params['action.editform.save'] = '1' request.params['editform.foo'] = 'foo' request.params['ajax'] = '1' with self.layer.authenticated('manager'): res = render_tile(settings['foo'], request, 'editform') self.assertEqual(res, u'') action = request.environ['cone.app.continuation'][0] self.assertTrue(isinstance(action, AjaxAction)) self.assertEqual(action.selector, '.foo')
def test_login_form(self): root = get_root() request = self.layer.new_request() res = render_tile(root, request, 'loginform') self.assertTrue(res.find('<form action="http://example.com/login"') > -1) # Authenticate with wrong credentials request.params['loginform.user'] = '******' request.params['loginform.password'] = '******' request.params['action.loginform.login'] = '******' res = render_tile(root, request, 'loginform') self.assertTrue(res.find('class="errormessage">Invalid Credentials') > -1) # Authenticate with correct credentials request.params['loginform.user'] = security.ADMIN_USER request.params['loginform.password'] = security.ADMIN_PASSWORD request.params['action.loginform.login'] = '******' render_tile(root, request, 'loginform') self.assertTrue(isinstance(request.environ['redirect'], HTTPFound))
def test_LocalManager(self): self.layer.new_request() # Local Manager test config root = get_root() config = root['settings']['ugm_localmanager'].attrs self.assertEqual(sorted(config.items()), [ ('admin_group_1', {'default': ['group1'], 'target': ['group0', 'group1']}), ('admin_group_2', {'default': ['group2'], 'target': ['group1', 'group2']}) ]) # Local Manager plumbing behavior @plumbing(LocalManager) class LocalManagerNode(BaseNode): pass lm_node = LocalManagerNode(name='lm_node', parent=root) self.assertFalse(lm_node.local_management_enabled) # ``local_management_enabled`` is generally ignored in following # functions of ``LocalManager``. User needs to consider if local # management is enabled. # Unauthenticated self.assertEqual(lm_node.local_manager_target_gids, []) self.assertEqual(lm_node.local_manager_target_uids, []) # Authenticated, no local manager with self.layer.authenticated('uid0'): self.assertEqual(lm_node.local_manager_target_gids, []) self.assertEqual(lm_node.local_manager_target_uids, []) # Authenticated, invalid local management group member groups = root['groups'].backend group = groups['admin_group_2'] group.add('localmanager_1') group() self.assertEqual(sorted(group.member_ids), ['localmanager_1', 'localmanager_2']) with self.layer.authenticated('localmanager_1'): err = self.expect_error( Exception, lambda: lm_node.local_manager_target_gids ) expected = ( "Authenticated member defined in local manager groups " "'admin_group_1', 'admin_group_2' but only one management group allowed " "for each user. Please contact System Administrator in order to fix " "this problem." ) self.assertEqual(str(err), expected) del group['localmanager_1'] group() self.assertEqual(group.member_ids, [u'localmanager_2']) # Authenticated, local manager with self.layer.authenticated('localmanager_1'): self.assertEqual( sorted(lm_node.local_manager_target_gids), ['group0', 'group1'] ) self.assertEqual(lm_node.local_manager_target_uids, ['uid1']) with self.layer.authenticated('localmanager_2'): self.assertEqual( sorted(lm_node.local_manager_target_gids), ['group1', 'group2'] ) self.assertEqual( sorted(lm_node.local_manager_target_uids), ['uid1', 'uid2'] ) # Check of group id is marked as default self.assertFalse(lm_node.local_manager_is_default('admin_group_1', 'group0')) err = self.expect_error( Exception, lm_node.local_manager_is_default, 'admin_group_2', 'group0' ) expected = "group 'group0' not managed by 'admin_group_2'" self.assertEqual(str(err), expected) self.assertTrue(lm_node.local_manager_is_default('admin_group_1', 'group1')) self.assertFalse(lm_node.local_manager_is_default('admin_group_2', 'group1')) err = self.expect_error( Exception, lm_node.local_manager_is_default, 'admin_group_1', 'group2' ) expected = "group 'group2' not managed by 'admin_group_1'" self.assertEqual(str(err), expected) self.assertTrue(lm_node.local_manager_is_default('admin_group_2', 'group2'))
def test_LocalManagerACL(self): root = get_root() self.layer.new_request() # Local manager ACL for users node users = root['users'] self.assertEqual(users.local_manager_acl, []) with self.layer.authenticated('uid1'): self.assertEqual(users.local_manager_acl, []) with self.layer.authenticated('localmanager_1'): self.assertEqual(users.local_manager_acl, [ ('Allow', 'localmanager_1', [ 'view', 'add', 'add_user', 'edit', 'edit_user', 'manage_expiration', 'manage_membership' ]) ]) # Local manager ACL for groups node groups = root['groups'] self.assertEqual(groups.local_manager_acl, []) with self.layer.authenticated('uid1'): self.assertEqual(groups.local_manager_acl, []) with self.layer.authenticated('localmanager_1'): self.assertEqual(groups.local_manager_acl, [ ('Allow', 'localmanager_1', ['view', 'manage_membership']) ]) # Local manager ACL for group node group0 = groups['group0'] group1 = groups['group1'] group2 = groups['group2'] self.assertEqual(group0.local_manager_acl, []) self.assertEqual(group1.local_manager_acl, []) self.assertEqual(group2.local_manager_acl, []) with self.layer.authenticated('uid1'): self.assertEqual(group0.local_manager_acl, []) self.assertEqual(group1.local_manager_acl, []) self.assertEqual(group2.local_manager_acl, []) with self.layer.authenticated('localmanager_1'): self.assertEqual(group0.local_manager_acl, [ ('Allow', 'localmanager_1', ['view', 'manage_membership']) ]) self.assertEqual(group1.local_manager_acl, [ ('Allow', 'localmanager_1', ['view', 'manage_membership']) ]) self.assertEqual(group2.local_manager_acl, []) with self.layer.authenticated('localmanager_2'): self.assertEqual(group0.local_manager_acl, []) self.assertEqual(group1.local_manager_acl, [ ('Allow', 'localmanager_2', ['view', 'manage_membership']) ]) self.assertEqual(group2.local_manager_acl, [ ('Allow', 'localmanager_2', ['view', 'manage_membership']) ]) # Local manager ACL for user node user1 = users['uid1'] user2 = users['uid2'] self.assertEqual(user1.local_manager_acl, []) self.assertEqual(user2.local_manager_acl, []) with self.layer.authenticated('uid1'): self.assertEqual(user1.local_manager_acl, []) self.assertEqual(user2.local_manager_acl, []) with self.layer.authenticated('localmanager_1'): self.assertEqual(user1.local_manager_acl, [ ('Allow', 'localmanager_1', [ 'view', 'add', 'add_user', 'edit', 'edit_user', 'manage_expiration', 'manage_membership' ]) ]) self.assertEqual(user2.local_manager_acl, []) with self.layer.authenticated('localmanager_2'): self.assertEqual(user1.local_manager_acl, [ ('Allow', 'localmanager_2', [ 'view', 'add', 'add_user', 'edit', 'edit_user', 'manage_expiration', 'manage_membership' ]) ]) self.assertEqual(user2.local_manager_acl, [ ('Allow', 'localmanager_2', [ 'view', 'add', 'add_user', 'edit', 'edit_user', 'manage_expiration', 'manage_membership' ]) ])
def wrapper(inst): w(inst) cfg = ugm_general(get_root()) cfg.attrs.users_portrait = u'True' cfg()
def test_autoincrement(self): root = get_root() users = root['users'] cfg = ugm_general(users) self.assertEqual(cfg.attrs.user_id_autoincrement, 'False') self.assertEqual(cfg.attrs.user_id_autoincrement_prefix, '') vessel = user_vessel(users) request = self.layer.new_request() with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.checkOutput(""" ...<input class="form-control required text" id="input-userform-id" name="userform.id" required="required" type="text" value="" />... """, res) cfg.attrs.user_id_autoincrement = 'True' cfg() vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.checkOutput(""" ...<input class="form-control text" disabled="disabled" id="input-userform-id" name="userform.id" type="text" value="auto_incremented" />... """, res) request = user_request( self.layer, 'Sepp Unterwurzacher', 'Sepp', '*****@*****.**' ) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), [ '100', 'admin', 'editor', 'localmanager_1', 'localmanager_2', 'manager', 'max', 'sepp', 'uid0', 'uid1', 'uid2', 'uid3', 'uid4', 'uid5', 'uid6', 'uid7', 'uid8', 'uid9', 'viewer' ]) request = user_request( self.layer, 'Franz Hinterhuber', 'Franz', '*****@*****.**' ) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), [ '100', '101', 'admin', 'editor', 'localmanager_1', 'localmanager_2', 'manager', 'max', 'sepp', 'uid0', 'uid1', 'uid2', 'uid3', 'uid4', 'uid5', 'uid6', 'uid7', 'uid8', 'uid9', 'viewer' ]) cfg.attrs.user_id_autoincrement_prefix = 'uid' cfg() request = user_request( self.layer, 'Ander Er', 'Ander', '*****@*****.**' ) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), [ '100', '101', 'admin', 'editor', 'localmanager_1', 'localmanager_2', 'manager', 'max', 'sepp', 'uid0', 'uid1', 'uid100', 'uid2', 'uid3', 'uid4', 'uid5', 'uid6', 'uid7', 'uid8', 'uid9', 'viewer' ]) request = user_request( self.layer, 'Hirs Schneider', 'Hirs', '*****@*****.**' ) vessel = user_vessel(users) with self.layer.authenticated('manager'): res = render_tile(vessel, request, 'addform') self.assertEqual(sorted(users.keys()), [ '100', '101', 'admin', 'editor', 'localmanager_1', 'localmanager_2', 'manager', 'max', 'sepp', 'uid0', 'uid1', 'uid100', 'uid101', 'uid2', 'uid3', 'uid4', 'uid5', 'uid6', 'uid7', 'uid8', 'uid9', 'viewer' ])
def test_login_view(self): root = get_root() request = self.layer.new_request() response = login_view(root, request) self.assertTrue(isinstance(response, Response))
def test_logout_view(self): root = get_root() request = self.layer.new_request() response = logout_view(root, request) self.assertTrue(isinstance(response, HTTPFound))