class UserTokens(SimpleItem): def __init__(self): self.user_tokens = PersistentMapping() def generateToken(self, userId): import random token = str(random.random()).split('.')[1] self.user_tokens[token] = userId return token def getUserId(self, userToken): if self.user_tokens.has_key(token): return self.user_tokens[token] return None def getUserToken(self, userId): for token, user_id in self.user_tokens.iteritems(): if user_id == userId: return token return None def getUserTokensList(self): tokens = [] for token, user_id in self.user_tokens.iteritems(): tokens.append({'userId' : user_id, 'userToken' : token}) return tokens def removeToken(self, userToken): """ Remove user token. """ if self.user_tokens.has_key(userToken): del self.user_tokens[userToken] else: LOG('', WARNING, 'Tried to remove unexisting token : %s' % userToken)
def _initDCWorkflowStates( workflow, states ): """ Initialize DCWorkflow states """ from Globals import PersistentMapping from Products.DCWorkflow.States import StateDefinition for s_info in states: id = str( s_info[ 'state_id' ] ) # no unicode! s = StateDefinition( id ) workflow.states._setObject( id, s ) s = workflow.states._getOb( id ) s.setProperties( title = s_info[ 'title' ] , description = s_info[ 'description' ] , transitions = s_info[ 'transitions' ] ) for k, v in s_info[ 'permissions' ].items(): s.setPermission( k, isinstance(v, list), v ) gmap = s.group_roles = PersistentMapping() for group_id, roles in s_info[ 'groups' ]: gmap[ group_id ] = roles vmap = s.var_values = PersistentMapping() for name, v_info in s_info[ 'variables' ].items(): value = _convertVariableValue( v_info[ 'value' ] , v_info[ 'type' ] ) vmap[ name ] = value
def setProperties(self, description, actbox_name='', actbox_url='', actbox_category='global', props=None, REQUEST=None): ''' ''' if props is None: props = REQUEST self.description = str(description) for key in self.getAvailableCatalogVars(): # Populate var_matches. fieldname = 'var_match_%s' % key v = props.get(fieldname, '') if v: if not self.var_matches: self.var_matches = PersistentMapping() v = [ var.strip() for var in v.split(';') ] self.var_matches[key] = tuple(v) else: if self.var_matches and self.var_matches.has_key(key): del self.var_matches[key] self.actbox_name = str(actbox_name) self.actbox_url = str(actbox_url) self.actbox_category = str(actbox_category) g = Guard() if g.changeFromProperties(props or REQUEST): self.guard = g else: self.guard = None if REQUEST is not None: return self.manage_properties(REQUEST, 'Properties changed.')
class Resource(Persistent): security = ClassSecurityInfo() def __init__(self, id, **kwargs): self._data = PersistentMapping() self._data['id'] = id self._data['expression'] = kwargs.get('expression', '') self._data['enabled'] = kwargs.get('enabled', True) self._data['cookable'] = kwargs.get('cookable', True) self._data['cacheable'] = kwargs.get('cacheable', True) def copy(self): result = self.__class__(self.getId()) for key, value in self._data.items(): if key != 'id': result._data[key] = value return result security.declarePublic('getId') def getId(self): return self._data['id'] def _setId(self, id): self._data['id'] = id security.declarePublic('getExpression') def getExpression(self): return self._data['expression'] security.declareProtected(permissions.ManagePortal, 'setExpression') def setExpression(self, expression): self._data['expression'] = expression security.declarePublic('getEnabled') def getEnabled(self): return bool(self._data['enabled']) security.declareProtected(permissions.ManagePortal, 'setEnabled') def setEnabled(self, enabled): self._data['enabled'] = enabled security.declarePublic('getCookable') def getCookable(self): return self._data['cookable'] security.declareProtected(permissions.ManagePortal, 'setCookable') def setCookable(self, cookable): self._data['cookable'] = cookable security.declarePublic('getCacheable') def getCacheable(self): # as this is a new property, old instance might not have that value, so # return True as default return self._data.get('cacheable', True) security.declareProtected(permissions.ManagePortal, 'setCacheable') def setCacheable(self, cacheable): self._data['cacheable'] = cacheable
def __init__(self): self._schemas = PersistentMapping() self._templates = PersistentMapping() self._registeredTemplates = PersistentMapping() # meta_type -> [names of CatalogTools] self.catalog_map = PersistentMapping() self.catalog_map['Reference'] = [] # References not in portal_catalog # DM (avoid persistency bug): "_types" now maps known schemas to signatures self._types = {}
def setDependentProducts(jar, productid, dep_ids): productid = str(productid) rd = _getCentralRefreshData(jar, 1) products = rd.get('products', None) if products is None: rd['products'] = products = PersistentMapping() product = products.get(productid, None) if product is None: products[productid] = product = PersistentMapping() product['dependent_products'] = tuple(map(str, dep_ids))
def setRoleMapping(self, portal_role, userfolder_role): """ set the mapping of roles between roles understood by the portal and roles coming from outside user sources """ if not hasattr(self, 'role_map'): self.role_map = PersistentMapping() if len(userfolder_role) < 1: del self.role_map[portal_role] else: self.role_map[portal_role] = userfolder_role return MessageDialog(title='Mapping updated', message='The Role mappings have been updated', action='manage_mapRoles')
class Federations(SimpleItem): def __init__(self): self.federations = PersistentMapping() def getUserId(self, nameIdentifier): return self.federations.get(nameIdentifier, {}).get('user_id') def getIdentityDump(self, nameIdentifier): return self.federations.get(nameIdentifier, {}).get('identity_dump') def setFederation(self, nameIdentifier, userId, identityDump): self.federations[nameIdentifier] = {'user_id': userId, 'identity_dump': identityDump} def removeFederation(self, nameIdentifier): if self.federations.has_key(nameIdentifier): del self.federations[nameIdentifier]
def wl_lockmapping(self, killinvalids=0, create=0): """ if 'killinvalids' is 1, locks who are no longer valid will be deleted """ try: locks = getattr(self, '_dav_writelocks', None) except: locks = None if locks is None: if create: locks = self._dav_writelocks = PersistentMapping() else: # Don't generate a side effect transaction. locks = {} return locks elif killinvalids: # Delete invalid locks for token, lock in locks.items(): if not lock.isValid(): del locks[token] if (not locks) and hasattr(Acquisition.aq_base(self), '__no_valid_write_locks__'): self.__no_valid_write_locks__() return locks else: return locks
def setChainForPortalTypes(self, pt_names, chain, verify=True, REQUEST=None): """ Set a chain for specific portal types. """ cbt = self._chains_by_type if cbt is None: self._chains_by_type = cbt = PersistentMapping() if isinstance(chain, basestring): if chain == '(Default)': chain = None else: chain = [ wf.strip() for wf in chain.split(',') if wf.strip() ] if chain is None: for type_id in pt_names: if cbt.has_key(type_id): del cbt[type_id] return ti_ids = [ t.getId() for t in self._listTypeInfo() ] for type_id in pt_names: if verify and not (type_id in ti_ids): continue cbt[type_id] = tuple(chain)
def setGlobalConfigurationAttr(self, **kw): """ Set global business configuration attribute. """ if getattr(aq_base(self), '_global_configuration_attributes', None) is None: self._global_configuration_attributes = PersistentMapping() for key, value in kw.items(): self._global_configuration_attributes[key] = value
def get_po_header(self, lang): """ """ # For backwards compatibility if not hasattr(aq_base(self), "_po_headers"): self._po_headers = PersistentMapping() return self._po_headers.get(lang, empty_po_header)
def setMultiEntryTransition(self, transition_url, max_entry_number): """ Set a transition as multiple - i.e max_entry_number of forms which will be rendered. This method is called in after scripts and usually this number is set by user in a web form. """ if getattr(aq_base(self), '_multi_entry_transitions', None) is None: self._multi_entry_transitions = PersistentMapping() self._multi_entry_transitions[transition_url] = max_entry_number
def __init__(self, id, title, sourcelang, languages): self.id = id self.title = title # Language Manager data self._languages = tuple(languages) self._default_language = sourcelang # Here the message translations are stored self._messages = PersistentMapping() # Data for the PO files headers self._po_headers = PersistentMapping() for lang in self._languages: self._po_headers[lang] = empty_po_header
def __init__(self, id, **kwargs): self._data = PersistentMapping() self._data['id'] = id self._data['expression'] = kwargs.get('expression', '') self._data['enabled'] = kwargs.get('enabled', True) self._data['cookable'] = kwargs.get('cookable', True) self._data['cacheable'] = kwargs.get('cacheable', True)
def _initDCWorkflowWorklists(workflow, worklists): """ Initialize DCWorkflow worklists """ from Globals import PersistentMapping from Products.DCWorkflow.Worklists import WorklistDefinition for w_info in worklists: id = str(w_info['worklist_id']) # no unicode! if not workflow.worklists.has_key(id): w = WorklistDefinition(id) workflow.worklists._setObject(id, w) w = workflow.worklists._getOb(id) action = w_info['action'] guard = w_info['guard'] props = { 'guard_roles': ';'.join(guard['roles']), 'guard_permissions': ';'.join(guard['permissions']), 'guard_groups': ';'.join(guard['groups']), 'guard_expr': guard['expression'] } w.setProperties(description=w_info['description'], actbox_name=action['name'], actbox_url=action['url'], actbox_category=action['category'], props=props) w.var_matches = PersistentMapping() for k, v in w_info['match'].items(): w.var_matches[str(k)] = tuple([str(x) for x in v])
def install(self): " Register the CMF Topic with portal_types and friends " out = StringIO() typestool = getToolByName(self, 'portal_types') skinstool = getToolByName(self, 'portal_skins') workflowtool = getToolByName(self, 'portal_workflow') # Borrowed from CMFDefault.Portal.PortalGenerator.setupTypes() # We loop through anything defined in the factory type information # and configure it in the types tool if it doesn't already exist for t in CMFWikiPage.factory_type_information: if t['id'] not in typestool.objectIds(): cfm = apply(ContentFactoryMetadata, (), t) typestool._setObject(t['id'], cfm) out.write('Registered %s with the types tool\n' % t['id']) else: out.write('Object "%s" already existed in the types tool\n' % (t['id'])) # Setup the skins # This is borrowed from CMFDefault/scripts/addImagesToSkinPaths.pys if 'wiki' not in skinstool.objectIds(): # We need to add Filesystem Directory Views for any directories # in our skins/ directory. These directories should already be # configured. addDirectoryViews(skinstool, 'skins', wiki_globals) out.write("Added 'wiki' directory view to portal_skins\n") # Now we need to go through the skin configurations and insert # 'wiki' into the configurations. Preferably, this should be # right before where 'content' is placed. Otherwise, we append # it to the end. skins = skinstool.getSkinSelections() for skin in skins: path = skinstool.getSkinPath(skin) path = map(string.strip, string.split(path, ',')) for dir in ('wiki', 'zpt_wiki'): if not dir in path: try: idx = path.index('custom') except ValueError: idx = 999 path.insert(idx + 1, dir) path = string.join(path, ', ') # addSkinSelection will replace existing skins as well. skinstool.addSkinSelection(skin, path) out.write("Added 'wiki' and 'zpt_wiki' to %s skin\n" % skin) # remove workflow for Wiki pages cbt = workflowtool._chains_by_type if cbt is None: cbt = PersistentMapping() cbt['CMF Wiki'] = [] cbt['CMF Wiki Page'] = [] workflowtool._chains_by_type = cbt out.write("Removed all workflow from CMF Wikis and CMF Wiki Pages") return out.getvalue()
def __init__( self, publisher=None #, initial_values_hook=None #, validation_hook=None , element_specs=DEFAULT_ELEMENT_SPECS): self.editProperties(publisher #, initial_values_hook #, validation_hook ) self.element_specs = PersistentMapping() for name, is_multi_valued in element_specs: self.element_specs[name] = ElementSpec(is_multi_valued)
def __init__(self,): self.encodings_map = encodings_map.copy() self.suffix_map = suffix_map.copy() # Major key -> minor IMimetype objects self._mimetypes = PersistentMapping() # ext -> IMimetype mapping self.extensions = PersistentMapping() # glob -> (regex, mimetype) mapping self.globs = OOBTree() self.manage_addProperty('defaultMimetype', 'text/plain', 'string') self.manage_addProperty('unicodePolicies', 'strict ignore replace', 'tokens') self.manage_addProperty('unicodePolicy', 'unicodePolicies', 'selection') self.manage_addProperty('fallbackEncoding', 'latin1', 'string') # initialize mime types initialize(self) self._new_style_mtr = 1
def addVariable(self,id,value,REQUEST=None): """Add a WorkflowVariable to State.""" if self.var_values is None: self.var_values = PersistentMapping() self.var_values[id] = value if REQUEST is not None: return self.manage_variables(REQUEST, 'Variable added.')
def _getCentralRefreshData(jar, create=0): root = jar.root() if root.has_key('RefreshData'): rd = root['RefreshData'] else: rd = PersistentMapping() if create: root['RefreshData'] = rd return rd
def listPolicies(self): """ return the list of defined policies a policy is a 2-uple (output_mime_type, [list of required transforms]) """ # XXXFIXME: backward compat, should be removed latter if not hasattr(self, '_policies'): self._policies = PersistentMapping() return self._policies.items()
def setPermission(self, permission, acquired, roles): """Set a permission for this State.""" pr = self.permission_roles if pr is None: self.permission_roles = pr = PersistentMapping() if acquired: roles = list(roles) else: roles = tuple(roles) pr[permission] = roles
def migrateDiscussionContainer(self, src_folder, dst_folder, place=()): self.visited_folders.append( '/'.join(place) ) dst_container = getattr(dst_folder, '_container', None) if dst_container is None: dst_container = dst_folder._container = PersistentMapping() for id, s_ob in src_folder._container.items(): d_ob = dst_container.get(id) to_store = self.migrateObject(id, s_ob, d_ob, dst_folder, place + (id,)) if to_store is not None: dst_container[id] = aq_base(to_store)
def make_config_persistent(kwargs): """ iterates on the given dictionnary and replace list by persistent list, dictionary by persistent mapping. """ for key, value in kwargs.items(): if type(value) == type({}): p_value = PersistentMapping(value) kwargs[key] = p_value elif type(value) in (type(()), type([])): p_value = PersistentList(value) kwargs[key] = p_value
def setPermission(self, permission, acquired, roles): ''' ''' pr = self.permission_roles if pr is None: self.permission_roles = pr = PersistentMapping() if acquired: roles = list(roles) else: roles = tuple(roles) pr[permission] = roles
def setVariables(self, ids=[], REQUEST=None): """Set values for Variables set by this State.""" if self.var_values is None: self.var_values = PersistentMapping() vv = self.var_values if REQUEST is not None: for id in vv.keys(): fname = 'varval_%s' % id vv[id] = str(REQUEST[fname]) return self.manage_variables(REQUEST, 'Variables changed.')
def setChainForPortalTypes(self, pt_names, chain): """ Set a chain for a specific portal type """ cbt = self._chains_by_type if cbt is None: self._chains_by_type = cbt = PersistentMapping() if type(chain) is type(''): chain = map(strip, split(chain, ',')) ti = self._listTypeInfo() for t in ti: id = t.getId() if id in pt_names: cbt[id] = tuple(chain)
def addVariable(self, id, text, REQUEST=None): ''' Add a variable expression. ''' if self.var_exprs is None: self.var_exprs = PersistentMapping() expr = None if text: expr = Expression(str(text)) self.var_exprs[id] = expr if REQUEST is not None: return self.manage_variables(REQUEST, 'Variable added.')
def enableAutoRefresh(jar, productid, enable): productid = str(productid) rd = _getCentralRefreshData(jar, 1) ids = rd.get('auto', None) if ids is None: if enable: rd['auto'] = ids = PersistentMapping() else: return if enable: ids[productid] = 1 else: if ids.has_key(productid): del ids[productid]
def setChainForPortalTypes(self, pt_names, chain): """ Set a chain for a specific portal type. """ cbt = self._chains_by_type if cbt is None: self._chains_by_type = cbt = PersistentMapping() if isinstance(chain, basestring): chain = [wf.strip() for wf in chain.split(',') if wf.strip()] ti = self._listTypeInfo() for t in ti: id = t.getId() if id in pt_names: cbt[id] = tuple(chain)
def __init__( self , publisher=None #, initial_values_hook=None #, validation_hook=None , element_specs=DEFAULT_ELEMENT_SPECS ): self.editProperties( publisher #, initial_values_hook #, validation_hook ) self.element_specs = PersistentMapping() for name, is_multi_valued in element_specs: self.element_specs[ name ] = ElementSpec( is_multi_valued )
def setPermissions(self, REQUEST): """Set the permissions in REQUEST for this State.""" pr = self.permission_roles if pr is None: self.permission_roles = pr = PersistentMapping() for p in self.getManagedPermissions(): roles = [] acquired = REQUEST.get('acquire_' + p, 0) for r in self.getAvailableRoles(): if REQUEST.get('%s|%s' % (p, r), 0): roles.append(r) roles.sort() if not acquired: roles = tuple(roles) pr[p] = roles return self.manage_permissions(REQUEST, 'Permissions changed.')
def setRoleMapping(self, portal_role, userfolder_role): """ set the mapping of roles between roles understood by the portal and roles coming from outside user sources """ if not hasattr(self, 'role_map'): self.role_map = PersistentMapping() if len(userfolder_role) < 1: del self.role_map[portal_role] else: self.role_map[portal_role] = userfolder_role return MessageDialog( title ='Mapping updated', message='The Role mappings have been updated', action ='manage_mapRoles')
def setChainForPortalTypes(self, pt_names, chain, verify=True): """ Set a chain for a specific portal type. """ cbt = self._chains_by_type if cbt is None: self._chains_by_type = cbt = PersistentMapping() if isinstance(chain, basestring): chain = [wf.strip() for wf in chain.split(',') if wf.strip()] ti_ids = [t.getId() for t in self._listTypeInfo()] for type_id in pt_names: if verify and not (type_id in ti_ids): continue cbt[type_id] = tuple(chain)
def setStatusOf(self, wf_id, ob, status): """ Append a record to the workflow history of a given workflow. """ wfh = None has_history = 0 if hasattr(aq_base(ob), 'workflow_history'): history = ob.workflow_history if history is not None: has_history = 1 wfh = history.get(wf_id, None) if wfh is not None: wfh = list(wfh) if not wfh: wfh = [] wfh.append(status) if not has_history: ob.workflow_history = PersistentMapping() ob.workflow_history[wf_id] = tuple(wfh)
def po_import(self, lang, data): """ """ messages = self._messages resource = memory.File(data) po = PO.PO(resource) # Load the data for msgid in po.get_msgids(): if isinstance(msgid, unicode): msgid = msgid.encode('utf-8') if msgid: msgstr = po.get_msgstr(msgid) or '' if not messages.has_key(msgid): messages[msgid] = PersistentMapping() messages[msgid][lang] = msgstr # Set the encoding (the full header should be loaded XXX) self.update_po_header(lang, charset=po.get_encoding())
def setVariables(self, ids=[], REQUEST=None): ''' set values for Variables set by this state ''' if self.var_exprs is None: self.var_exprs = PersistentMapping() ve = self.var_exprs if REQUEST is not None: for id in ve.keys(): fname = 'varexpr_%s' % id val = REQUEST[fname] expr = None if val: expr = Expression(str(REQUEST[fname])) ve[id] = expr return self.manage_variables(REQUEST, 'Variables changed.')
def setStatusOf(self, wf_id, ob, status): ''' Invoked by workflow definitions. Appends to the workflow history. ''' wfh = None has_history = 0 if hasattr(aq_base(ob), 'workflow_history'): history = ob.workflow_history if history is not None: has_history = 1 wfh = history.get(wf_id, None) if wfh is not None: wfh = list(wfh) if not wfh: wfh = [] wfh.append(status) if not has_history: ob.workflow_history = PersistentMapping() ob.workflow_history[wf_id] = tuple(wfh)
def manage_changeWorkflows(self, default_chain, props=None, REQUEST=None): """ Changes which workflows apply to objects of which type. """ if props is None: props = REQUEST cbt = self._chains_by_type if cbt is None: self._chains_by_type = cbt = PersistentMapping() ti = self._listTypeInfo() # Set up the chains by type. if not (props is None): for t in ti: id = t.getId() field_name = 'chain_%s' % id chain = props.get(field_name, '(Default)').strip() if chain == '(Default)': # Remove from cbt. if cbt.has_key(id): del cbt[id] else: chain = chain.replace(',', ' ') ids = [] for wf_id in chain.split(' '): if wf_id: if not self.getWorkflowById(wf_id): raise ValueError, ( '"%s" is not a workflow ID.' % wf_id) ids.append(wf_id) cbt[id] = tuple(ids) # Set up the default chain. default_chain = default_chain.replace(',', ' ') ids = [] for wf_id in default_chain.split(' '): if wf_id: if not self.getWorkflowById(wf_id): raise ValueError, ( '"%s" is not a workflow ID.' % wf_id) ids.append(wf_id) self._default_chain = tuple(ids) if REQUEST is not None: return self.manage_selectWorkflows(REQUEST, manage_tabs_message='Changed.')
def setGroups(self, REQUEST, RESPONSE=None): """Set the group to role mappings in REQUEST for this State. """ map = self.group_roles if map is None: self.group_roles = map = PersistentMapping() map.clear() all_roles = self.getWorkflow().getRoles() for group in self.getWorkflow().getGroups(): roles = [] for role in all_roles: if REQUEST.get('%s|%s' % (group, role), 0): roles.append(role) roles.sort() roles = tuple(roles) map[group] = roles if RESPONSE is not None: RESPONSE.redirect( "%s/manage_groups?manage_tabs_message=Groups+changed." % self.absolute_url())
def __init__( self, is_multi_valued ): self.is_multi_valued = is_multi_valued self.policies = PersistentMapping() self.policies[ None ] = self._makePolicy() # set default policy
class ElementSpec( SimpleItem ): """ Represent all the tool knows about a single metadata element. """ security = ClassSecurityInfo() # # Default values. # is_multi_valued = 0 def __init__( self, is_multi_valued ): self.is_multi_valued = is_multi_valued self.policies = PersistentMapping() self.policies[ None ] = self._makePolicy() # set default policy security.declarePrivate( '_makePolicy' ) def _makePolicy( self ): return MetadataElementPolicy( self.is_multi_valued ) security.declareProtected(View , 'isMultiValued') def isMultiValued( self ): """ Is this element multi-valued? """ return self.is_multi_valued security.declareProtected(View , 'getPolicy') def getPolicy( self, typ=None ): """ Find the policy this element for objects whose type object name is 'typ'; return a default, if none found. """ try: return self.policies[ typ ].__of__(self) except KeyError: return self.policies[ None ] security.declareProtected(View , 'listPolicies') def listPolicies( self ): """ Return a list of all policies for this element. """ res = [] for k, v in self.policies.items(): res.append((k, v.__of__(self))) return res security.declareProtected(ManagePortal , 'addPolicy') def addPolicy( self, typ ): """ Add a policy to this element for objects whose type object name is 'typ'. """ if typ is None: raise MetadataError, "Can't replace default policy." if self.policies.has_key( typ ): raise MetadataError, "Existing policy for content type:" + typ self.policies[ typ ] = self._makePolicy() security.declareProtected(ManagePortal, 'removePolicy') def removePolicy( self, typ ): """ Remove the policy from this element for objects whose type object name is 'typ' (*not* the default, however). """ if typ is None: raise MetadataError, "Can't remove default policy." del self.policies[ typ ]
class AuthenticationTool( BasicUserFolder, Role, ObjectManager, session_manager, file_utils, plugins_tool, PropertyManager ): meta_type = METATYPE_AUTHENTICATIONTOOL icon = "misc_/NaayaCore/AuthenticationTool.gif" manage_options = ( {"label": "Users", "action": "manage_users_html"}, {"label": "Roles", "action": "manage_roles_html"}, {"label": "Permissions", "action": "manage_permissions_html"}, {"label": "Other sources", "action": "manage_sources_html"}, {"label": "Properties", "action": "manage_propertiesForm", "help": ("OFSP", "Properties.stx")}, ) _properties = ( {"id": "title", "type": "string", "mode": "w", "label": "Title"}, {"id": "encrypt_passwords", "type": "boolean", "mode": "w", "label": "Encrypt users passwords"}, { "id": "email_expression", "type": "string", "mode": "w", "label": "E-mail should match this regular expression", }, { "id": "email_confirmation", "type": "boolean", "mode": "w", "label": "Ask for email confirmation before add user ", }, ) security = ClassSecurityInfo() # # Properties # encrypt_passwords = False email_expression = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$" email_confirmation = False def __init__(self, id, title): self.id = id self.title = title self.data = PersistentMapping() Role.__dict__["__init__"](self) plugins_tool.__dict__["__init__"](self) security.declarePrivate("loadDefaultData") def loadDefaultData(self): # load default stuff pass security.declarePrivate("_doAddTempUser") def _doAddTempUser(self, **kwargs): """Generate a confirmation string, add it to temp users list, and return it. """ text = object2string(kwargs) if not hasattr(self, "_temp_users"): self._temp_users = [] if text in self._temp_users: raise Exception, "User already request access roles." self._temp_users.append(text) self._p_changed = 1 return text security.declarePrivate("_doAddUser") def _doAddUser(self, name, password, roles, domains, firstname, lastname, email, **kw): """Create a new user. The 'password' will be the original input password, unencrypted. This method is responsible for performing any needed encryption.""" if password is not None and self.encrypt_passwords: password = self._encryptPassword(password) self.data[name] = User(name, password, roles, domains, firstname, lastname, email) self._p_changed = 1 return name security.declarePrivate("_doChangeUser") def _doChangeUser(self, name, password, roles, domains, firstname, lastname, email, lastupdated, **kw): """Modify an existing user. The 'password' will be the original input password, unencrypted. The implementation of this method is responsible for performing any needed encryption.""" user = self.data[name] if password is not None: if self.encrypt_passwords and not self._isPasswordEncrypted(password): password = self._encryptPassword(password) user.__ = password user.roles = roles user.domains = domains user.firstname = firstname user.lastname = lastname user.email = email user.lastupdated = lastupdated self._p_changed = 1 security.declarePublic("changeLastLogin") def changeLastLogin(self, name): user = self.data.get(name, None) if user: user.lastlogin = time.strftime("%d %b %Y %H:%M:%S") self._p_changed = 1 security.declarePublic("changeLastPost") def changeLastPost(self, name): user = self.data.get(name, None) if user: user.lastpost = time.strftime("%d %b %Y %H:%M:%S") self._p_changed = 1 security.declareProtected(manage_users, "getUserPass") def getUserPass(self): """Return a list of usernames""" temp = {} names = self.data.keys() for name in names: temp[name] = self.getUser(name).__ return temp security.declarePrivate("_doChangeUserRoles") def _doChangeUserRoles(self, name, roles, **kw): """ """ user = self.data[name] user.roles = roles self._p_changed = 1 security.declarePrivate("_doDelUserRoles") def _doDelUserRoles(self, name, **kw): """ """ for user in name: user_obj = self.data[user] user_obj.roles = [] self._p_changed = 1 security.declarePrivate("_doDelUsers") def _doDelUsers(self, names): """Delete one or more users.""" for name in names: del self.data[name] self._p_changed = 1 # zmi actions security.declareProtected(manage_users, "manage_confirmUser") def manage_confirmUser(self, key="", REQUEST=None): """ Add user from key """ if key not in getattr(self, "_temp_users", []): raise Exception, "Invalid activation key !" try: res = string2object(key) except InvalidStringError, err: raise Exception, "Invalid activation key !" else:
def __init__( self, id, element_specs=() ): self._setId( id ) self.element_specs = PersistentMapping() for name, is_multi_valued in element_specs: self.element_specs[ name ] = ElementSpec( is_multi_valued )
def __init__(self): self.data=PersistentMapping()
class DocAuthentication(BasicUserFolder, ObjectManager, session, CookieCrumbler): meta_type = 'User Folder' icon = 'misc_/Finshare/acl_users.gif' manage_options = ( {'label' : 'Users', 'action' : 'manage_users_html'}, {'label' : 'Permissions', 'action' : 'manage_permissions_html'}, ) security = ClassSecurityInfo() def __init__(self, id, title): self.id = id self.title = title self.data = PersistentMapping() ########################### # PRIVATE METHODS # ########################### security.declarePrivate('_doAddUser') def _doAddUser(self, name, password, roles, firstname, lastname, email, **kw): """Create a new user. The 'password' will be the original input password, unencrypted. This method is responsible for performing any needed encryption.""" if password is not None and self.encrypt_passwords: password = self._encryptPassword(password) self.data[name] = User(name, password, roles, firstname, lastname, email) self._p_changed = 1 security.declarePrivate('_doChangeUser') def _doChangeUser(self, name, password, roles, firstname, lastname, email, lastupdated, notifications, **kw): """Modify an existing user. The 'password' will be the original input password, unencrypted. The implementation of this method is responsible for performing any needed encryption.""" user=self.data[name] if password is not None: if self.encrypt_passwords and not self._isPasswordEncrypted(password): password = self._encryptPassword(password) user.__ = password user.roles = roles user.firstname = firstname user.lastname = lastname user.email = email user.lastupdated = lastupdated user.notifications = notifications self._p_changed = 1 security.declarePrivate('_doDelUsers') def _doDelUsers(self, names): """Delete one or more users.""" for name in names: del self.data[name] self._p_changed = 1 security.declareProtected(PERMISSION_EDIT_USERS, 'manage_addUser') def manage_addUser(self, user='', pwd='', cpwd='', role='', fname='', lname='', email='', REQUEST=None): """ """ if REQUEST and REQUEST.has_key('CancelButton'): return REQUEST.RESPONSE.redirect(REQUEST['destination']) errors = [] if not string.strip(user): errors.append(ERROR102) if not string.strip(fname): errors.append(ERROR100) if not string.strip(lname): errors.append(ERROR101) if not string.strip(email): errors.append(ERROR104) if not string.strip(pwd) or not string.strip(cpwd): errors.append(ERROR103) if self.getUser(user) or (self._emergency_user and user == self._emergency_user.getUserName()): errors.append(ERROR105) if (pwd or cpwd) and (pwd != cpwd): errors.append(ERROR106) users = self.getUserNames() for n in users: us = self.getUser(n) if email.strip() == us.email: errors.append(ERROR113) break if fname == us.firstname and lname == us.lastname: errors.append(ERROR114) break role = self.utConvertToList(role) #domains are not used for the moment #if domains and not self.domainSpecValidate(domains): # errors.append(ERROR107) if len(errors): if REQUEST is not None: #save form data to session self.setUserSession(user, role, fname, lname, email) #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) else: return errors self._doAddUser(user, pwd, role, fname, lname, email) if REQUEST is not None and REQUEST.has_key('destination'): return REQUEST.RESPONSE.redirect(REQUEST['destination']) security.declareProtected(PERMISSION_EDIT_USERS, 'manage_changeUser') def manage_changeUser(self, user='', role='', fname='', lname='', email='', lastupdated='', REQUEST=None): """ """ if REQUEST and REQUEST.has_key('CancelButton'): return REQUEST.RESPONSE.redirect(REQUEST['destination']) errors = [] if not fname: errors.append(ERROR100) if not lname: errors.append(ERROR101) if not email: errors.append(ERROR104) user_ob = self.getUser(user) role = self.utConvertToList(role) if len(errors): if REQUEST is not None: #save form data to session self.setUserSession(user, role, fname, lname, email) #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) else: return errors #domains are not used for the moment #if domains and not self.domainSpecValidate(domains): # errors.append(ERROR107) lastupdated = time.strftime('%d %b %Y %H:%M:%S') self._doChangeUser(user, self.getUserPassword(user_ob), role, fname, lname, email, lastupdated, []) if REQUEST is not None and REQUEST.has_key('destination'): return REQUEST.RESPONSE.redirect(REQUEST['destination'] + '?save=ok') security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'changeUserAccount') def changeUserAccount(self, user='', fname='', lname='', email='', REQUEST=None, RESPONSE=None): """ change user account information """ errors = [] if not fname: errors.append(ERROR100) if not lname: errors.append(ERROR101) if not email: errors.append(ERROR104) user_ob = self.getUser(user) if len(errors): if REQUEST is not None: #save form data to session self.setUserSession(user, '', fname, lname, email) #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) else: return errors lastupdated = time.strftime('%d %b %Y %H:%M:%S') self._doChangeUser(user, self.getUserPassword(user_ob), self.getUserRoles(user_ob), fname, lname, email, lastupdated, []) if REQUEST is not None: return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER + '?save=ok') security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'changeUserPassword') def changeUserPassword(self, user='', opass='', npass='', cpass='', REQUEST=None, RESPONSE=None): """ change user password """ errors = [] if not opass: errors.append(ERROR115) if (npass or cpass) and (npass != cpass): errors.append(ERROR106) if npass == cpass == '': errors.append(ERROR103) user_ob = self.getUser(user) if opass != self.getUserPassword(user_ob): errors.append(ERROR116) if len(errors): if REQUEST is not None: #save form data to session self.setUserSession(user, '', '', '', '') #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) else: return errors lastupdated = time.strftime('%d %b %Y %H:%M:%S') self._doChangeUser(user, npass, self.getUserRoles(user_ob), self.getUserFirstName(user_ob), self.getUserLastName(user_ob), self.getUserEmail(user_ob), lastupdated, []) self.credentialsChanged(user, npass) if REQUEST is not None: return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER + '?save=ok') security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'changeUserNotifications') def changeUserNotifications(self, user='', newsletter=[], REQUEST=None, RESPONSE=None): """ change user notifications list """ if newsletter: notifications = self.utConvertToList(newsletter) else: notifications = [] user_ob = self.getUser(user) lastupdated = time.strftime('%d %b %Y %H:%M:%S') self._doChangeUser(user, self.getUserPassword(user_ob), self.getUserRoles(user_ob), self.getUserFirstName(user_ob), self.getUserLastName(user_ob), self.getUserEmail(user_ob), lastupdated, notifications) if REQUEST is not None: return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER + '?save=ok') security.declarePublic('registerUser') def registerUser(self, user='', fname='', lname='', email='', npass='', cpass='', REQUEST=None, RESPONSE=None): """ register a new user """ errors = [] if not string.strip(user): errors.append(ERROR102) if not string.strip(fname): errors.append(ERROR100) if not string.strip(lname): errors.append(ERROR101) if not string.strip(email): errors.append(ERROR104) if not string.strip(npass) or not string.strip(cpass): errors.append(ERROR103) if self.getUser(user) or (self._emergency_user and user == self._emergency_user.getUserName()): errors.append(ERROR105) if (npass or cpass) and (npass != cpass): errors.append(ERROR106) users = self.getUserNames() for n in users: us = self.getUser(n) if email.strip() == us.email: errors.append(ERROR113) break if fname == us.firstname and lname == us.lastname: errors.append(ERROR114) break if len(errors): if REQUEST is not None: #save form data to session self.setUserSession(user, '', fname, lname, email) #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) else: return errors n = Notification() template_text = self.notification.register.document_src() template_html = self.notification.register_html.document_src() if self.notification.register.title: subject = self.notification.register.title elif self.notification.register_html.title: subject = self.notification.register_html.title else: subject = "finShare notifications" if self.webmaster: webmaster = self.webmaster else: webmaster = "*****@*****.**" n.send_registration(user, email, fname, lname, npass, webmaster, subject, template_text, template_html) if REQUEST is not None and REQUEST.has_key('destination'): return REQUEST.RESPONSE.redirect(REQUEST['destination'] + '?save=ok') security.declarePublic('forgotPassword') def lostPassword(self, email='', REQUEST=None, RESPONSE=None): """ forgot password """ errors = [] if not string.strip(email): errors.append(ERROR104) pwd = fname = lname = accoount = None if email!='': for n in self.getUserNames(): us = self.getUser(n) if email.strip() == us.email: pwd = self.getUserPassword(us) fname = self.getUserFirstName(us) lname = self.getUserLastName(us) account = self.getUserAccount(us) break if pwd is None: errors.append(ERROR117) if len(errors): if REQUEST is not None: #save form data to session self.setUserSession('', '', '', '', email) #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) else: return errors n = Notification() template_text = self.notification.sendpassword.document_src() template_html = self.notification.sendpassword_html.document_src() if self.notification.sendpassword.title: subject = self.notification.sendpassword.title elif self.notification.sendpassword_html.title: subject = self.notification.sendpassword_html.title else: subject = "finShare notifications" if self.webmaster: webmaster = self.webmaster else: webmaster = "*****@*****.**" n.send_passwords(account, email, fname, lname, pwd, webmaster, subject, template_text, template_html) if REQUEST is not None and REQUEST.has_key('destination'): return REQUEST.RESPONSE.redirect(REQUEST['destination'] + '?save=ok') security.declarePublic('sendFeedback') def sendFeedback(self, title, comments, REQUEST=None): """ send feedback """ n = Notification() template_text = self.notification.feedback.document_src() template_html = self.notification.feedback_html.document_src() user = self.REQUEST.AUTHENTICATED_USER.getUserName() user_ob = self.getUser(user) fname = self.getUserFirstName(user_ob) lname = self.getUserLastName(user_ob) email = self.getUserEmail(user_ob) n.send_feedback(title, comments, fname, lname, email, self.getDocManagerURL(), '*****@*****.**', template_text, template_html) if REQUEST is not None and REQUEST.has_key('destination'): return REQUEST.RESPONSE.redirect(REQUEST['destination'] + '?send=ok') security.declareProtected(PERMISSION_EDIT_USERS, 'manage_delUsers') def manage_delUsers(self, users=[], REQUEST=None): """ """ errors = [] names = self.utConvertToList(users) if len(names) == 0: errors.append(ERROR108) if len(errors): #save error to session self.setSessionErrors(errors) return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER) self._doDelUsers(names) if REQUEST: return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER + '?save=ok') ########################### # USER METHODS # ########################### def getUserNames(self): """Return a list of usernames""" names=self.data.keys() names.sort() return names security.declareProtected(PERMISSION_EDIT_USERS, 'getUsersNames') def getUsersNames(self): """ return a list of usernames """ return self.user_names() def getUsers(self): """Return a list of user objects""" data=self.data names=data.keys() names.sort() users=[] f=users.append for n in names: f(data[n]) return users security.declarePublic('getUser') #xxx def getUser(self, name): """Return the named user object or None""" return self.data.get(name, None) def getUserAccount(self, user_obj): """ Return the username""" return user_obj.name def getUserPassword(self, user_obj): """ Return the password""" return user_obj.__ def getUserFirstName(self, user_obj): """ Return the firstname""" return user_obj.firstname def getUserLastName(self, user_obj): """ Return the lastname""" return user_obj.lastname def getUserEmail(self, user_obj): """ Return the email """ return user_obj.email def getUserRoles(self, user_obj): """ Return the user roles """ return user_obj.roles def getUserHistory(self, user_obj): """ return the last login""" return user_obj.history def getUserCreatedDate(self, user_obj): """ Return the created date """ return user_obj.created def getUserLastUpdated(self, user_obj): """ Return the lastupdated date""" return user_obj.lastupdated def getUserNotifications(self, user_obj): """ Return the lastupdated date""" return user_obj.notifications def forgotPassword(self, email, REQUEST=None, RESPONSE=None): """ retrieve user's password given the email """ security.declareProtected(PERMISSION_EDIT_USERS, 'manage_users_html') manage_users_html = PageTemplateFile('zpt/DocAuth/show_users.zpt', globals()) security.declareProtected(PERMISSION_EDIT_USERS, 'manage_addUser_html') manage_addUser_html = PageTemplateFile('zpt/DocAuth/add_user.zpt', globals()) security.declareProtected(PERMISSION_EDIT_USERS, 'manage_editUser_html') manage_editUser_html = PageTemplateFile('zpt/DocAuth/edit_user.zpt', globals()) security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'personal_html') personal_html = PageTemplateFile('zpt/DocAuth/personal.zpt', globals()) security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'changepwd_html') changepwd_html = PageTemplateFile('zpt/DocAuth/changepwd.zpt', globals()) security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'newsletter_html') newsletter_html = PageTemplateFile('zpt/DocAuth/newsletter.zpt', globals()) security.declareProtected(PERMISSION_VIEW_DMOBJECTS, 'feedback_html') feedback_html = PageTemplateFile('zpt/DocManager/DocManager_feedback', globals())
def __init__(self): self.id = 'talkback' self._container = PersistentMapping()
def __init__(self, id, title): self.id = id self.title = title self.data = PersistentMapping()
def __init__(self, id, title): self.id = id self.title = title self.data = PersistentMapping() Role.__dict__["__init__"](self) plugins_tool.__dict__["__init__"](self)
class MetadataTool( UniqueObject, SimpleItem, ActionProviderBase ): __implements__ = (IMetadataTool, ActionProviderBase.__implements__) id = 'portal_metadata' meta_type = 'Default Metadata Tool' _actions = () # # Default values. # publisher = '' element_specs = None #initial_values_hook = None #validation_hook = None security = ClassSecurityInfo() def __init__( self , publisher=None #, initial_values_hook=None #, validation_hook=None , element_specs=DEFAULT_ELEMENT_SPECS ): self.editProperties( publisher #, initial_values_hook #, validation_hook ) self.element_specs = PersistentMapping() for name, is_multi_valued in element_specs: self.element_specs[ name ] = ElementSpec( is_multi_valued ) # # ZMI methods # manage_options = ( ActionProviderBase.manage_options + ( { 'label' : 'Overview' , 'action' : 'manage_overview' } , { 'label' : 'Properties' , 'action' : 'propertiesForm' } , { 'label' : 'Elements' , 'action' : 'elementPoliciesForm' } # TODO , { 'label' : 'Types' # , 'action' : 'typesForm' # } ) + SimpleItem.manage_options ) security.declareProtected(ManagePortal, 'manage_overview') manage_overview = DTMLFile( 'explainMetadataTool', _dtmldir ) security.declareProtected(ManagePortal, 'propertiesForm') propertiesForm = DTMLFile( 'metadataProperties', _dtmldir ) security.declareProtected(ManagePortal, 'editProperties') def editProperties( self , publisher=None # TODO , initial_values_hook=None # TODO , validation_hook=None , REQUEST=None ): """ Form handler for "tool-wide" properties (including list of metadata elements). """ if publisher is not None: self.publisher = publisher # TODO self.initial_values_hook = initial_values_hook # TODO self.validation_hook = validation_hook if REQUEST is not None: REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/propertiesForm' + '?manage_tabs_message=Tool+updated.' ) security.declareProtected(ManagePortal, 'elementPoliciesForm') elementPoliciesForm = DTMLFile( 'metadataElementPolicies', _dtmldir ) security.declareProtected(ManagePortal, 'addElementPolicy') def addElementPolicy( self , element , content_type , is_required , supply_default , default_value , enforce_vocabulary , allowed_vocabulary , REQUEST=None ): """ Add a type-specific policy for one of our elements. """ if content_type == '<default>': content_type = None spec = self.getElementSpec( element ) spec.addPolicy( content_type ) policy = spec.getPolicy( content_type ) policy.edit( is_required , supply_default , default_value , enforce_vocabulary , allowed_vocabulary ) if REQUEST is not None: REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/elementPoliciesForm' + '?element=' + element + '&manage_tabs_message=Policy+added.' ) security.declareProtected(ManagePortal, 'removeElementPolicy') def removeElementPolicy( self , element , content_type , REQUEST=None ): """ Remvoe a type-specific policy for one of our elements. """ if content_type == '<default>': content_type = None spec = self.getElementSpec( element ) spec.removePolicy( content_type ) if REQUEST is not None: REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/elementPoliciesForm' + '?element=' + element + '&manage_tabs_message=Policy+removed.' ) security.declareProtected(ManagePortal, 'updateElementPolicy') def updateElementPolicy( self , element , content_type , is_required , supply_default , default_value , enforce_vocabulary , allowed_vocabulary , REQUEST=None ): """ Update a policy for one of our elements ('content_type' will be '<default>' when we edit the default). """ if content_type == '<default>': content_type = None spec = self.getElementSpec( element ) policy = spec.getPolicy( content_type ) policy.edit( is_required , supply_default , default_value , enforce_vocabulary , allowed_vocabulary ) if REQUEST is not None: REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/elementPoliciesForm' + '?element=' + element + '&manage_tabs_message=Policy+updated.' ) # # Element spec manipulation. # security.declareProtected(ManagePortal, 'listElementSpecs') def listElementSpecs( self ): """ Return a list of ElementSpecs representing the elements managed by the tool. """ res = [] for k, v in self.element_specs.items(): res.append((k, v.__of__(self))) return res security.declareProtected(ManagePortal, 'getElementSpec') def getElementSpec( self, element ): """ Return an ElementSpec representing the tool's knowledge of 'element'. """ return self.element_specs[ element ].__of__( self ) security.declareProtected(ManagePortal, 'addElementSpec') def addElementSpec( self, element, is_multi_valued, REQUEST=None ): """ Add 'element' to our list of managed elements. """ # Don't replace. if self.element_specs.has_key( element ): return self.element_specs[ element ] = ElementSpec( is_multi_valued ) if REQUEST is not None: REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/propertiesForm' + '?manage_tabs_message=Element+' + element + '+added.' ) security.declareProtected(ManagePortal, 'removeElementSpec') def removeElementSpec( self, element, REQUEST=None ): """ Remove 'element' from our list of managed elements. """ del self.element_specs[ element ] if REQUEST is not None: REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/propertiesForm' + '?manage_tabs_message=Element+' + element + '+removed.' ) security.declareProtected(ManagePortal, 'listPolicies') def listPolicies( self, typ=None ): """ Show all policies for a given content type, or the default if None. """ result = [] for element, spec in self.listElementSpecs(): result.append( ( element, spec.getPolicy( typ ) ) ) return result # # 'portal_metadata' interface # security.declarePrivate( 'getFullName' ) def getFullName( self, userid ): """ Convert an internal userid to a "formal" name, if possible, perhaps using the 'portal_membership' tool. Used to map userid's for Creator, Contributor DCMI queries. """ return userid # TODO: do lookup here security.declarePublic( 'getPublisher' ) def getPublisher( self ): """ Return the "formal" name of the publisher of the portal. """ return self.publisher security.declarePublic( 'listAllowedVocabulary' ) def listAllowedVocabulary( self, element, content=None, content_type=None ): """ List allowed keywords for a given portal_type, or all possible keywords if none supplied. """ spec = self.getElementSpec( element ) if content_type is None and content: content_type = content.getPortalTypeName() return spec.getPolicy( content_type ).allowedVocabulary() security.declarePublic( 'listAllowedSubjects' ) def listAllowedSubjects( self, content=None, content_type=None ): """ List allowed keywords for a given portal_type, or all possible keywords if none supplied. """ return self.listAllowedVocabulary( 'Subject', content, content_type ) security.declarePublic( 'listAllowedFormats' ) def listAllowedFormats( self, content=None, content_type=None ): """ List the allowed 'Content-type' values for a particular portal_type, or all possible formats if none supplied. """ return self.listAllowedVocabulary( 'Format', content, content_type ) security.declarePublic( 'listAllowedLanguages' ) def listAllowedLanguages( self, content=None, content_type=None ): """ List the allowed language values. """ return self.listAllowedVocabulary( 'Language', content, content_type ) security.declarePublic( 'listAllowedRights' ) def listAllowedRights( self, content=None, content_type=None ): """ List the allowed values for a "Rights" selection list; this gets especially important where syndication is involved. """ return self.listAllowedVocabulary( 'Rights', content, content_type ) security.declareProtected(ModifyPortalContent, 'setInitialMetadata') def setInitialMetadata( self, content ): """ Set initial values for content metatdata, supplying any site-specific defaults. """ for element, policy in self.listPolicies(content.getPortalTypeName()): if not getattr( content, element )(): if policy.supplyDefault(): setter = getattr( content, 'set%s' % element ) setter( policy.defaultValue() ) elif policy.isRequired(): raise MetadataError, \ 'Metadata element %s is required.' % element # TODO: Call initial_values_hook, if present security.declareProtected(View, 'validateMetadata') def validateMetadata( self, content ): """ Enforce portal-wide policies about DCI, e.g., requiring non-empty title/description, etc. Called by the CMF immediately before saving changes to the metadata of an object. """ for element, policy in self.listPolicies(content.getPortalTypeName()): value = getattr( content, element )() if not value and policy.isRequired(): raise MetadataError, \ 'Metadata element %s is required.' % element if value and policy.enforceVocabulary(): values = policy.isMultiValued() and value or [ value ] for value in values: if not value in policy.allowedVocabulary(): raise MetadataError, \ 'Value %s is not in allowed vocabulary for ' \ 'metadata element %s.' % ( value, element )
class AuthenticationTool(BasicUserFolder, Role, ObjectManager, session_manager, file_utils, plugins_tool, PropertyManager): meta_type = METATYPE_AUTHENTICATIONTOOL icon = 'misc_/NaayaCore/AuthenticationTool.gif' manage_options = ( {'label': 'Users', 'action': 'manage_users_html'}, {'label': 'Roles', 'action': 'manage_roles_html'}, {'label': 'Permissions', 'action': 'manage_permissions_html'}, {'label': 'Other sources', 'action': 'manage_sources_html'}, {'label': 'Properties', 'action': 'manage_propertiesForm', 'help': ('OFSP','Properties.stx')}, ) _properties = ( {'id': 'title', 'type': 'string', 'mode': 'w', 'label': 'Title'}, {'id': 'encrypt_passwords', 'type': 'boolean', 'mode': 'w', 'label': 'Encrypt users passwords'}, {'id': 'email_expression', 'type': 'string', 'mode': 'w', 'label': 'E-mail should match this regular expression'}, {'id': 'email_confirmation', 'type': 'boolean', 'mode': 'w', 'label': 'Ask for email confirmation before add user '}, ) security = ClassSecurityInfo() # # Properties # encrypt_passwords = False email_expression = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$' email_confirmation = False def __init__(self, id, title): self.id = id self.title = title self.data = PersistentMapping() Role.__dict__['__init__'](self) plugins_tool.__dict__['__init__'](self) security.declarePrivate('loadDefaultData') def loadDefaultData(self): #load default stuff pass security.declarePrivate('_doAddTempUser') def _doAddTempUser(self, **kwargs): """Generate a confirmation string, add it to temp users list, and return it. """ text = object2string(kwargs) if not hasattr(self, '_temp_users'): self._temp_users = [] if text in self._temp_users: raise Exception, 'User already request access roles.' self._temp_users.append(text) self._p_changed = 1 return text security.declarePrivate('_doAddUser') def _doAddUser(self, name, password, roles, domains, firstname, lastname, email, **kw): """Create a new user. The 'password' will be the original input password, unencrypted. This method is responsible for performing any needed encryption.""" if password is not None and self.encrypt_passwords: password = self._encryptPassword(password) self.data[name] = User(name, password, roles, domains, firstname, lastname, email) self._p_changed = 1 return name security.declarePrivate('_doChangeUser') def _doChangeUser(self, name, password, roles, domains, firstname, lastname, email, lastupdated, **kw): """Modify an existing user. The 'password' will be the original input password, unencrypted. The implementation of this method is responsible for performing any needed encryption.""" user=self.data[name] if password is not None: if self.encrypt_passwords and not self._isPasswordEncrypted(password): password = self._encryptPassword(password) user.__ = password user.roles = roles user.domains = domains user.firstname = firstname user.lastname = lastname user.email = email user.lastupdated = lastupdated self._p_changed = 1 security.declarePublic('changeLastLogin') def changeLastLogin(self, name): user=self.data.get(name, None) if user: user.lastlogin = time.strftime('%d %b %Y %H:%M:%S') self._p_changed = 1 security.declarePublic('changeLastPost') def changeLastPost(self, name): user=self.data.get(name, None) if user: user.lastpost = time.strftime('%d %b %Y %H:%M:%S') self._p_changed = 1 security.declareProtected(manage_users, 'getUserPass') def getUserPass(self): """Return a list of usernames""" temp = {} names=self.data.keys() for name in names: temp[name] = self.getUser(name).__ return temp security.declarePrivate('_doChangeUserRoles') def _doChangeUserRoles(self, name, roles, **kw): """ """ user=self.data[name] user.roles = roles self._p_changed = 1 security.declarePrivate('_doDelUserRoles') def _doDelUserRoles(self, name, **kw): """ """ for user in name: user_obj = self.data[user] user_obj.roles = [] self._p_changed = 1 security.declarePrivate('_doDelUsers') def _doDelUsers(self, names): """Delete one or more users.""" for name in names: del self.data[name] self._p_changed = 1 #zmi actions security.declareProtected(manage_users, 'manage_confirmUser') def manage_confirmUser(self, key='', REQUEST=None): """ Add user from key """ if key not in getattr(self, '_temp_users', []): raise Exception, 'Invalid activation key !' try: res = string2object(key) except InvalidStringError, err: raise Exception, 'Invalid activation key !' else:
class ContentTypeRegistry( SimpleItem ): """ Registry for rules which map PUT args to a CMF Type Object. """ __implements__ = IContentTypeRegistry meta_type = 'Content Type Registry' id = 'content_type_registry' manage_options = ( { 'label' : 'Predicates' , 'action' : 'manage_predicates' } , { 'label' : 'Test' , 'action' : 'manage_testRegistry' } ) + SimpleItem.manage_options security = ClassSecurityInfo() def __init__( self ): self.predicate_ids = () self.predicates = PersistentMapping() # # ZMI # security.declarePublic( 'listPredicateTypes' ) def listPredicateTypes( self ): """ """ return map( lambda x: x[0], _predicate_types ) security.declareProtected( ManagePortal, 'manage_predicates' ) manage_predicates = DTMLFile( 'registryPredList', _dtmldir ) security.declareProtected( ManagePortal, 'doAddPredicate' ) def doAddPredicate( self, predicate_id, predicate_type, REQUEST ): """ """ self.addPredicate( predicate_id, predicate_type ) REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/manage_predicates' + '?manage_tabs_message=Predicate+added.' ) security.declareProtected( ManagePortal, 'doUpdatePredicate' ) def doUpdatePredicate( self , predicate_id , predicate , typeObjectName , REQUEST ): """ """ self.updatePredicate( predicate_id, predicate, typeObjectName ) REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/manage_predicates' + '?manage_tabs_message=Predicate+updated.' ) security.declareProtected( ManagePortal, 'doMovePredicateUp' ) def doMovePredicateUp( self, predicate_id, REQUEST ): """ """ predicate_ids = list( self.predicate_ids ) ndx = predicate_ids.index( predicate_id ) if ndx == 0: msg = "Predicate+already+first." else: self.reorderPredicate( predicate_id, ndx - 1 ) msg = "Predicate+moved." REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/manage_predicates' + '?manage_tabs_message=%s' % msg ) security.declareProtected( ManagePortal, 'doMovePredicateDown' ) def doMovePredicateDown( self, predicate_id, REQUEST ): """ """ predicate_ids = list( self.predicate_ids ) ndx = predicate_ids.index( predicate_id ) if ndx == len( predicate_ids ) - 1: msg = "Predicate+already+last." else: self.reorderPredicate( predicate_id, ndx + 1 ) msg = "Predicate+moved." REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/manage_predicates' + '?manage_tabs_message=%s' % msg ) security.declareProtected( ManagePortal, 'doRemovePredicate' ) def doRemovePredicate( self, predicate_id, REQUEST ): """ """ self.removePredicate( predicate_id ) REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/manage_predicates' + '?manage_tabs_message=Predicate+removed.' ) security.declareProtected( ManagePortal, 'manage_testRegistry' ) manage_testRegistry = DTMLFile( 'registryTest', _dtmldir ) security.declareProtected( ManagePortal, 'doTestRegistry' ) def doTestRegistry( self, name, content_type, body, REQUEST ): """ """ typeName = self.findTypeName( name, content_type, body ) if typeName is None: typeName = '<unknown>' else: types_tool = getToolByName(self, 'portal_types') typeName = types_tool.getTypeInfo(typeName).Title() REQUEST[ 'RESPONSE' ].redirect( self.absolute_url() + '/manage_testRegistry' + '?testResults=Type:+%s' % urllib.quote( typeName ) ) # # Predicate manipulation # security.declarePublic( 'getPredicate' ) def getPredicate( self, predicate_id ): """ Find the predicate whose id is 'id'; return the predicate object, if found, or else None. """ return self.predicates.get( predicate_id, ( None, None ) )[0] security.declarePublic( 'listPredicates' ) def listPredicates( self ): """ Return a sequence of tuples, '( id, ( predicate, typeObjectName ) )' for all predicates in the registry """ result = [] for predicate_id in self.predicate_ids: result.append( ( predicate_id, self.predicates[ predicate_id ] ) ) return tuple( result ) security.declarePublic( 'getTypeObjectName' ) def getTypeObjectName( self, predicate_id ): """ Find the predicate whose id is 'id'; return the name of the type object, if found, or else None. """ return self.predicates.get( predicate_id, ( None, None ) )[1] security.declareProtected( ManagePortal, 'addPredicate' ) def addPredicate( self, predicate_id, predicate_type ): """ Add a predicate to this element of type 'typ' to the registry. """ if predicate_id in self.predicate_ids: raise ValueError, "Existing predicate: %s" % predicate_id klass = None for key, value in _predicate_types: if key == predicate_type: klass = value if klass is None: raise ValueError, "Unknown predicate type: %s" % predicate_type self.predicates[ predicate_id ] = ( klass( predicate_id ), None ) self.predicate_ids = self.predicate_ids + ( predicate_id, ) security.declareProtected( ManagePortal, 'updatePredicate' ) def updatePredicate( self, predicate_id, predicate, typeObjectName ): """ Update a predicate in this element. """ if not predicate_id in self.predicate_ids: raise ValueError, "Unknown predicate: %s" % predicate_id predObj = self.predicates[ predicate_id ][0] mapply( predObj.edit, (), predicate.__dict__ ) self.assignTypeName( predicate_id, typeObjectName ) security.declareProtected( ManagePortal, 'removePredicate' ) def removePredicate( self, predicate_id ): """ Remove a predicate from the registry. """ del self.predicates[ predicate_id ] idlist = list( self.predicate_ids ) ndx = idlist.index( predicate_id ) idlist = idlist[ :ndx ] + idlist[ ndx+1: ] self.predicate_ids = tuple( idlist ) security.declareProtected( ManagePortal, 'reorderPredicate' ) def reorderPredicate( self, predicate_id, newIndex ): """ Move a given predicate to a new location in the list. """ idlist = list( self.predicate_ids ) ndx = idlist.index( predicate_id ) pred = idlist[ ndx ] idlist = idlist[ :ndx ] + idlist[ ndx+1: ] idlist.insert( newIndex, pred ) self.predicate_ids = tuple( idlist ) security.declareProtected( ManagePortal, 'assignTypeName' ) def assignTypeName( self, predicate_id, typeObjectName ): """ Bind the given predicate to a particular type object. """ pred, oldTypeObjName = self.predicates[ predicate_id ] self.predicates[ predicate_id ] = ( pred, typeObjectName ) # # ContentTypeRegistry interface # def findTypeName( self, name, typ, body ): """ Perform a lookup over a collection of rules, returning the the name of the Type object corresponding to name/typ/body. Return None if no match found. """ for predicate_id in self.predicate_ids: pred, typeObjectName = self.predicates[ predicate_id ] if pred( name, typ, body ): return typeObjectName return None
class MembershipTool(UniqueObject, Folder, ActionProviderBase): """ This tool accesses member data through an acl_users object. It can be replaced with something that accesses member data in a different way. """ implements(IMembershipTool) __implements__ = (z2IMembershipTool, ActionProviderBase.__implements__) id = 'portal_membership' meta_type = 'CMF Membership Tool' memberareaCreationFlag = 1 security = ClassSecurityInfo() manage_options=( ({ 'label' : 'Configuration' , 'action' : 'manage_mapRoles' },) + ActionProviderBase.manage_options + ( { 'label' : 'Overview' , 'action' : 'manage_overview' }, ) + Folder.manage_options) # # ZMI methods # security.declareProtected(ManagePortal, 'manage_overview') manage_overview = DTMLFile( 'explainMembershipTool', _dtmldir ) # # 'portal_membership' interface methods # security.declareProtected(ManagePortal, 'manage_mapRoles') manage_mapRoles = DTMLFile('membershipRolemapping', _dtmldir ) security.declareProtected(SetOwnPassword, 'setPassword') def setPassword(self, password, domains=None): '''Allows the authenticated member to set his/her own password. ''' registration = getToolByName(self, 'portal_registration', None) if not self.isAnonymousUser(): member = self.getAuthenticatedMember() if registration: failMessage = registration.testPasswordValidity(password) if failMessage is not None: raise BadRequest(failMessage) member.setSecurityProfile(password=password, domains=domains) else: raise BadRequest('Not logged in.') security.declarePublic('getAuthenticatedMember') def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. ''' u = _getAuthenticatedUser(self) if u is None: u = nobody return self.wrapUser(u) security.declarePrivate('wrapUser') def wrapUser(self, u, wrap_anon=0): """ Set up the correct acquisition wrappers for a user object. Provides an opportunity for a portal_memberdata tool to retrieve and store member data independently of the user object. """ b = getattr(u, 'aq_base', None) if b is None: # u isn't wrapped at all. Wrap it in self.acl_users. b = u u = u.__of__(self.acl_users) if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'): # This user is either not recognized by acl_users or it is # already registered with something that implements the # member data tool at least partially. return u # Apply any role mapping if we have it if hasattr(self, 'role_map'): for portal_role in self.role_map.keys(): if (self.role_map.get(portal_role) in u.roles and portal_role not in u.roles): u.roles.append(portal_role) mdtool = getToolByName(self, 'portal_memberdata', None) if mdtool is not None: try: u = mdtool.wrapUser(u) except ConflictError: raise except: logging.exception('CMFCore.MembershipTool', 'Error during wrapUser') return u security.declareProtected(ManagePortal, 'getPortalRoles') def getPortalRoles(self): """ Return all local roles defined by the portal itself, which means roles that are useful and understood by the portal object """ parent = self.aq_inner.aq_parent roles = list( parent.userdefined_roles() ) # This is *not* a local role in the portal but used by it roles.append('Manager') roles.append('Owner') return roles security.declareProtected(ManagePortal, 'setRoleMapping') def setRoleMapping(self, portal_role, userfolder_role): """ set the mapping of roles between roles understood by the portal and roles coming from outside user sources """ if not hasattr(self, 'role_map'): self.role_map = PersistentMapping() if len(userfolder_role) < 1: del self.role_map[portal_role] else: self.role_map[portal_role] = userfolder_role return MessageDialog( title ='Mapping updated', message='The Role mappings have been updated', action ='manage_mapRoles') security.declareProtected(ManagePortal, 'getMappedRole') def getMappedRole(self, portal_role): """ returns a role name if the portal role is mapped to something else or an empty string if it is not """ if hasattr(self, 'role_map'): return self.role_map.get(portal_role, '') else: return '' security.declarePublic('getMembersFolder') def getMembersFolder(self): """ Get the members folder object. """ parent = aq_parent( aq_inner(self) ) members = getattr(parent, 'Members', None) return members security.declareProtected(ManagePortal, 'getMemberareaCreationFlag') def getMemberareaCreationFlag(self): """ Returns the flag indicating whether the membership tool will create a member area if an authenticated user from an underlying user folder logs in first without going through the join process """ return self.memberareaCreationFlag security.declareProtected(ManagePortal, 'setMemberareaCreationFlag') def setMemberareaCreationFlag(self): """ sets the flag indicating whether the membership tool will create a member area if an authenticated user from an underlying user folder logs in first without going through the join process """ if not hasattr(self, 'memberareaCreationFlag'): self.memberareaCreationFlag = 0 if self.memberareaCreationFlag == 0: self.memberareaCreationFlag = 1 else: self.memberareaCreationFlag = 0 return MessageDialog( title ='Member area creation flag changed', message='Member area creation flag has been updated', action ='manage_mapRoles') security.declarePublic('createMemberArea') def createMemberArea(self, member_id=''): """ Create a member area for 'member_id' or authenticated user. """ if not self.getMemberareaCreationFlag(): return None members = self.getMembersFolder() if not members: return None if self.isAnonymousUser(): return None # Note: We can't use getAuthenticatedMember() and getMemberById() # because they might be wrapped by MemberDataTool. user = _getAuthenticatedUser(self) user_id = user.getId() if member_id in ('', user_id): member = user member_id = user_id else: if _checkPermission(ManageUsers, self): member = self.acl_users.getUserById(member_id, None) if member: member = member.__of__(self.acl_users) else: raise ValueError('Member %s does not exist' % member_id) else: return None if hasattr( aq_base(members), member_id ): return None else: f_title = "%s's Home" % member_id members.manage_addPortalFolder( id=member_id, title=f_title ) f=getattr(members, member_id) f.manage_permission(View, ['Owner','Manager','Reviewer'], 0) f.manage_permission(AccessContentsInformation, ['Owner','Manager','Reviewer'], 0) # Grant Ownership and Owner role to Member f.changeOwnership(member) f.__ac_local_roles__ = None f.manage_setLocalRoles(member_id, ['Owner']) return f security.declarePublic('createMemberarea') createMemberarea = createMemberArea security.declareProtected(ManageUsers, 'deleteMemberArea') def deleteMemberArea(self, member_id): """ Delete member area of member specified by member_id. """ members = self.getMembersFolder() if not members: return 0 if hasattr( aq_base(members), member_id ): members.manage_delObjects(member_id) return 1 else: return 0 security.declarePublic('isAnonymousUser') def isAnonymousUser(self): ''' Returns 1 if the user is not logged in. ''' u = _getAuthenticatedUser(self) if u is None or u.getUserName() == 'Anonymous User': return 1 return 0 security.declarePublic('checkPermission') def checkPermission(self, permissionName, object, subobjectName=None): ''' Checks whether the current user has the given permission on the given object or subobject. ''' if subobjectName is not None: object = getattr(object, subobjectName) return _checkPermission(permissionName, object) security.declarePublic('credentialsChanged') def credentialsChanged(self, password): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' if not self.isAnonymousUser(): acl_users = self.acl_users user = _getAuthenticatedUser(self) name = user.getUserName() # this really does need to be the user name, and not the user id, # because we're dealing with authentication credentials if hasattr(acl_users.aq_base, 'credentialsChanged'): # Use an interface provided by LoginManager. acl_users.credentialsChanged(user, name, password) else: req = self.REQUEST p = getattr(req, '_credentials_changed_path', None) if p is not None: # Use an interface provided by CookieCrumbler. change = self.restrictedTraverse(p) change(user, name, password) security.declareProtected(ManageUsers, 'getMemberById') def getMemberById(self, id): ''' Returns the given member. ''' user = self._huntUser(id, self) if user is not None: user = self.wrapUser(user) return user def _huntUser(self, username, context): """Find user in the hierarchy starting from bottom level 'start'. """ uf = context.acl_users while uf is not None: user = uf.getUserById(username) if user is not None: return user container = aq_parent(aq_inner(uf)) parent = aq_parent(aq_inner(container)) uf = getattr(parent, 'acl_users', None) return None def __getPUS(self): # Gets something we can call getUsers() and getUserNames() on. acl_users = self.acl_users if hasattr(acl_users, 'getUsers'): return acl_users else: # This hack works around the absence of getUsers() in LoginManager. # Gets the PersistentUserSource object that stores our users for us in acl_users.UserSourcesGroup.objectValues(): if us.meta_type == 'Persistent User Source': return us.__of__(acl_users) security.declareProtected(ManageUsers, 'listMemberIds') def listMemberIds(self): '''Lists the ids of all members. This may eventually be replaced with a set of methods for querying pieces of the list rather than the entire list at once. ''' user_folder = self.__getPUS() return [ x.getId() for x in user_folder.getUsers() ] security.declareProtected(ManageUsers, 'listMembers') def listMembers(self): '''Gets the list of all members. ''' return map(self.wrapUser, self.__getPUS().getUsers()) security.declareProtected(ListPortalMembers, 'searchMembers') def searchMembers( self, search_param, search_term ): """ Search the membership """ md = getToolByName( self, 'portal_memberdata' ) return md.searchMemberData( search_param, search_term ) security.declareProtected(View, 'getCandidateLocalRoles') def getCandidateLocalRoles(self, obj): """ What local roles can I assign? """ member = self.getAuthenticatedMember() member_roles = member.getRolesInContext(obj) if _checkPermission(ManageUsers, obj): local_roles = self.getPortalRoles() if 'Manager' not in member_roles: local_roles.remove('Manager') else: local_roles = [ role for role in member_roles if role not in ('Member', 'Authenticated') ] local_roles.sort() return tuple(local_roles) security.declareProtected(View, 'setLocalRoles') def setLocalRoles(self, obj, member_ids, member_role, reindex=1): """ Add local roles on an item. """ if ( _checkPermission(ChangeLocalRoles, obj) and member_role in self.getCandidateLocalRoles(obj) ): for member_id in member_ids: roles = list(obj.get_local_roles_for_userid( userid=member_id )) if member_role not in roles: roles.append( member_role ) obj.manage_setLocalRoles( member_id, roles ) if reindex: # It is assumed that all objects have the method # reindexObjectSecurity, which is in CMFCatalogAware and # thus PortalContent and PortalFolder. obj.reindexObjectSecurity() security.declareProtected(View, 'deleteLocalRoles') def deleteLocalRoles(self, obj, member_ids, reindex=1, recursive=0): """ Delete local roles of specified members. """ if _checkPermission(ChangeLocalRoles, obj): for member_id in member_ids: if obj.get_local_roles_for_userid(userid=member_id): obj.manage_delLocalRoles(userids=member_ids) break if recursive and hasattr( aq_base(obj), 'contentValues' ): for subobj in obj.contentValues(): self.deleteLocalRoles(subobj, member_ids, 0, 1) if reindex: # reindexObjectSecurity is always recursive obj.reindexObjectSecurity() security.declarePrivate('addMember') def addMember(self, id, password, roles, domains, properties=None): '''Adds a new member to the user folder. Security checks will have already been performed. Called by portal_registration. ''' acl_users = self.acl_users if hasattr(acl_users, '_doAddUser'): acl_users._doAddUser(id, password, roles, domains) else: # The acl_users folder is a LoginManager. Search for a UserSource # with the needed support. for source in acl_users.UserSourcesGroup.objectValues(): if hasattr(source, 'addUser'): source.__of__(self).addUser(id, password, roles, domains) raise "Can't add Member", "No supported UserSources" if properties is not None: member = self.getMemberById(id) member.setMemberProperties(properties) security.declareProtected(ManageUsers, 'deleteMembers') def deleteMembers(self, member_ids, delete_memberareas=1, delete_localroles=1): """ Delete members specified by member_ids. """ # Delete members in acl_users. acl_users = self.acl_users if _checkPermission(ManageUsers, acl_users): if isinstance(member_ids, basestring): member_ids = (member_ids,) member_ids = list(member_ids) for member_id in member_ids[:]: if not acl_users.getUserById(member_id, None): member_ids.remove(member_id) try: acl_users.userFolderDelUsers(member_ids) except (NotImplementedError, 'NotImplemented'): raise NotImplementedError('The underlying User Folder ' 'doesn\'t support deleting members.') else: raise AccessControl_Unauthorized('You need the \'Manage users\' ' 'permission for the underlying User Folder.') # Delete member data in portal_memberdata. mdtool = getToolByName(self, 'portal_memberdata', None) if mdtool is not None: for member_id in member_ids: mdtool.deleteMemberData(member_id) # Delete members' home folders including all content items. if delete_memberareas: for member_id in member_ids: self.deleteMemberArea(member_id) # Delete members' local roles. if delete_localroles: utool = getToolByName(self, 'portal_url', None) self.deleteLocalRoles( utool.getPortalObject(), member_ids, reindex=1, recursive=1 ) return tuple(member_ids) security.declarePublic('getHomeFolder') def getHomeFolder(self, id=None, verifyPermission=0): """Returns a member's home folder object or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None security.declarePublic('getHomeUrl') def getHomeUrl(self, id=None, verifyPermission=0): """Returns the URL to a member's home folder or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None
def __init__( self ): self.predicate_ids = () self.predicates = PersistentMapping()
class UserFolder(BasicUserFolder): """Standard UserFolder object A UserFolder holds User objects which contain information about users including name, password domain, and roles. UserFolders function chiefly to control access by authenticating users and binding them to a collection of roles.""" meta_type='User Folder' id ='acl_users' title ='User Folder' icon ='p_/UserFolder' def __init__(self): self.data=PersistentMapping() def getUserNames(self): """Return a list of usernames""" names=self.data.keys() names.sort() return names def getUsers(self): """Return a list of user objects""" data=self.data names=data.keys() names.sort() users=[] f=users.append for n in names: f(data[n]) return users def getUser(self, name): """Return the named user object or None""" return self.data.get(name, None) def _doAddUser(self, name, password, roles, domains, **kw): """Create a new user""" if password is not None and self.encrypt_passwords: password = self._encryptPassword(password) self.data[name]=User(name,password,roles,domains) def _doChangeUser(self, name, password, roles, domains, **kw): user=self.data[name] if password is not None: if self.encrypt_passwords and not self._isPasswordEncrypted(pw): password = self._encryptPassword(password) user.__=password user.roles=roles user.domains=domains def _doDelUsers(self, names): for name in names: del self.data[name] def _createInitialUser(self): """ If there are no users or only one user in this user folder, populates from the 'inituser' file in INSTANCE_HOME. We have to do this even when there is already a user just in case the initial user ignored the setup messages. We don't do it for more than one user to avoid abuse of this mechanism. Called only by OFS.Application.initialize(). """ if len(self.data) <= 1: info = readUserAccessFile('inituser') if info: name, password, domains, remote_user_mode = info self._doDelUsers(self.getUserNames()) self._doAddUser(name, password, ('Manager',), domains) try: os.remove(os.path.join(INSTANCE_HOME, 'inituser')) except: pass
class MembershipTool (UniqueObject, SimpleItem, ActionProviderBase): # This tool accesses member data through an acl_users object. # It can be replaced with something that accesses member data in # a different way. id = 'portal_membership' meta_type = 'CMF Membership Tool' _actions = [] security = ClassSecurityInfo() memberareaCreationFlag = 1 manage_options=( ({ 'label' : 'Configuration' , 'action' : 'manage_mapRoles' },) + ActionProviderBase.manage_options + ( { 'label' : 'Overview' , 'action' : 'manage_overview' }, ) + SimpleItem.manage_options) # # ZMI methods # security.declareProtected( CMFCorePermissions.ManagePortal , 'manage_overview' ) manage_overview = DTMLFile( 'explainMembershipTool', _dtmldir ) # # 'portal_membership' interface methods # security.declareProtected(ManagePortal, 'manage_mapRoles') manage_mapRoles = DTMLFile('membershipRolemapping', _dtmldir ) security.declareProtected(CMFCorePermissions.SetOwnPassword, 'setPassword') def setPassword(self, password, domains=None): '''Allows the authenticated member to set his/her own password. ''' registration = getToolByName(self, 'portal_registration', None) if not self.isAnonymousUser(): member = self.getAuthenticatedMember() if registration: failMessage = registration.testPasswordValidity(password) if failMessage is not None: raise 'Bad Request', failMessage member.setSecurityProfile(password=password, domains=domains) else: raise 'Bad Request', 'Not logged in.' security.declarePublic('getAuthenticatedMember') def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. ''' u = _getAuthenticatedUser(self) if u is None: u = nobody return self.wrapUser(u) security.declarePrivate('wrapUser') def wrapUser(self, u, wrap_anon=0): ''' Sets up the correct acquisition wrappers for a user object and provides an opportunity for a portal_memberdata tool to retrieve and store member data independently of the user object. ''' b = getattr(u, 'aq_base', None) if b is None: # u isn't wrapped at all. Wrap it in self.acl_users. b = u u = u.__of__(self.acl_users) if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'): # This user is either not recognized by acl_users or it is # already registered with something that implements the # member data tool at least partially. return u parent = self.aq_inner.aq_parent base = getattr(parent, 'aq_base', None) if hasattr(base, 'portal_memberdata'): # Apply any role mapping if we have it if hasattr(self, 'role_map'): for portal_role in self.role_map.keys(): if (self.role_map.get(portal_role) in u.roles and portal_role not in u.roles): u.roles.append(portal_role) # Get portal_memberdata to do the wrapping. md = getToolByName(parent, 'portal_memberdata') try: portal_user = md.wrapUser(u) # Check for the member area creation flag and # take appropriate (non-) action if getattr(self, 'memberareaCreationFlag', 0) != 0: if self.getHomeUrl(portal_user.getId()) is None: self.createMemberarea(portal_user.getId()) return portal_user except ConflictError: raise except: from zLOG import LOG, ERROR import sys type,value,tb = sys.exc_info() try: LOG('CMFCore.MembershipTool', ERROR, 'Error during wrapUser:'******'getPortalRoles') def getPortalRoles(self): """ Return all local roles defined by the portal itself, which means roles that are useful and understood by the portal object """ parent = self.aq_inner.aq_parent roles = list(parent.__ac_roles__) # This is *not* a local role in the portal but used by it roles.append('Manager') roles.append('Owner') return roles security.declareProtected(ManagePortal, 'setRoleMapping') def setRoleMapping(self, portal_role, userfolder_role): """ set the mapping of roles between roles understood by the portal and roles coming from outside user sources """ if not hasattr(self, 'role_map'): self.role_map = PersistentMapping() if len(userfolder_role) < 1: del self.role_map[portal_role] else: self.role_map[portal_role] = userfolder_role return MessageDialog( title ='Mapping updated', message='The Role mappings have been updated', action ='manage_mapRoles') security.declareProtected(ManagePortal, 'getMappedRole') def getMappedRole(self, portal_role): """ returns a role name if the portal role is mapped to something else or an empty string if it is not """ if hasattr(self, 'role_map'): return self.role_map.get(portal_role, '') else: return '' security.declareProtected(ManagePortal, 'getMemberareaCreationFlag') def getMemberareaCreationFlag(self): """ Returns the flag indicating whether the membership tool will create a member area if an authenticated user from an underlying user folder logs in first without going through the join process """ return self.memberareaCreationFlag security.declareProtected(ManagePortal, 'setMemberareaCreationFlag') def setMemberareaCreationFlag(self): """ sets the flag indicating whether the membership tool will create a member area if an authenticated user from an underlying user folder logs in first without going through the join process """ if not hasattr(self, 'memberareaCreationFlag'): self.memberareaCreationFlag = 0 if self.memberareaCreationFlag == 0: self.memberareaCreationFlag = 1 else: self.memberareaCreationFlag = 0 return MessageDialog( title ='Member area creation flag changed', message='Member area creation flag has been updated', action ='manage_mapRoles') security.declareProtected(ManagePortal, 'createMemberarea') def createMemberarea(self, member_id): """ create a member area """ parent = self.aq_inner.aq_parent members = getattr(parent, 'Members', None) user = self.acl_users.getUser( member_id ).__of__( self.acl_users ) if members is not None and user is not None: f_title = "%s's Home" % member_id members.manage_addPortalFolder( id=member_id, title=f_title ) f=getattr(members, member_id) f.manage_permission(CMFCorePermissions.View, ['Owner','Manager','Reviewer'], 0) f.manage_permission(CMFCorePermissions.AccessContentsInformation, ['Owner','Manager','Reviewer'], 0) # Grant ownership to Member try: f.changeOwnership(user) except AttributeError: pass # Zope 2.1.x compatibility f.manage_setLocalRoles(member_id, ['Owner']) security.declarePublic('isAnonymousUser') def isAnonymousUser(self): ''' Returns 1 if the user is not logged in. ''' u = _getAuthenticatedUser(self) if u is None or u.getUserName() == 'Anonymous User': return 1 return 0 security.declarePublic('checkPermission') def checkPermission(self, permissionName, object, subobjectName=None): ''' Checks whether the current user has the given permission on the given object or subobject. ''' if subobjectName is not None: object = getattr(object, subobjectName) return _checkPermission(permissionName, object) security.declarePublic('credentialsChanged') def credentialsChanged(self, password): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' if not self.isAnonymousUser(): acl_users = self.acl_users user = _getAuthenticatedUser(self) id = user.getUserName() if hasattr(acl_users.aq_base, 'credentialsChanged'): # Use an interface provided by LoginManager. acl_users.credentialsChanged(user, id, password) else: req = self.REQUEST p = getattr(req, '_credentials_changed_path', None) if p is not None: # Use an interface provided by CookieCrumbler. change = self.restrictedTraverse(p) change(user, id, password) security.declareProtected(ManagePortal, 'getMemberById') def getMemberById(self, id): ''' Returns the given member. ''' u = self.acl_users.getUser(id) if u is not None: u = self.wrapUser(u) return u def __getPUS(self): # Gets something we can call getUsers() and getUserNames() on. acl_users = self.acl_users if hasattr(acl_users, 'getUsers'): return acl_users else: # This hack works around the absence of getUsers() in LoginManager. # Gets the PersistentUserSource object that stores our users for us in acl_users.UserSourcesGroup.objectValues(): if us.meta_type == 'Persistent User Source': return us.__of__(acl_users) security.declareProtected(ManagePortal, 'listMemberIds') def listMemberIds(self): '''Lists the ids of all members. This may eventually be replaced with a set of methods for querying pieces of the list rather than the entire list at once. ''' return self.__getPUS().getUserNames() security.declareProtected(ManagePortal, 'listMembers') def listMembers(self): '''Gets the list of all members. ''' return map(self.wrapUser, self.__getPUS().getUsers()) security.declareProtected( CMFCorePermissions.ListPortalMembers , 'searchMembers') def searchMembers( self, search_param, search_term ): """ Search the membership """ md = getToolByName( self, 'portal_memberdata' ) return md.searchMemberDataContents( search_param, search_term ) security.declareProtected(CMFCorePermissions.View, 'getCandidateLocalRoles') def getCandidateLocalRoles( self, obj ): """ What local roles can I assign? """ member = self.getAuthenticatedMember() if 'Manager' in member.getRoles(): return self.getPortalRoles() else: member_roles = list( member.getRolesInContext( obj ) ) del member_roles[member_roles.index( 'Member')] return tuple( member_roles ) security.declareProtected(CMFCorePermissions.View, 'setLocalRoles') def setLocalRoles( self, obj, member_ids, member_role, reindex=1 ): """ Set local roles on an item """ member = self.getAuthenticatedMember() my_roles = member.getRolesInContext( obj ) if 'Manager' in my_roles or member_role in my_roles: for member_id in member_ids: roles = list(obj.get_local_roles_for_userid( userid=member_id )) if member_role not in roles: roles.append( member_role ) obj.manage_setLocalRoles( member_id, roles ) if reindex: # It is assumed that all objects have the method # reindexObjectSecurity, which is in CMFCatalogAware and # thus PortalContent and PortalFolder. obj.reindexObjectSecurity() security.declareProtected(CMFCorePermissions.View, 'deleteLocalRoles') def deleteLocalRoles( self, obj, member_ids, reindex=1 ): """ Delete local roles for members member_ids """ member = self.getAuthenticatedMember() my_roles = member.getRolesInContext( obj ) if 'Manager' in my_roles or 'Owner' in my_roles: obj.manage_delLocalRoles( userids=member_ids ) if reindex: obj.reindexObjectSecurity() security.declarePrivate('addMember') def addMember(self, id, password, roles, domains, properties=None): '''Adds a new member to the user folder. Security checks will have already been performed. Called by portal_registration. ''' acl_users = self.acl_users if hasattr(acl_users, '_addUser'): acl_users._addUser(id, password, password, roles, domains) else: # The acl_users folder is a LoginManager. Search for a UserSource # with the needed support. for source in acl_users.UserSourcesGroup.objectValues(): if hasattr(source, 'addUser'): source.__of__(self).addUser(id, password, roles, domains) raise "Can't add Member", "No supported UserSources" if properties is not None: membership = getToolByName(self, 'portal_membership') member = membership.getMemberById(id) member.setMemberProperties(properties) security.declarePrivate('listActions') def listActions(self, info=None): return None security.declarePublic('getHomeFolder') def getHomeFolder(self, id=None, verifyPermission=0): """Returns a member's home folder object or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None security.declarePublic('getHomeUrl') def getHomeUrl(self, id=None, verifyPermission=0): """Returns the URL to a member's home folder or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None
class DiscussionItemContainer( Persistent, Implicit, Traversable ): """ Store DiscussionItem objects. Discussable content that has DiscussionItems associated with it will have an instance of DiscussionItemContainer injected into it to hold the discussion threads. """ __implements__ = Discussable # for the security machinery to allow traversal #__roles__ = None security = ClassSecurityInfo() def __init__(self): self.id = 'talkback' self._container = PersistentMapping() security.declareProtected(View, 'getId') def getId( self ): return self.id security.declareProtected(View, 'getReply') def getReply( self, reply_id ): """ Return a discussion item, given its ID; raise KeyError if not found. """ return self._container.get( reply_id ).__of__(self) # Is this right? security.declareProtected(View, '__bobo_traverse__') def __bobo_traverse__(self, REQUEST, name): """ This will make this container traversable """ target = getattr(self, name, None) if target is not None: return target else: try: return self.getReply(name) except: parent = aq_parent( aq_inner( self ) ) if parent.getId() == name: return parent else: REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, '')) security.declarePrivate('manage_afterAdd') def manage_afterAdd(self, item, container): """ We have juste been added or moved. Add the contained items to the catalog. """ if aq_base(container) is not aq_base(self): for obj in self.objectValues(): obj.__of__(self).manage_afterAdd(item, container) security.declarePrivate('manage_afterClone') def manage_afterClone(self, item): """ We have just been cloned. Notify the workflow about the contained items. """ for obj in self.objectValues(): obj.__of__(self).manage_afterClone(item) security.declarePrivate( 'manage_beforeDelete' ) def manage_beforeDelete(self, item, container): """ Remove the contained items from the catalog. """ if aq_base(container) is not aq_base(self): for obj in self.objectValues(): obj.__of__( self ).manage_beforeDelete( item, container ) # # OFS.ObjectManager query interface. # security.declareProtected(AccessContentsInformation, 'objectIds') def objectIds( self, spec=None ): """ Return a list of the ids of our DiscussionItems. """ if spec and spec is not DiscussionItem.meta_type: return [] return self._container.keys() security.declareProtected(AccessContentsInformation, 'objectItems') def objectItems(self, spec=None): """ Return a list of (id, subobject) tuples for our DiscussionItems. """ r=[] a=r.append g=self._container.get for id in self.objectIds(spec): a( (id, g( id ) ) ) return r security.declareProtected(AccessContentsInformation, 'objectValues') def objectValues(self): """ Return a list of our DiscussionItems. """ return self._container.values() # # Discussable interface # security.declareProtected(ReplyToItem, 'createReply') def createReply( self, title, text, Creator=None, text_format='structured-text' ): """ Create a reply in the proper place """ container = self._container id = int(DateTime().timeTime()) while self._container.get( str(id), None ) is not None: id = id + 1 id = str( id ) item = DiscussionItem( id, title=title, description=title ) item._edit( text_format=text_format, text=text ) item.__of__(self).addCreator(Creator) item.__of__(self).indexObject() item.setReplyTo( self._getDiscussable() ) item.__of__(self).notifyWorkflowCreated() self._container[ id ] = item return id security.declareProtected(ManagePortal, 'deleteReply') def deleteReply( self, reply_id ): """ Remove a reply from this container """ if self._container.has_key( reply_id ): reply = self._container.get( reply_id ).__of__( self ) my_replies = reply.talkback.getReplies() for my_reply in my_replies: my_reply_id = my_reply.getId() if hasattr( my_reply, 'unindexObject' ): my_reply.unindexObject() del self._container[my_reply_id] if hasattr( reply, 'unindexObject' ): reply.unindexObject() del self._container[reply_id] security.declareProtected(View, 'hasReplies') def hasReplies( self, content_obj ): """ Test to see if there are any dicussion items """ outer = self._getDiscussable( outer=1 ) if content_obj == outer: return not not len( self._container ) else: return not not len( content_obj.talkback._getReplyResults() ) security.declareProtected(View, 'replyCount') def replyCount( self, content_obj ): """ How many replies do i have? """ outer = self._getDiscussable( outer=1 ) if content_obj == outer: return len( self._container ) else: replies = content_obj.talkback.getReplies() return self._repcount( replies ) security.declarePrivate('_repcount') def _repcount( self, replies ): """ counts the total number of replies by recursing thru the various levels """ count = 0 for reply in replies: count = count + 1 #if there is at least one reply to this reply replies = reply.talkback.getReplies() if replies: count = count + self._repcount( replies ) return count security.declareProtected(View, 'getReplies') def getReplies( self ): """ Return a sequence of the DiscussionResponse objects which are associated with this Discussable """ objects = [] a = objects.append result_ids = self._getReplyResults() for id in result_ids: a( self._container.get( id ).__of__( self ) ) return objects security.declareProtected(View, 'quotedContents') def quotedContents(self): """ Return this object's contents in a form suitable for inclusion as a quote in a response. """ return "" # # Utility methods # security.declarePrivate( '_getReplyParent' ) def _getReplyParent( self, in_reply_to ): """ Return the object indicated by the 'in_reply_to', where 'None' represents the "outer" content object. """ outer = self._getDiscussable( outer=1 ) if in_reply_to is None: return outer parent = self._container[ in_reply_to ].__of__( aq_inner( self ) ) return parent.__of__( outer ) security.declarePrivate( '_getDiscussable' ) def _getDiscussable( self, outer=0 ): """ """ tb = outer and aq_inner( self ) or self return getattr( tb, 'aq_parent', None ) security.declarePrivate( '_getReplyResults' ) def _getReplyResults( self ): """ Get a list of ids of DiscussionItems which are replies to our Discussable. """ discussable = self._getDiscussable() outer = self._getDiscussable( outer=1 ) if discussable == outer: in_reply_to = None else: in_reply_to = discussable.getId() result = [] a = result.append for key, value in self._container.items(): if value.in_reply_to == in_reply_to: a( ( key, value ) ) result.sort( lambda a, b: cmp(a[1].creation_date, b[1].creation_date) ) return [ x[0] for x in result ]
class MembershipTool (UniqueObject, SimpleItem): # This tool accesses member data through an acl_users object. # It can be replaced with something that accesses member data in # a different way. id = 'portal_membership' meta_type = 'CMF Membership Tool' security = ClassSecurityInfo() manage_options=( { 'label' : 'Overview' , 'action' : 'manage_overview' } , { 'label' : 'Role Mapping' , 'action' : 'manage_mapRoles' } ) + SimpleItem.manage_options # # ZMI methods # security.declareProtected( CMFCorePermissions.ManagePortal , 'manage_overview' ) manage_overview = DTMLFile( 'explainMembershipTool', _dtmldir ) # # 'portal_membership' interface methods # security.declareProtected(ManagePortal, 'manage_mapRoles') manage_mapRoles = DTMLFile('dtml/membershipRolemapping', _dtmldir ) security.declarePublic('getAuthenticatedMember') def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. ''' u = _getAuthenticatedUser(self) if u is None: u = nobody return self.wrapUser(u) security.declarePrivate('wrapUser') def wrapUser(self, u, wrap_anon=0): ''' Sets up the correct acquisition wrappers for a user object and provides an opportunity for a portal_memberdata tool to retrieve and store member data independently of the user object. ''' b = getattr(u, 'aq_base', None) if b is None: # u isn't wrapped at all. Wrap it in self.acl_users. b = u u = u.__of__(self.acl_users) if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'): # This user is either not recognized by acl_users or it is # already registered with something that implements the # member data tool at least partially. return u parent = self.aq_inner.aq_parent base = getattr(parent, 'aq_base', None) if hasattr(base, 'portal_memberdata'): # Apply any role mapping if we have it if hasattr(self, 'role_map'): for portal_role in self.role_map.keys(): if (self.role_map.get(portal_role) in u.roles and portal_role not in u.roles): u.roles.append(portal_role) # Get portal_memberdata to do the wrapping. md = getToolByName(parent, 'portal_memberdata') try: portal_user = md.wrapUser(u) # Check for the member area creation flag and # take appropriate (non-) action if getattr(self, 'memberareaCreationFlag', 0) != 0: if self.getHomeUrl(portal_user.getId()) is None: self.createMemberarea(portal_user.getId()) return portal_user except: # DEBUGGING CODE import traceback traceback.print_exc() pass # Failed. return u security.declareProtected(ManagePortal, 'getPortalRoles') def getPortalRoles(self): """ Return all local roles defined by the portal itself, which means roles that are useful and understood by the portal object """ parent = self.aq_inner.aq_parent roles = list(parent.__ac_roles__) # This is *not* a local role in the portal but used by it roles.append('Manager') return roles security.declareProtected(ManagePortal, 'setRoleMapping') def setRoleMapping(self, portal_role, userfolder_role): """ set the mapping of roles between roles understood by the portal and roles coming from outside user sources """ if not hasattr(self, 'role_map'): self.role_map = PersistentMapping() if len(userfolder_role) < 1: del self.role_map[portal_role] else: self.role_map[portal_role] = userfolder_role return MessageDialog( title ='Mapping updated', message='The Role mappings have been updated', action ='manage_mapRoles') security.declareProtected(ManagePortal, 'getMappedRole') def getMappedRole(self, portal_role): """ returns a role name if the portal role is mapped to something else or an empty string if it is not """ if hasattr(self, 'role_map'): return self.role_map.get(portal_role, '') else: return '' security.declareProtected(ManagePortal, 'getMemberareaCreationFlag') def getMemberareaCreationFlag(self): """ Returns the flag indicating whether the membership tool will create a member area if an authenticated user from an underlying user folder logs in first without going through the join process """ if not hasattr(self, 'memberareaCreationFlag'): self.memberareaCreationFlag = 0 return self.memberareaCreationFlag security.declareProtected(ManagePortal, 'setMemberareaCreationFlag') def setMemberareaCreationFlag(self): """ sets the flag indicating whether the membership tool will create a member area if an authenticated user from an underlying user folder logs in first without going through the join process """ if not hasattr(self, 'memberareaCreationFlag'): self.memberareaCreationFlag = 0 if self.memberareaCreationFlag == 0: self.memberareaCreationFlag = 1 else: self.memberareaCreationFlag = 0 return MessageDialog( title ='Member area creation flag changed', message='Member area creation flag has been updated', action ='manage_mapRoles') security.declareProtected(ManagePortal, 'createMemberarea') def createMemberarea(self, member_id): """ create a member area """ parent = self.aq_inner.aq_parent members = getattr(parent, 'Members', None) if members is not None: members.manage_addPortalFolder(member_id) f=getattr(members, member_id) f.manage_permission(CMFCorePermissions.View, ['Owner','Manager','Reviewer'], 0) f.manage_permission(CMFCorePermissions.AccessContentsInformation, ['Owner','Manager','Reviewer'], 0) security.declarePublic('isAnonymousUser') def isAnonymousUser(self): ''' Returns 1 if the user is not logged in. ''' u = _getAuthenticatedUser(self) if u is None or u.getUserName() == 'Anonymous User': return 1 return 0 security.declarePublic('checkPermission') def checkPermission(self, permissionName, object, subobjectName=None): ''' Checks whether the current user has the given permission on the given object or subobject. ''' if subobjectName is not None: object = getattr(object, subobjectName) return _checkPermission(permissionName, object) security.declarePublic('credentialsChanged') def credentialsChanged(self, password): ''' Notifies the authentication mechanism that this user has changed passwords. This can be used to update the authentication cookie. Note that this call should *not* cause any change at all to user databases. ''' if not self.isAnonymousUser(): acl_users = self.acl_users user = _getAuthenticatedUser(self) id = user.getUserName() if hasattr(acl_users.aq_base, 'credentialsChanged'): # Use an interface provided by LoginManager. acl_users.credentialsChanged(user, id, password) else: req = self.REQUEST p = getattr(req, '_credentials_changed_path', None) if p is not None: # Use an interface provided by CookieCrumbler. change = self.restrictedTraverse(p) change(user, id, password) security.declareProtected(ManagePortal, 'getMemberById') def getMemberById(self, id): ''' Returns the given member. ''' u = self.acl_users.getUser(id) if u is not None: u = self.wrapUser(u) return u def __getPUS(self): # Gets something we can call getUsers() and getUserNames() on. acl_users = self.acl_users if hasattr(acl_users, 'getUsers'): return acl_users else: # This hack works around the absence of getUsers() in LoginManager. # Gets the PersistentUserSource object that stores our users for us in acl_users.UserSourcesGroup.objectValues(): if us.meta_type == 'Persistent User Source': return us.__of__(acl_users) security.declareProtected(ManagePortal, 'listMemberIds') def listMemberIds(self): '''Lists the ids of all members. This may eventually be replaced with a set of methods for querying pieces of the list rather than the entire list at once. ''' return self.__getPUS().getUserNames() security.declareProtected(ManagePortal, 'listMembers') def listMembers(self): '''Gets the list of all members. ''' return map(self.wrapUser, self.__getPUS().getUsers()) security.declarePrivate('addMember') def addMember(self, id, password, roles, domains, properties=None): '''Adds a new member to the user folder. Security checks will have already been performed. Called by portal_registration. ''' acl_users = self.acl_users if hasattr(acl_users, '_addUser'): acl_users._addUser(id, password, password, roles, domains) else: # The acl_users folder is a LoginManager. Search for a UserSource # with the needed support. for source in acl_users.UserSourcesGroup.objectValues(): if hasattr(source, 'addUser'): source.__of__(self).addUser(id, password, roles, domains) return raise "Can't add Member", "No supported UserSources" if properties is not None: membership = getToolByName(self, 'portal_membership') member = membership.getMemberById(id) member.setMemberProperties(properties) security.declarePrivate('listActions') def listActions(self, info): return None security.declarePublic('getHomeFolder') def getHomeFolder(self, id=None, verifyPermission=0): """Returns a member's home folder object or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None security.declarePublic('getHomeUrl') def getHomeUrl(self, id=None, verifyPermission=0): """Returns the URL to a member's home folder or None. Set verifyPermission to 1 to return None when the user doesn't have the View permission on the folder. """ return None