""" Challenge the user for credentials. """ realm = response.realm if realm: response.addHeader('WWW-Authenticate', 'basic realm="%s"' % realm) m = "<strong>You are not authorized to access this resource.</strong>" if response.debug_mode: if response._auth: m = m + '<p>\nUsername and password are not correct.' else: m = m + '<p>\nNo Authorization header found.' response.setBody(m, is_error=1) response.setStatus(401) return 1 security.declarePrivate('resetCredentials') def resetCredentials(self, request, response): """ Raise unauthorized to tell browser to clear credentials. """ # XXX: Does this need to check whether we have an HTTP response? response.unauthorized() classImplements(HTTPBasicAuthHelper, IHTTPBasicAuthHelper, ILoginPasswordHostExtractionPlugin, IChallengePlugin, ICredentialsResetPlugin) InitializeClass(HTTPBasicAuthHelper)
response.setBody(self.body) # Keep HTTPResponse.exception() from further writing on the # response body, without using HTTPResponse.write() response._locked_status = True response.setBody = self._setBody # Keep response.exception return True # Methods to override on response def _setBody(self, body, *args, **kw): pass classImplements( InlineAuthHelper , IInlineAuthHelper , ILoginPasswordHostExtractionPlugin , IChallengePlugin ) InitializeClass(InlineAuthHelper) BASIC_LOGIN_FORM = """<html> <head> <title> Login Form </title> </head> <body> <h3> Please log in </h3>
return None InitializeClass(ERP5User) class ERP5UserFactory(BasePlugin): """ PAS plugin for creating users that understand local roles blocking based on type information's acquire_local_roles """ meta_type = "ERP5 User Factory" security = ClassSecurityInfo() def __init__(self, id, title=None): self._id = self.id = id self.title = title security.declarePrivate("createUser") def createUser(self, user_id, name): """ See IUserFactoryPlugin """ return ERP5User(user_id, name) classImplements(ERP5UserFactory, IUserFactoryPlugin) InitializeClass(ERP5UserFactory)
record = self._domain_map.get(user_id, []) if len(record) < 1: msg = 'No mappings for user %s' % user_id if msg: if REQUEST is not None: return self.manage_map(manage_tabs_message=msg) else: return to_delete = [x for x in record if x['match_id'] in match_ids] for match in to_delete: record.remove(match) self._domain_map[user_id] = record if REQUEST is not None: msg = 'Matches deleted' if user_id: return self.manage_map(manage_tabs_message=msg) else: return self.manage_genericmap(manage_tabs_message=msg) classImplements(DomainAuthHelper, IDomainAuthHelper, IExtractionPlugin, IAuthenticationPlugin, IRolesPlugin) InitializeClass(DomainAuthHelper)
#Save user_id_key if user_id_key == '' or user_id_key is None: error_message += 'Invalid key value ' else: self.user_id_key = user_id_key if login_portal_type_list == '' or login_portal_type_list is None: error_message += 'Invalid portal type value ' else: self.login_portal_type_list = login_portal_type_list #Redirect if RESPONSE is not None: if error_message != '': self.REQUEST.form['manage_tabs_message'] = error_message return self.manage_editERP5ExternalAuthenticationPluginForm( RESPONSE) else: message = "Updated" RESPONSE.redirect( '%s/manage_editERP5ExternalAuthenticationPluginForm' '?manage_tabs_message=%s' % (self.absolute_url(), message)) #List implementation of class classImplements(ERP5ExternalAuthenticationPlugin, plugins.ILoginPasswordHostExtractionPlugin) InitializeClass(ERP5ExternalAuthenticationPlugin)
if not login_name: login_name = user_id # XXX: validate 'user_id', 'login_name' against policies? self.updateUserPassword(user_id, login_name, password) message = 'password+updated' if RESPONSE is not None: RESPONSE.redirect('%s/manage_updatePasswordForm' '?manage_tabs_message=%s' % (self.absolute_url(), message)) classImplements(ZODBUserManager, IZODBUserManager, IAuthenticationPlugin, IUserEnumerationPlugin, IUserAdderPlugin) InitializeClass(ZODBUserManager) class _ZODBUserFilter: def __init__(self, id=None, login=None, **kw): self._filter_ids = id self._filter_logins = login def __call__(self, user_info): if self._filter_ids: key = 'id'
id = self.getId() for type in pt: ids = plugins.listPluginIds( type ) if id not in ids and type in active_interfaces: plugins.activatePlugin( type, id ) # turn us on elif id in ids and type not in active_interfaces: plugins.deactivatePlugin( type, id ) # turn us off if RESPONSE is not None: RESPONSE.redirect('%s/manage_workspace' '?manage_tabs_message=' 'Interface+activations+updated.' % self.absolute_url()) security.declarePrivate( '_getPAS' ) def _getPAS( self ): """ Canonical way to get at the PAS instance from a plugin """ return aq_parent( aq_inner( self ) ) try: from Products.Five.bridge import fromZ2Interface except ImportError: BasePlugin.__implements__ = SimpleItem.__implements__ else: classImplements( BasePlugin , *implementedBy(SimpleItem) ) InitializeClass(BasePlugin)
if not removed: message = 'Principals+not+in+group+%s' % group_id else: message = 'Principals+%s+removed+from+%s' % ('+'.join(removed), group_id) if RESPONSE is not None: RESPONSE.redirect(('%s/manage_groups?group_id=%s&assign=1' + '&manage_tabs_message=%s') % (self.absolute_url(), group_id, message)) manage_removePrincipalsFromGroup = postonly( manage_removePrincipalsFromGroup) classImplements(ZODBGroupManager, IZODBGroupManager, IGroupEnumerationPlugin, IGroupsPlugin) InitializeClass(ZODBGroupManager) class _ZODBGroupFilter: def __init__(self, id=None, title=None, **kw): self._filter_ids = id self._filter_titles = title def __call__(self, group_info): if self._filter_ids: key = 'id'
return creds def authenticateCredentials(self, credentials): if credentials.has_key('extractor') and \ credentials['extractor'] != self.getId(): return (None, None) login = credentials.get('login') #log( "returning credentials: (%s, %s)" % (login, login) ) return (login, login) security.declarePrivate('resetCredentials') def resetCredentials(self, request, response): """ Clears credentials""" session = self.REQUEST.SESSION session[self.session_var] = None classImplements( OneTimeTokenPlugin, IExtractionPlugin, IAuthenticationPlugin, ) InitializeClass(OneTimeTokenPlugin)
#Register value self._id = self.id = id self.title = title security.declarePrivate('extractCredentials') def extractCredentials(self, request): """ Extract credentials from the request header. """ creds = {} getHeader = getattr(request, 'getHeader', None) if getHeader is None: # use get_header instead for Zope-2.8 getHeader = request.get_header user_id = getHeader('REMOTE_USER') if user_id is not None: creds['external_login'] = user_id creds['remote_host'] = request.get('REMOTE_HOST', '') creds['login_portal_type'] = "ERP5 Login" try: creds['remote_address'] = request.getClientAddr() except AttributeError: creds['remote_address'] = request.get('REMOTE_ADDR', '') return creds else: # fallback to default way return DumbHTTPExtractor().extractCredentials(request) classImplements( SlapOSMachineAuthenticationPlugin, plugins.ILoginPasswordHostExtractionPlugin) InitializeClass(SlapOSMachineAuthenticationPlugin)
if ip & mask == subnet: return dict(AutoRole=True) return {} # # IAuthenticationPlugin # security.declarePrivate('authenticateCredentials') def authenticateCredentials(self, credentials): # Make sure we don't instantiate anonymous if there are other credentials # BBB: this seems only work for basic authentication. Can we do something better? # cf. Products.AutoRoleFromHostHeader if credentials.get('login'): return None autorole = credentials.get('AutoRole', None) if not autorole: return None return ('Anonymous User', 'Anonymous User') classImplements( AutoRole , IRolesPlugin , IGroupsPlugin , IExtractionPlugin , IAuthenticationPlugin ) InitializeClass(AutoRole)
**category_dict) if isinstance(group_id_list, str): group_id_list = [group_id_list] security_group_list.extend(group_id_list) except ConflictError: raise except: LOG('EGOVGroupManager', WARNING, 'could not get security groups from %s' % generator_name, error = sys.exc_info()) finally: setSecurityManager(sm) return tuple(security_group_list) if not NO_CACHE_MODE: _getGroupsForPrincipal = CachingMethod(_getGroupsForPrincipal, id='EGOVGroupManager_getGroupsForPrincipal', cache_factory='erp5_content_short') return _getGroupsForPrincipal( user_name=principal.getId(), path=self.getPhysicalPath()) classImplements( EGOVGroupManager , IGroupsPlugin ) InitializeClass(EGOVGroupManager)
#TODO Should read the shibboleth.xml to figureout where the AAP is try: filename, extra_attributes, attribute_path = self.configFile() except TypeError: return [] doc = Sax2.Reader().fromStream(open(filename)) nodes = [n for n in xpath.Evaluate(attribute_path, doc.documentElement)] # TODO the following attributes are missing for an unknown reason attributes = list(set(['HTTP_' + n._get_value().upper().replace('-','_') for n in nodes])) + extra_attributes attributes.sort() return attributes classImplements(ShibbolethHelper, interface.IShibbolethHelper) InitializeClass( ShibbolethHelper ) class _ShibUserFilter: def __init__( self , id=None , login=None , exact_match=False , rattr_map={} , **kw ): self._filter_ids = id
userAccount.setEmail(properties['email']) if properties.has_key('location'): userAccount.setLocation(properties['location']) # XXX more are comming! should leverage the # portal_memberdata tool else: userAccount.setFullname(theLogin) # reindexing the new user account in membrane_tool. membraneTool = getToolByName(self, 'membrane_tool') membraneTool.indexObject(userAccount) finally: # restore the current security manager. setSecurityManager(current_sm) # return admin site's membrane user folder, so you can create user account. security.declarePrivate('getUserFolder') def getUserFolder(self): """ a regular Plone folder as the user management folder. """ app = self.getPhysicalRoot() return app.unrestrictedTraverse(self.userFolder) # implements plugins. classImplements(ProxyMultiPlugins, IAuthenticationPlugin) InitializeClass(ProxyMultiPlugins)
return safe_unicode(sheet.getProperty(id)) return safe_unicode(default) first = safe_unicode(getProperty('firstname', u'')) last = safe_unicode(getProperty('lastname', u'')) street = safe_unicode(getProperty('street', u'')) zip_code = safe_unicode(getProperty('zip', u'')) city = safe_unicode(getProperty('city', u'')) country = safe_unicode(getProperty('country', u'')) try: country = country and get_pycountry_name(country) or '' except KeyError: country = '' join_list = [street, u'{0} {1}'.format(zip_code, city), country] return { 'fullname': u'{0}{1}{2}'.format( first, u' ' if first and last else u'', last ), 'location': u', '.join([it for it in join_list if it]), } classImplements(UserPropertiesPASPlugin, IPropertiesPlugin) InitializeClass(UserPropertiesPASPlugin)
exact_match=exact_match, sort_by=sort_by, max_results=max_results, **kw) security.declarePrivate('enumerateGroups') def enumerateGroups(self, id=None, exact_match=0, sort_by=None, max_results=None, **kw): """ see IGroupEnumerationPlugin """ acl = self._getDelegate() if acl is None: return () return acl.searchGroups(id=id, exact_match=exact_match, sort_by=sort_by, max_results=max_results, **kw) classImplements(SearchPrincipalsPlugin, IUserEnumerationPlugin, IGroupEnumerationPlugin) InitializeClass(SearchPrincipalsPlugin)
'value': '' }) return self.manage_editProtocolMappingForm(info=info, REQUEST=REQUEST) def manage_updateProtocolMapping(self, mapping, REQUEST=None): """ Update mapping of Request Type to Protocols """ for key, value in mapping.items(): value = filter(None, value) if not value: if key in self._map: del self._map[key] else: self._map[key] = value if REQUEST is not None: REQUEST['RESPONSE'].redirect('%s/manage_editProtocolMapping' '?manage_tabs_message=' 'Protocol+Mappings+Changed.' % self.absolute_url()) classImplements(ChallengeProtocolChooser, IChallengeProtocolChooserPlugin, IChallengeProtocolChooser) InitializeClass(ChallengeProtocolChooser) for label, iface in (('Browser', IBrowserRequest), ('WebDAV', IWebDAVRequest), ('FTP', IFTPRequest), ('XML-RPC', IXMLRPCRequest)): registerRequestType(label, iface)
else: for group_id in group_ids: self.removeGroup(group_id) message = 'Groups+removed' if RESPONSE is not None: RESPONSE.redirect('%s/manage_groups?manage_tabs_message=%s' % (self.absolute_url(), message)) manage_removeGroups = postonly(manage_removeGroups) classImplements(DynamicGroupsPlugin, IDynamicGroupsPlugin, IGroupsPlugin, IGroupEnumerationPlugin) InitializeClass(DynamicGroupsPlugin) class _DynamicGroupFilter: def __init__(self, id=None, **kw): self._filter_ids = id def __call__(self, group_info): if self._filter_ids: key = 'id'
__name__='manage_editERP5ExternalAuthenticationPluginForm') security.declareProtected(ManageUsers, 'manage_editERP5ExternalAuthenticationPlugin') def manage_editERP5ExternalAuthenticationPlugin(self, user_id_key, RESPONSE=None): """Edit the object""" error_message = '' #Save user_id_key if user_id_key == '' or user_id_key is None: error_message += 'Invalid key value ' else: self.user_id_key = user_id_key #Redirect if RESPONSE is not None: if error_message != '': self.REQUEST.form['manage_tabs_message'] = error_message return self.manage_editERP5ExternalAuthenticationPluginForm(RESPONSE) else: message = "Updated" RESPONSE.redirect('%s/manage_editERP5ExternalAuthenticationPluginForm' '?manage_tabs_message=%s' % (self.absolute_url(), message) ) #List implementation of class classImplements(ERP5ExternalAuthenticationPlugin, plugins.ILoginPasswordHostExtractionPlugin) InitializeClass(ERP5ExternalAuthenticationPlugin)
, sort_by=sort_by , max_results=max_results , **kw ) security.declarePrivate('enumerateGroups') def enumerateGroups( self , id=None , exact_match=0 , sort_by=None , max_results=None , **kw ): """ see IGroupEnumerationPlugin """ acl = self._getDelegate() if acl is None: return () return acl.searchGroups( id=id , exact_match=exact_match , sort_by=sort_by , max_results=max_results , **kw ) classImplements( SearchPrincipalsPlugin , IUserEnumerationPlugin , IGroupEnumerationPlugin ) InitializeClass(SearchPrincipalsPlugin)
yield roles def _get_principal_by_id(self, principal_id): session = Session() query = session.query(self.principal_class).filter_by( zope_id=principal_id ) return query.first() classImplements( Plugin, IAuthenticationPlugin, IUserEnumerationPlugin, IUserAdderPlugin, IUserManagement, IDeleteCapability, IPasswordSetCapability, IRolesPlugin, IRoleAssignerPlugin, IAssignRoleCapability, IGroupCapability, IPropertiesPlugin, IMutablePropertiesPlugin, IGroupsPlugin, IGroupEnumerationPlugin, IGroupIntrospection, IGroupManagement) InitializeClass(Plugin)
@UnrestrictedMethod def extractCredentials(self, request): return DumbHTTPExtractor().extractCredentials(request) #Form for new plugin in ZMI manage_addERP5DumbHTTPExtractionPluginForm = PageTemplateFile( 'www/ERP5Security_addERP5DumbHTTPExtractionPlugin', globals(), __name__='manage_addERP5DumbHTTPExtractionPluginForm') def addERP5DumbHTTPExtractionPlugin(dispatcher, id, title=None, REQUEST=None): """ Add an ERP5DumbHTTPExtractionPlugin to a Pluggable Auth Service. """ plugin = ERP5DumbHTTPExtractionPlugin(id, title) dispatcher._setObject(plugin.getId(), plugin) if REQUEST is not None: REQUEST['RESPONSE'].redirect('%s/manage_workspace' '?manage_tabs_message=' 'ERP5DumbHTTPExtractionPlugin+added.' % dispatcher.absolute_url()) #List implementation of class classImplements(ERP5DumbHTTPExtractionPlugin, plugins.ILoginPasswordHostExtractionPlugin) InitializeClass(ERP5DumbHTTPExtractionPlugin)
if cookie_auth: set_anon_user = False except: pass return dict(TokenRole=True, SetAnonymousUser=set_anon_user) return {} # # IAuthenticationPlugin # security.declarePrivate('authenticateCredentials') def authenticateCredentials(self, credentials): if credentials.has_key('login'): if credentials.get('login'): return None tokenrole = credentials.get('TokenRole', None) if not tokenrole: return None if credentials.get('SetAnonymousUser', None): return ('Anonymous User', 'Anonymous User') return None classImplements(TokenRole, IExtractionPlugin, IAuthenticationPlugin) InitializeClass(TokenRole)
# Our regex didn't match, or something went wrong. return '' security.declarePrivate('challenge') def challenge(self, request, response): # Just Start a challenge, if not logged yet if request.getHeader(httpRemoteUserKey, None) == None: url = self.loginUrl(request.ACTUAL_URL) if url: response.redirect(url, lock=True) return True # Pass off control to the next challenge plugin. return False classImplements(AutoUserMakerPASPlugin, IAuthenticationPlugin, IChallengePlugin) class MockUser: """Used in ExtractionPlugin.extractCredentials for testing. Unittest it here (not that it does much ;-): >>> from Products.AutoUserMakerPASPlugin.auth import MockUser >>> user = MockUser('test') >>> user.getId() 'test' >>> user.getGroups() () """ def __init__(self, sUserId): self.sUserId = sUserId
request.SESSION.set('__ac_password', password) if creds: creds['remote_host'] = request.get('REMOTE_HOST', '') try: creds['remote_address'] = request.getClientAddr() except AttributeError: creds['remote_address'] = request.get('REMOTE_ADDR', '') return creds @security.private def updateCredentials(self, request, response, login, new_password): """ Respond to change of credentials. """ request.SESSION.set('__ac_name', login) request.SESSION.set('__ac_password', new_password) @security.private def resetCredentials(self, request, response): """ Empty out the currently-stored session values """ request.SESSION.set('__ac_name', '') request.SESSION.set('__ac_password', '') classImplements(SessionAuthHelper, ISessionAuthHelper, ILoginPasswordHostExtractionPlugin, ICredentialsUpdatePlugin, ICredentialsResetPlugin) InitializeClass(SessionAuthHelper)
""" Challenge the user for credentials. Prevent redirect to login page for paths mentioned in control panel" """ portal = getSite() annotations = IAnnotations(portal) do_basic_auth_paths = annotations.get('rohberg.doorman.do_basic_auth_paths', []) if do_basic_auth_paths: realm = response.realm do_basic_auth = False vup = request.get("VIRTUAL_URL_PARTS", None) if vup: vup = list(vup) if len(vup) > 2: do_basic_auth = vup[2] in do_basic_auth_paths if do_basic_auth: if realm: response.addHeader('WWW-Authenticate', 'basic realm="%s"' % realm) m = "<strong>You are not authorized to access this resource.</strong>" response.setBody(m, is_error=1) response.setStatus(401) return 1 return 0 for itf in PLUGIN_INTERFACES: classImplements(StrengthenedPasswordPlugin, itf) InitializeClass(StrengthenedPasswordPlugin)
"""Refresh the cookie""" setHeader = REQUEST.response.setHeader # Disable HTTP 1.0 Caching setHeader('Expires', formatdate(0, usegmt=True)) if self.refresh_interval < 0: return self._refresh_content(REQUEST) now = time.time() refreshed = self._refreshSession(REQUEST, now) if not refreshed: # We have an unauthenticated user setHeader('Cache-Control', 'public, must-revalidate, max-age=%d, s-max-age=86400' % self.refresh_interval) setHeader('Vary', 'Cookie') else: setHeader('Cache-Control', 'private, must-revalidate, proxy-revalidate, max-age=%d, s-max-age=0' % self.refresh_interval) return self._refresh_content(REQUEST) security.declarePublic('remove') def remove(self, REQUEST): """Remove the cookie""" self.resetCredentials(REQUEST, REQUEST.response) setHeader = REQUEST.response.setHeader # Disable HTTP 1.0 Caching setHeader('Expires', formatdate(0, usegmt=True)) setHeader('Cache-Control', 'public, must-revalidate, max-age=0, s-max-age=86400') return self._refresh_content(REQUEST) classImplements(SessionPlugin, ISessionPlugin, IExtractionPlugin, IAuthenticationPlugin, ICredentialsResetPlugin, ICredentialsUpdatePlugin)
# 3rd - try to fetch from URI Query Parameter # Not implemented as considered as unsecure. pass if token is not None: with super_user(): reference = self.Base_extractBearerTokenInformation(token) if reference is not None: creds['external_login'] = reference if 'external_login' in creds: creds['remote_host'] = request.get('REMOTE_HOST', '') try: creds['remote_address'] = request.getClientAddr() except AttributeError: creds['remote_address'] = request.get('REMOTE_ADDR', '') return creds # fallback to default way return DumbHTTPExtractor().extractCredentials(request) manage_editERP5BearerExtractionPluginForm = PageTemplateFile( 'www/ERP5Security_editERP5BearerExtractionPlugin', globals(), __name__='manage_editERP5BearerExtractionPluginForm') #List implementation of class classImplements( ERP5BearerExtractionPlugin, plugins.ILoginPasswordHostExtractionPlugin ) InitializeClass(ERP5BearerExtractionPlugin)
self._id = self.id = id self.title = title security.declarePrivate('sniffRequestType') def sniffRequestType(self, request): found = None for iface, func in _sniffers: if func( request ): found = iface if found is not None: return found classImplements(RequestTypeSniffer, IRequestTypeSnifferPlugin, IRequestTypeSniffer, ) InitializeClass(RequestTypeSniffer) # Most of the sniffing code below has been inspired by # similar tests found in BaseRequest, HTTPRequest and ZServer def webdavSniffer(request): dav_src = request.get('WEBDAV_SOURCE_PORT', None) method = request.get('REQUEST_METHOD', 'GET').upper() path_info = request.get('PATH_INFO', '') if dav_src: return True if method not in ('GET', 'POST'):
return assertion def validateServiceTicket( self, service, ticket ): ''' See interfaces.IAnzCASClient. ''' if self.ticketValidationSpecification == 'CAS 1.0': validator = Cas10TicketValidator( self.casServerUrlPrefix, self.renew ) else: if self.acceptAnyProxy or self.allowedProxyChains: validator = Cas20ProxyTicketValidator( self.casServerUrlPrefix, self._pgtStorage, acceptAnyProxy=self.acceptAnyProxy, allowedProxyChains=self.allowedProxyChains, renew=self.renew ) else: validator = Cas20ServiceTicketValidator( self.casServerUrlPrefix, self._pgtStorage, self.renew ) return validator.validate( ticket, service, self.getProxyCallbackUrl() ) classImplements( AnzCASClient, IExtractionPlugin, IChallengePlugin, ICredentialsResetPlugin, IAuthenticationPlugin ) InitializeClass( AnzCASClient )
# log( "returning username: %s" % username ) return creds def authenticateCredentials(self, credentials): if 'extractor' in credentials and \ credentials['extractor'] != self.getId(): return (None, None) login = credentials.get('login') #log( "returning credentials: (%s, %s)" % (login, login) ) return (login, login) security.declarePrivate('resetCredentials') def resetCredentials(self, request, response): """ Clears credentials""" session = self.REQUEST.SESSION session[self.session_var] = None classImplements(OneTimeTokenPlugin, IExtractionPlugin, IAuthenticationPlugin, ) InitializeClass(OneTimeTokenPlugin)
message = 'no+groups+selected' else: for group_id in group_ids: self.removeGroup( group_id ) message = 'Groups+removed' if RESPONSE is not None: RESPONSE.redirect( '%s/manage_groups?manage_tabs_message=%s' % ( self.absolute_url(), message ) ) classImplements( DynamicGroupsPlugin , IGroupsPlugin , IGroupEnumerationPlugin ) InitializeClass( DynamicGroupsPlugin ) class _DynamicGroupFilter: def __init__( self , id=None , **kw ): self._filter_ids = id def __call__( self, group_info ):
# | foo | # +-----+ # 1 row in set (0.01 sec) # " foo", "foo " and other padding variations because of # ZSQLCatalog (feature ?): # (Pdb) print portal.portal_catalog.unrestrictedSearchResults(\ # portal_type="Person", reference=' foo ', src__=1) # SELECT DISTINCT # catalog.path, catalog.uid # FROM # catalog AS catalog # WHERE # 1 = 1 # AND (((((catalog.portal_type = 'Person'))))) AND (((((catalog.reference = 'foo'))))) # LIMIT 1000 # "bar OR foo" because of ZSQLCatalog tokenizing searched sgtrings # by default (feature). return [x.path for x in result if (not exact_match) or x['reference'] in login] _getUserByLogin = CachingMethod(_getUserByLogin, id='ERP5UserManager_getUserByLogin', cache_factory='erp5_content_short') result = _getUserByLogin(login, exact_match) return [portal.unrestrictedTraverse(x) for x in result] classImplements( EGOVUserManager , IAuthenticationPlugin , IUserEnumerationPlugin ) InitializeClass(EGOVUserManager)
def challenge( self, request, response, **kw ): """ Challenge the user for credentials. """ realm = response.realm if realm: response.addHeader('WWW-Authenticate', 'basic realm="%s"' % realm) m = "<strong>You are not authorized to access this resource.</strong>" response.setBody(m, is_error=1) response.setStatus(401) return 1 security.declarePrivate( 'resetCredentials' ) def resetCredentials( self, request, response ): """ Raise unauthorized to tell browser to clear credentials. """ # XXX: Does this need to check whether we have an HTTP response? response.unauthorized() classImplements( HTTPBasicAuthHelper , IHTTPBasicAuthHelper , ILoginPasswordHostExtractionPlugin , IChallengePlugin , ICredentialsResetPlugin ) InitializeClass( HTTPBasicAuthHelper )
class PloneUserFactory(BasePlugin): security = ClassSecurityInfo() meta_type = "Plone User Factory" def __init__(self, id, title=""): self.id = id self.title = title or self.meta_type security.declarePrivate("createUser") def createUser(self, user_id, name): return PloneUser(user_id, name) classImplements(PloneUserFactory, IUserFactoryPlugin) InitializeClass(PloneUserFactory) class PloneUser(PropertiedUser): security = ClassSecurityInfo() ################################# # GRUF API _isGroup = False def __init__(self, id, login=None): super(PloneUser, self).__init__(id, login) self._propertysheets = OrderedDict()
if data: self.ZCacheable_set(data, view_name=view_name) sheet = MutablePropertySheet(self.id, **data) return sheet # # IMutablePropertiesPlugin implementation # def setPropertiesForUser(self, user, propertysheet): if user.isGroup(): pass #we do not set any attributes from plone here else: h = httplib2.Http() query = '/++rest++brs/users' data = {'login': user.getUserName()} params = urllib.urlencode(data) resp, content = h.request(connection_url() + query + params, "GET") if propertysheet.getProperty('email'): data['email'] = propertysheet.getProperty('email') if propertysheet.getProperty('notification') != None: data['receive_notification'] = propertysheet.getProperty( 'notification') view_name = createViewName('getPropertiesForUser', user) cached_info = self.ZCacheable_invalidate(view_name=view_name) classImplements(PropertyProvider, IPropertiesPlugin, IUpdatePlugin, IMutablePropertiesPlugin)
# exist, and user ids are some internal detail where it is easy to avoid # such magic strings) and no login (because nobody should ever be able to # log in as a special user, and logins are exposed to users (duh !) and # hence magic values are impossible to avoid with ad-hoc code peppered # everywhere). To avoid such ad-hoc code, this plugin will find magic # users so code checking if a user login exists before allowing it to be # reused, preventing misleading logins from being misused. result.append({ 'id': special_user_name, 'login': special_user_name, 'pluginid': plugin_id, 'path': None, 'uid': None, 'login_list': [{ 'reference': special_user_name, 'path': None, 'uid': None, }] }) return tuple(result) classImplements(ERP5LoginUserManager, IAuthenticationPlugin, IUserEnumerationPlugin) InitializeClass(ERP5LoginUserManager)
if login is not None: kwargs = { 'username': login, 'password': credentials.get('password', '') } if self._realm: kwargs['realm'] = self._realm if self._config_file: kwargs['config'] = self._config_file try: logger.info('Verify user %s' % login) user = _kerberos5.KerberosUser(**kwargs) if user.is_valid(): username = user.get_username() principal = user.get_principal() logger.info('Authentication succeed for "%s" (%s)', username, principal) return (username, username) except (_kerberos5.KerberosError, _kerberos5.KerberosPasswordExpired), error: logger.info('Failed to authenticate "%s" (%s)', login, error.args[0]) pass return None classImplements(Kerberos5Plugin, IKerberos5Plugin, plugins.IAuthenticationPlugin, *implementedBy(BasePlugin)) InitializeClass(Kerberos5Plugin)
session.close() #self.ZCacheable_set(data, view_name=view_name) if data: #self.ZCacheable_set(data, view_name=view_name) idSyg = data.pop('id', None) sheet = MutablePropertySheet(idSyg, **data) if request: request.SESSION.set("sheetSygefor%s" % username, sheet) return sheet # # IRolesPlugin implementation # def getRolesForPrincipal(self, principal, request=None): #print "--- getRolesForPrincipal ---" return ("Authenticated", "Sygefor") def Session(self): engine = create_engine(self.serviceUrl, echo=False) return sessionmaker(bind=engine)() classImplements( SygeforHelper, IAuthenticationPlugin, IPropertiesPlugin, IRolesPlugin, IUserEnumerationPlugin, ) InitializeClass(SygeforHelper)
response.setStatus('200') response.setBody(self.body) # Keep HTTPResponse.exception() from further writing on the # response body, without using HTTPResponse.write() response._locked_status = True response.setBody = self._setBody # Keep response.exception return True # Methods to override on response def _setBody(self, body, *args, **kw): pass classImplements(InlineAuthHelper, IInlineAuthHelper, ILoginPasswordHostExtractionPlugin, IChallengePlugin) InitializeClass(InlineAuthHelper) BASIC_LOGIN_FORM = """<html> <head> <title> Login Form </title> </head> <body> <h3> Please log in </h3> <form method="post"> <table cellpadding="2"> <tr>
def getRoleInfo(self, role_id): """Over-ride parent to not explode when getting role info by role_id.""" return self._roles.get(role_id, None) def allowRoleAssign(self, user_id, role_id): """True iff this plugin will allow assigning a certain user a certain role.""" present = self.getRoleInfo(role_id) if present: return 1 # if we have a role, we can assign it # slightly naive, but should be okay. return 0 def listRoleIds(self): self.updateRolesList() return ZODBRoleManager.listRoleIds(self) def getRoleInfo(self, role_id): if role_id not in self._roles: self.updateRolesList() return ZODBRoleManager.getRoleInfo(self, role_id) def getRoleInfo(self, role_id): if role_id not in self._roles: self.updateRolesList() return ZODBRoleManager.getRoleInfo(self, role_id) classImplements(GroupAwareRoleManager, IAssignRoleCapability, *implementedBy(ZODBRoleManager)) InitializeClass(GroupAwareRoleManager)
security.declarePrivate('geturl_encoded_string_for_hdd') def geturl_encoded_string_for_hdd(self, request, response): user = request.AUTHENTICATED_USER perm_set = None permission_set = self.get_simsathens_permissions(contact_number=user).dictionaries() decoded_key = base64.b64decode(self.key+'==') if request.get('came_from'): came_from = request.get('came_from') else: came_from = request['BASE0'] for permission in permission_set: if permission['permission_set']: perm_set = permission['permission_set'] url_string="<dst p=\"%s\" u=\"%s\" d=\"%s\" />"%(perm_set, user ,request.get('p')) LOG('AthenPASPlugin',INFO, "HDD String is " + str(url_string)) pad = self.block_size - len(url_string) % self.block_size data = url_string + pad * chr(pad) encrypted_string = self.iv_bytes + AES.new(decoded_key, self.mode, self.iv_bytes).encrypt(data) base64_encoded_string=base64.b64encode(encrypted_string) self.insert_web_auth_log(contact_number=user,permission_set='rcs-cs',url_string=url_string,return_url=request.environ['HTTP_REFERER'],browser=request.environ['HTTP_USER_AGENT'],ip_address=request.environ['REMOTE_ADDR'],return_parameter=None) return urllib.urlencode({"t":"dst","id":self.org_id,"p":base64_encoded_string}) classImplements(AthensdaHelper, interface.IAthensdaHelper, ICredentialsUpdatePlugin) InitializeClass( AthensdaHelper )
""" See IPropertySheet. """ result = [] for id, ptype in self._schema: result.append( { 'id' : id, 'type' : ptype, 'mode' : '' } ) return tuple( result ) def propertyIds( self ): """ See IPropertySheet. """ return [ x[0] for x in self._schema ] def propertyValues( self ): """ See IPropertySheet. """ return [ self._properties.get( x ) for x in self.propertyIds() ] def propertyItems( self ): """ See IPropertySheet. """ return [ ( x, self._properties.get( x ) ) for x in self.propertyIds() ] classImplements( UserPropertySheet , IPropertySheet )
# IUpdateCredentialPlugins get their updateCredentials method # called. If the method is called on the CookieAuthHelper it will # simply set its own auth cookie, to the exclusion of any other # plugins that might want to store the credentials. pas_instance = self._getPAS() if pas_instance is not None: pas_instance.updateCredentials(request, response, login, password) came_from = request.form['came_from'] return response.redirect(came_from) classImplements(CookieAuthHelper, ICookieAuthHelper, ILoginPasswordHostExtractionPlugin, IChallengePlugin, ICredentialsUpdatePlugin, ICredentialsResetPlugin) InitializeClass(CookieAuthHelper) BASIC_LOGIN_FORM = """<html> <head> <title> Login Form </title> </head> <body> <h3> Please log in </h3> <form method="post" action="" tal:attributes="action string:${here/absolute_url}/login">
return {'login': login, 'last': last, 'IP': IP, 'count': count} security.declareProtected(ManageUsers, 'listAttempts') def listAttempts(self): root = self.getRootPlugin() return [self.getAttemptInfo(x) for x in root._login_attempts.keys()] security.declareProtected(ManageUsers, 'resetAllAccounts') def resetAllAccounts(self): root = self.getRootPlugin() root._login_attempts.clear() classImplements(AccountLocker, IAuthenticationPlugin, IAnonymousUserFactoryPlugin) InitializeClass(AccountLocker) def setup(context): def activatePluginForInterfaces(pas, plugin, selected_interfaces): plugin_obj = pas[plugin] activatable = [] for info in plugin_obj.plugins.listPluginTypeInfo(): interface = info['interface'] interface_name = info['id'] if plugin_obj.testImplements(interface) and \ interface_name in selected_interfaces: activatable.append(interface_name)
def manage_updateProtocolMapping(self, mapping, REQUEST=None): """ Update mapping of Request Type to Protocols """ for key, value in mapping.items(): value = filter(None, value) if not value: if self._map.has_key(key): del self._map[key] else: self._map[key] = value if REQUEST is not None: REQUEST["RESPONSE"].redirect( "%s/manage_editProtocolMapping" "?manage_tabs_message=" "Protocol+Mappings+Changed." % self.absolute_url() ) classImplements(ChallengeProtocolChooser, IChallengeProtocolChooserPlugin, IChallengeProtocolChooser) InitializeClass(ChallengeProtocolChooser) for label, iface in ( ("Browser", IBrowserRequest), ("WebDAV", IWebDAVRequest), ("FTP", IFTPRequest), ("XML-RPC", IXMLRPCRequest), ): registerRequestType(label, iface)
"DisabledUserPlugin: extractCredentials: __ac_name: %s" % str(__ac_name)) try: dtool = DisabledUser(self) except Exception, e: logger.info("extractCredentials: Exception: %s" % str(e)) raise else: if __ac_name: try: is_disabled = dtool.is_disabled(__ac_name) except Exception, e: logger.info( "extractCredentials: Exception: %s" % str(e)) raise else: logger.info( "extractCredentials: is_disabled: %s" % str(is_disabled)) if is_disabled: messages = IStatusMessage(request) messages.add(redirect_message, type=u"error") raise Redirect(redirect_url) return None classImplements(DisabledUserPlugin, IExtractionPlugin) InitializeClass(DisabledUserPlugin)
category_order=base_category_list, **category_dict) if isinstance(group_id_list, str): group_id_list = [group_id_list] security_group_list.extend(group_id_list) except ConflictError: raise except: LOG('ERP5GroupManager', WARNING, 'could not get security groups from %s' % generator_name, error=sys.exc_info()) finally: pass return tuple(security_group_list) if not NO_CACHE_MODE: _getGroupsForPrincipal = CachingMethod( _getGroupsForPrincipal, id='ERP5GroupManager_getGroupsForPrincipal', cache_factory='erp5_content_short') return _getGroupsForPrincipal(user_name=principal.getId(), path=self.getPhysicalPath()) classImplements(ERP5GroupManager, IGroupsPlugin) InitializeClass(ERP5GroupManager)
return view_name, keywords def _invalidateCache(self, user): view_name, keywords = self._getUserPropertyCacheKey(user) ldapmp = self.getLDAPMultiPlugin(user) ldapmp.ZCacheable_invalidate(view_name=view_name) def _setCache(self, user, properties): """Cache user properties""" view_name, keywords = self._getUserPropertyCacheKey(user) ldapmp = self.getLDAPMultiPlugin(user) ldapmp.ZCacheable_set(properties, view_name=view_name, keywords=keywords) def _getCache(self, user, default=None): """Retrieve user properties from cache, given a user id. Returns None or the passed-in default if the cache has no group with such id """ view_name, keywords = self._getUserPropertyCacheKey(user) ldapmp = self.getLDAPMultiPlugin(user) result = ldapmp.ZCacheable_get(view_name=view_name, keywords=keywords, default=default) return result classImplements(LDAPPropertySheet, IMutablePropertySheet)
keywords = {'id': gid} return view_name, keywords security.declarePrivate('_setGroupInfoCache') def _setGroupInfoCache(self, info): """Cache a group info""" gid = info['id'] view_name, keywords = self._getGroupInfoCacheKey(gid) self.ZCacheable_set(info, view_name=view_name, keywords=keywords) security.declarePrivate('_getGroupInfoCache') def _getGroupInfoCache(self, gid, default=None): """Retrieve a group info from cache, given its group id. Returns None or the passed-in default if the cache has no group with such id """ view_name, keywords = self._getGroupInfoCacheKey(gid) result = self.ZCacheable_get(view_name=view_name, keywords=keywords, default=default) return result classImplements(LDAPPluginBase, IAuthenticationPlugin, ICredentialsResetPlugin, IPropertiesPlugin, IRolesPlugin, ILDAPMultiPlugin) InitializeClass(LDAPPluginBase)
def getGroupIds(self): # gruf returns these prefixed return self._getUserFolder().getGroupIds() def getGroups(self): return self._getUserFolder().getGroups() def getGroupMembers(self, group_id): return self._getUserFolder().getMemberIds(group_id) ################################# def getGroupInfo(self, group): url = group.absolute_url() return { 'id' : group.getId(), 'pluginid' : self.getId(), 'members_url' : url, 'properties_url' : url, } def _demangle(self, princid): unmangle_fn = self.aq_acquire('_unmangleId') # acquire from PAS unmangled_princid = unmangle_fn(princid)[-1] return unmangled_princid classImplements(GRUFBridge, plugins.IGroupsPlugin, plugins.IGroupEnumerationPlugin, *implementedBy(DelegatingMultiPlugin)) InitializeClass(GRUFBridge)
for policy in uf.objectIds(['Default Plone Password Policy']): uf.plugins.deactivatePlugin(IValidationPlugin, policy) obj = DeadParrotPassword('test') uf._setObject(obj.getId(), obj) obj = uf[obj.getId()] activatePluginInterfaces(portal, obj.getId()) # portal = getUtility(ISiteRoot) plugins = uf._getOb('plugins') validators = plugins.listPlugins(IValidationPlugin) assert validators commit() classImplements(DeadParrotPassword, IValidationPlugin) def get_security_settings(): registry = getUtility(IRegistry) return registry.forInterface(ISecuritySchema, prefix="plone") def set_mock_mailhost(portal): portal._original_MailHost = portal.MailHost portal.MailHost = mailhost = MockMailHost('MailHost') sm = getSiteManager(context=portal) sm.unregisterUtility(provided=IMailHost) sm.registerUtility(mailhost, provided=IMailHost)
from AccessControl import ClassSecurityInfo from Products.Archetypes.public import IStorage from Products.PluggableAuthService.utils import classImplements from Products.PlonePAS.interfaces.propertysheets import IMutablePropertySheet class PASStorage(object): security = ClassSecurityInfo() def get(self, name, instance, **kwargs): user = instance.getUser() sheets = user.getOrderedSheets() for sheet in sheets: if sheet.hasProperty(name): return sheet.getProperty(name) raise AttributeError(name) def set(self, name, instance, value, **kwargs): user = instance.getUser() sheets = user.getOrderedSheets() for sheet in sheets: if sheet.hasProperty(name): if IMutablePropertySheet.providedBy(sheet): sheet.setProperty(name, value) else: raise RuntimeError("mutable property provider shadowed by read only provider") classImplements(PASStorage, IStorage)
self.title = title # # IGroupsPlugin implementation # security.declarePrivate('getGroupsForPrincipal') def getGroupsForPrincipal(self, user, request=None): set = list(user.getGroups()) seen = [] parent = aq_parent(self) while set: test = set.pop(0) if test in seen: continue seen.append(test) new_groups = parent._getGroupsForPrincipal( PropertiedUser(test).__of__(parent), ignore_plugins=(self.getId(), )) if new_groups: set.extend(new_groups) return tuple(seen) classImplements(RecursiveGroupsPlugin, IRecursiveGroupsPlugin, IGroupsPlugin) InitializeClass(RecursiveGroupsPlugin)
This function handles GET parameters """ service = request['URL'] # remove ticket parameter(s) query_string = request.get('QUERY_STRING', "") ticket_idx = query_string.find('ticket=') if ticket_idx > 1: # ticket is after some other parameters that we preserve # we also remove the '&' char query_string = query_string[:ticket_idx - 1] elif ticket_idx == 0: # ticket was the only parameter query_string = "" # add filtered QUERY_STRING to service if query_string: service = "%s?%s" % (service, query_string) return urllib.quote(service) classImplements(CASAuthHelper, IExtractionPlugin, IChallengePlugin, ICredentialsResetPlugin, IAuthenticationPlugin) InitializeClass(CASAuthHelper)
class LocalRolePlugin(BasePlugin): """ Provide roles during Authentication from local roles assignments made on the root object. """ meta_type = 'Local Role Plugin' security = ClassSecurityInfo() def __init__(self, id, title=None): self._setId(id) self.title = title # # IRolesPlugin implementation # security.declarePrivate('getRolesForPrincipal') def getRolesForPrincipal(self, principal, request=None): """ See IRolesPlugin. """ local_roles = getattr(self.getPhysicalRoot(), '__ac_local_roles__', None) if local_roles is None: return None return local_roles.get(principal.getId()) classImplements(LocalRolePlugin, ILocalRolePlugin, IRolesPlugin) InitializeClass(LocalRolePlugin)
# Read magical header task_user_id = request.getHeader('X-Task-User-Id') if task_user_id != None: return {'login': task_user_id} return {} # IAuthenticationPlugin implementation def authenticateCredentials(self, credentials): # Verity credentials source if credentials.get('extractor') != self.getId(): return None # Verify credentials data if not 'login' in credentials: return None # Verify user pas = self._getPAS() info = pas._verifyUser(pas.plugins, user_id=credentials['login']) if info is None: return None # Let the task request in as requested user return info['id'], info['login'] classImplements(TaskQueueAuthPlugin, IExtractionPlugin, IAuthenticationPlugin) InitializeClass(TaskQueueAuthPlugin)
""" For ZMI update of interfaces. """ pas_instance = self._getPAS() plugins = pas_instance._getOb('plugins') new_interfaces = [] for interface in interfaces: new_interfaces.append(plugins._getInterfaceFromName(interface)) klass_interfaces = [x for x in implementedBy(ScriptablePlugin)] directlyProvides(self, *(klass_interfaces + new_interfaces)) if RESPONSE is not None: RESPONSE.redirect('%s/manage_workspace' '?manage_tabs_message=' 'Interfaces+updated.' % self.absolute_url()) try: from Products.Five.bridge import fromZ2Interface except ImportError: ScriptablePlugin.__implements__ = ((IScriptablePlugin, ) + Folder.__implements__ + BasePlugin.__implements__) else: classImplements(ScriptablePlugin, IScriptablePlugin, *(implementedBy(Folder) + implementedBy(BasePlugin))) InitializeClass(ScriptablePlugin)
if not removed: message = 'Principals+not+in+group+%s' % group_id else: message = 'Principals+%s+removed+from+%s' % ( '+'.join( removed ) , group_id ) if RESPONSE is not None: RESPONSE.redirect( ( '%s/manage_groups?group_id=%s&assign=1' + '&manage_tabs_message=%s' ) % ( self.absolute_url(), group_id, message ) ) classImplements( ZODBGroupManager , IGroupEnumerationPlugin , IGroupsPlugin ) InitializeClass( ZODBGroupManager ) class _ZODBGroupFilter: def __init__( self , id=None , title=None , **kw ): self._filter_ids = id self._filter_titles = title