Exemplo n.º 1
0
    def extractCredentials(self, request):
        """Ties to extract credentials from a request.

        A return value of None indicates that no credentials could be found.
        Any other return value is treated as valid credentials.
        """
        session = ISession(request)[SESSION_KEY]
        requestToken = session.get(REQUEST_TOKEN_KEY)
        accessToken = session.get(ACCESS_TOKEN_KEY)
        if not requestToken and not accessToken:
            return None
        return TwitterCredentials(requestToken, accessToken)
Exemplo n.º 2
0
    def authenticateCredentials(self, credentials):
        """
        Check if username and password match
        get the credentials from the IUserManagement Utility
        """
        request = zope.security.management.getInteraction().participations[0]
        session = ISession(request)['adhoc.authentication']
        authenticated = session.get(USER_SESSION_KEY)
        if authenticated is None:
            if not (credentials and 'login' in credentials
                    and 'password' in credentials):
                return
            login, password = credentials['login'], credentials['password']

            utility = IAdHocManagement(request.principal)

            if not utility.checkRule(login):
                return

            user = utility.getData(login)
            if not user:
                return

            if not utility.validatePassword(password, user.get('password')):
                return
            user_id = login
            authenticated = session[USER_SESSION_KEY] = dict(
                id=user_id,
                title=login,
                description=login,
                login=login)
        return PrincipalInfo(**authenticated)
Exemplo n.º 3
0
    def __init__(self, *args, **kw):
        # Figure out sorting situation
        kw['ignore_request'] = True
        request = args[1]
        prefix = kw.get('prefix')
        session = ISession(request)[self.sortKey]
        if 'sort-on' in request:
            name = request['sort-on']
            if prefix and name.startswith(prefix):
                name = name[len(prefix):]
                oldName, oldReverse = session.get(prefix, (None, None))
                if oldName == name:
                    session[prefix] = (name, not oldReverse)
                else:
                    session[prefix] = (name, False)
        # Now get the sort-on data from the session
        if prefix in session:
            kw['sort_on'] = [session[prefix]]

        super(ListFormatter, self).__init__(*args, **kw)
        self.columnCSS = {}

        self.sortOn = (None, None)
        if 'sort_on' in kw:
            for name, reverse in kw['sort_on']:
                self.columnCSS[name] = 'sorted-on'
            self.sortOn = kw['sort_on'][0]
Exemplo n.º 4
0
    def authenticateCredentials(self, credentials):
        """
        Check if username and password match
        get the credentials from the IUserManagement Utility
        """
        request = zope.security.management.getInteraction().participations[0]
        session = ISession(request)["adhoc.authentication"]
        authenticated = session.get(USER_SESSION_KEY)
        if authenticated is None:
            if not (credentials and "login" in credentials and "password" in credentials):
                return
            login, password = credentials["login"], credentials["password"]

            utility = IAdHocManagement(request.principal)

            if not utility.checkRule(login):
                return

            user = utility.getData(login)
            if not user:
                return

            if not utility.validatePassword(password, user.get("password")):
                return
            user_id = login
            authenticated = session[USER_SESSION_KEY] = dict(id=user_id, title=login, description=login, login=login)
        return PrincipalInfo(**authenticated)
Exemplo n.º 5
0
    def uninstall(self):
        """See `IDatabasePolicy`.

        If the request just handled was not read_only, we need to store
        this fact and the timestamp in the session. Subsequent requests
        can then keep using the master until they are sure any changes
        made have been propagated.
        """
        if not self.read_only:
            # We need to further distinguish whether it's safe to write
            # to the session. This will be true if the principal is
            # authenticated or if there is already a session cookie
            # hanging around.
            if not IUnauthenticatedPrincipal.providedBy(
                    self.request.principal) or self._hasSession():
                # A non-readonly request has been made. Store this fact
                # in the session. Precision is hard coded at 1 minute
                # (so we don't update the timestamp if it is no more
                # than 1 minute out of date to avoid unnecessary and
                # expensive write operations). Feeds are always read
                # only, and since they run over http, browsers won't
                # send their session key that was set over https, so we
                # don't want to access the session which will overwrite
                # the cookie and log the user out.
                session_data = ISession(self.request)['lp.dbpolicy']
                last_write = session_data.get('last_write', None)
                now = _now()
                if (last_write is None
                        or last_write < now - timedelta(minutes=1)):
                    # set value
                    session_data['last_write'] = now
Exemplo n.º 6
0
    def extractCredentials(self, request):
        """Extracts credentials from a session if they exist."""
        if not IHTTPRequest.providedBy(request):
            return None
        session = ISession(request, None)
        sessionData = session.get('z3c.authenticator.credential.session')
        login = request.get(self.loginfield, None)
        password = request.get(self.passwordfield, None)
        # support z3c.form prefixes
        for prefix in self.prefixes:
            login = request.get(prefix + self.loginfield, login)
            password = request.get(prefix + self.passwordfield, password)
        credentials = None

        if login and password:
            credentials = SessionCredentials(login, password)
        elif not sessionData:
            return None
        sessionData = session['z3c.authenticator.credential.session']
        if credentials:
            sessionData['credentials'] = credentials
        else:
            credentials = sessionData.get('credentials', None)
        if not credentials:
            return None
        return {'login': credentials.getLogin(),
                'password': credentials.getPassword()}
Exemplo n.º 7
0
    def __init__(self, *args, **kw):
        # Figure out sorting situation
        kw['ignore_request'] = True
        request = args[1]
        prefix = kw.get('prefix')
        session = ISession(request)[self.sortKey]
        if 'sort-on' in request:
            name = request['sort-on']
            if prefix and name.startswith(prefix):
                name = name[len(prefix):]
                oldName, oldReverse = session.get(prefix, (None, None))
                if oldName == name:
                    session[prefix] = (name, not oldReverse)
                else:
                    session[prefix] = (name, False)
        # Now get the sort-on data from the session
        if prefix in session:
            kw['sort_on'] = [session[prefix]]

        super(ListFormatter, self).__init__(*args, **kw)
        self.columnCSS = {}

        self.sortOn = (None, None)
        if 'sort_on' in kw:
            for name, reverse in kw['sort_on']:
                self.columnCSS[name] = 'sorted-on'
            self.sortOn = kw['sort_on'][0]
Exemplo n.º 8
0
    def uninstall(self):
        """See `IDatabasePolicy`.

        If the request just handled was not read_only, we need to store
        this fact and the timestamp in the session. Subsequent requests
        can then keep using the master until they are sure any changes
        made have been propagated.
        """
        if not self.read_only:
            # We need to further distinguish whether it's safe to write
            # to the session. This will be true if the principal is
            # authenticated or if there is already a session cookie
            # hanging around.
            if not IUnauthenticatedPrincipal.providedBy(
                self.request.principal) or self._hasSession():
                # A non-readonly request has been made. Store this fact
                # in the session. Precision is hard coded at 1 minute
                # (so we don't update the timestamp if it is no more
                # than 1 minute out of date to avoid unnecessary and
                # expensive write operations). Feeds are always read
                # only, and since they run over http, browsers won't
                # send their session key that was set over https, so we
                # don't want to access the session which will overwrite
                # the cookie and log the user out.
                session_data = ISession(self.request)['lp.dbpolicy']
                last_write = session_data.get('last_write', None)
                now = _now()
                if (last_write is None or
                    last_write < now - timedelta(minutes=1)):
                    # set value
                    session_data['last_write'] = now
Exemplo n.º 9
0
    def extractCredentials(self, request):
        """Extracts credentials from a session if they exist."""
        if not IHTTPRequest.providedBy(request):
            return None
        session = ISession(request)
        sessionData = session.get(
            'zope.pluggableauth.browserplugins')
        login = request.get(self.loginfield, None)
        password = request.get(self.passwordfield, None)
        credentials = None

        if login and password:
            credentials = self._makeCredentials(login, password)
        elif not sessionData:
            return None
        sessionData = session[
            'zope.pluggableauth.browserplugins']
        if credentials:
            sessionData['credentials'] = credentials
        else:
            credentials = sessionData.get('credentials', None)
        if not credentials:
            return None
        return {'login': credentials.getLogin(),
                'password': credentials.getPassword()}
Exemplo n.º 10
0
 def extractCredentials(self, request):
     if not IHTTPRequest.providedBy(request):
         return None
     login = request.get(self.loginfield, None)
     password = request.get(self.passwordfield, None)
     session = ISession(request)
     sessionData = session.get('zope.pluggableauth.browserplugins')
     traversalStack = request.getTraversalStack()
     authMethod = 'standard'
     credentials = None
     if sessionData:
         credentials = sessionData.get('credentials')
         if isinstance(sessionData, TwoFactorSessionCredentials):
             authMethod = '2factor'
     if (authMethod == 'standard' and traversalStack
             and traversalStack[-1].startswith('++auth++')):
         authMethod = traversalStack[-1][8:]
     viewAnnotations = request.annotations.setdefault('loops.view', {})
     viewAnnotations['auth_method'] = authMethod
     #log.info('authentication method: %s.' % authMethod)
     if authMethod == 'standard':
         return self.extractStandardCredentials(request, login, password,
                                                session, credentials)
     elif authMethod == '2factor':
         return self.extract2FactorCredentials(request, login, password,
                                               session, credentials)
     else:
         return None
Exemplo n.º 11
0
 def extractCredentials(self, request):
     if not IHTTPRequest.providedBy(request):
         return None
     login = request.get(self.loginfield, None)
     password = request.get(self.passwordfield, None)
     session = ISession(request)
     sessionData = session.get('zope.pluggableauth.browserplugins')
     traversalStack = request.getTraversalStack()
     authMethod = 'standard'
     credentials = None
     if sessionData:
         credentials = sessionData.get('credentials')
         if isinstance(sessionData, TwoFactorSessionCredentials):
             authMethod = '2factor'
     if (authMethod == 'standard' and 
             traversalStack and traversalStack[-1].startswith('++auth++')):
         authMethod = traversalStack[-1][8:]
     viewAnnotations = request.annotations.setdefault('loops.view', {})
     viewAnnotations['auth_method'] = authMethod
     #log.info('authentication method: %s.' % authMethod)
     if authMethod == 'standard':
         return self.extractStandardCredentials(
                         request, login, password, session, credentials)
     elif authMethod == '2factor':
         return self.extract2FactorCredentials(
                         request, login, password, session, credentials)
     else:
         return None
Exemplo n.º 12
0
    def extractCredentials(self, request, overrides=None):
        """Extracts credentials from a session if they exist."""

        if not IHTTPRequest.providedBy(request):
            return None

        session = ISession(request)
        sessionData = session.get('zope.app.authentication.browserplugins')

        (login, password, domain, ip) = (None, None, None, None)
        credentials = None
        logging_in = False

        if overrides:
            login = overrides.get('login', None)
            password = overrides.get('password', None)
            ip = overrides.get('ip', None)
            domain = overrides.get('domain', None)

        login = login or request.get(self.loginfield, None)
        password = password or request.get(self.passwordfield, None)
        domain = domain or request.get(self.domainfield, None)
        ip = ip or request.environment.get('HTTP_X_FORWARDED_FOR', None)
        ip = ip or request.environment.get('REMOTE_ADDR', None)

        if login and password:
            credentials = SessionCredentials(
                login,
                password,
                ip=ip,
                domain=domain,
                request_annotations=request.annotations,
                passwordManager=self.passwordManager)
            if IHTTPRequest.providedBy(request):
                self._update_cookie(request, credentials)
            logging_in = True

        elif not sessionData:
            return None
        sessionData = session['zope.app.authentication.browserplugins']
        if credentials:
            sessionData['credentials'] = credentials
        else:
            credentials = sessionData.get('credentials', None)
            if not credentials:
                return None
            if credentials.isExpired(self.idleExpiry):
                return None
        return {
            'login': credentials.getLogin(),
            'password': credentials.getPassword(),
            'ip': credentials.getIP(),
            'domain': credentials.getDomain(),
            'logging_in': logging_in,
            'request-annotations': credentials.getRequestAnnotations(),
            'extractTime': credentials.getExtractTime(),
            'accessTime': credentials.getAccessTime(),
            'passwordManager': credentials.getPasswordManager(),
        }
Exemplo n.º 13
0
 def handleLogin(self, action):
     """Handle the subscribe action will register and login a user."""
     if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
         session = ISession(self.request, None)
         sessionData = session.get('z3c.authenticator.credential.session')
         if sessionData is not None and sessionData.get('camefrom'):
             self.nextURL = sessionData['camefrom']
             sessionData['camefrom'] = None
Exemplo n.º 14
0
 def restorePOSTData(self, request):
     form = getattr(request, "form", None)
     if form:
         form_id = request.form.get('post_form')
         if form_id:
             session = ISession(request)[self.session_name]
             form = session.get(form_id, None)
             if form is not None:
                 request.form = form
                 del session[form_id]
Exemplo n.º 15
0
    def update(self):
        context = self.context
        request = self.request

        self.noIcon = not bool(self.context.icon)

        principal = self.request.principal
        if not IUnauthenticatedPrincipal.providedBy(principal):
            self.menu = True

            self.submitTopic = \
                checkPermission('zojax.forum.AddTopic', context) or \
                checkPermission('zojax.forum.SubmitTopic', context)

            notifications = getAdapter(context, IContentNotification, 'forum')
            self.subscribed = notifications.isSubscribed(principal.id)

        if len(self.context) > 1:
            self.searching = True

        data = ISession(request)[SESSIONKEY]
        forum = removeAllProxies(context)
        key = getUtility(IIntIds).getId(forum)

        if 'form.button.search' in request:
            searchableText = request['form.searchforum']
            data[key] = (searchableText, True)

        if 'form.button.clear' in request:
            searchableText = None
            if key in data:
                del data[key]

        else:
            searchtext, searching = data.get(key, (u'', False))
            if searchtext and searching:
                searchableText = searchtext
            else:
                searchableText = None

        if searchableText:
            query = {'searchableText': searchableText,
                     'type': {'any_of': ('forum.message',)},
                     'traversablePath': {'any_of': (forum,)},
                     'noPublishing': True, 'noSecurityChecks': True}

            try:
                results = getUtility(ICatalog).searchResults(**query)
            except Exception, e:
                IStatusMessage(self.request).add(e, 'error')
                return

            self.total = len(results)
            self.searchableText = searchableText
            self.searchResults = Batch(results, size=20, request=request)
Exemplo n.º 16
0
 def getCurrentStep(self):
     """See interfaces.IWizard"""
     session = ISession(self.request)[self.sessionKey]
     if 'step' in self.request:
         name = self.request['step']
         step = name, dict(self.steps).get(name)
     else:
         step = session.get('step', self.steps[0])
     session['step'] = step
     name, klass = step
     inst = klass(self.getContent(), self.request, self)
     inst.name = name
     return inst
Exemplo n.º 17
0
    def install(self):
        """See `IDatabasePolicy`."""
        default_flavor = None

        # If this is a Retry attempt, force use of the master database.
        if getattr(self.request, '_retry_count', 0) > 0:
            default_flavor = MASTER_FLAVOR

        # Select if the DEFAULT_FLAVOR Store will be the master or a
        # slave. We select slave if this is a readonly request, and
        # only readonly requests have been made by this user recently.
        # This ensures that a user will see any changes they just made
        # on the master, despite the fact it might take a while for
        # those changes to propagate to the slave databases.
        elif self.read_only:
            lag = self.getReplicationLag()
            if (lag is not None
                and lag > timedelta(seconds=config.database.max_usable_lag)):
                # Don't use the slave at all if lag is greater than the
                # configured threshold. This reduces replication oddities
                # noticed by users, as well as reducing load on the
                # slave allowing it to catch up quicker.
                default_flavor = MASTER_FLAVOR
            else:
                # We don't want to even make a DB query to read the session
                # if we can tell that it is not around.  This can be
                # important for fast and reliable performance for pages like
                # +opstats.
                if self._hasSession():
                    session_data = ISession(self.request)['lp.dbpolicy']
                    last_write = session_data.get('last_write', None)
                else:
                    last_write = None
                now = _now()
                # 'recently' is  2 minutes plus the replication lag.
                recently = timedelta(minutes=2)
                if lag is None:
                    recently = timedelta(minutes=2)
                else:
                    recently = timedelta(minutes=2) + lag
                if last_write is None or last_write < now - recently:
                    default_flavor = SLAVE_FLAVOR
                else:
                    default_flavor = MASTER_FLAVOR
        else:
            default_flavor = MASTER_FLAVOR

        assert default_flavor is not None, 'default_flavor not set!'

        self.default_flavor = default_flavor
Exemplo n.º 18
0
    def install(self):
        """See `IDatabasePolicy`."""
        default_flavor = None

        # If this is a Retry attempt, force use of the master database.
        if getattr(self.request, '_retry_count', 0) > 0:
            default_flavor = MASTER_FLAVOR

        # Select if the DEFAULT_FLAVOR Store will be the master or a
        # slave. We select slave if this is a readonly request, and
        # only readonly requests have been made by this user recently.
        # This ensures that a user will see any changes they just made
        # on the master, despite the fact it might take a while for
        # those changes to propagate to the slave databases.
        elif self.read_only:
            lag = self.getReplicationLag()
            if (lag is not None and
                    lag > timedelta(seconds=config.database.max_usable_lag)):
                # Don't use the slave at all if lag is greater than the
                # configured threshold. This reduces replication oddities
                # noticed by users, as well as reducing load on the
                # slave allowing it to catch up quicker.
                default_flavor = MASTER_FLAVOR
            else:
                # We don't want to even make a DB query to read the session
                # if we can tell that it is not around.  This can be
                # important for fast and reliable performance for pages like
                # +opstats.
                if self._hasSession():
                    session_data = ISession(self.request)['lp.dbpolicy']
                    last_write = session_data.get('last_write', None)
                else:
                    last_write = None
                now = _now()
                # 'recently' is  2 minutes plus the replication lag.
                recently = timedelta(minutes=2)
                if lag is None:
                    recently = timedelta(minutes=2)
                else:
                    recently = timedelta(minutes=2) + lag
                if last_write is None or last_write < now - recently:
                    default_flavor = SLAVE_FLAVOR
                else:
                    default_flavor = MASTER_FLAVOR
        else:
            default_flavor = MASTER_FLAVOR

        assert default_flavor is not None, 'default_flavor not set!'

        self.default_flavor = default_flavor
Exemplo n.º 19
0
    def extract(self, default=NOVALUE):  # noqa
        action = self.request.get('{0}.action'.format(self.name), None)
        if self.request.get('PATH_INFO',
                            '').endswith('kss_z3cform_inline_validation'):
            action = 'nochange'

        if action == 'remove':
            return None
        elif action == 'nochange':
            session = ISession(self.request)[SESSION_PKG_KEY]
            token = self.uploaded_token
            if token is None:
                token = self.request.get('{0}.token'.format(self.name), None)
            if token in session:
                self.uploaded_token = token
                return session.get(token)
            if self.value is not None:
                return self.value
            if self.ignoreContext:
                return default
            dm = getMultiAdapter((self.context, self.field), IDataManager)
            value = dm.query()

            if isinstance(value, Proxy):
                value = removeSecurityProxy(value)
            return value
        elif action == 'replace':
            # set the action back to 'nochange' so that the button is
            # preselected. Only applicable when form is reloaded with errors
            self.request.form['{0}.action'.format(self.name)] = 'nochange'

        # empty unnamed FileUploads should not count as a value
        value = super(NamedFileWidget, self).extract(default)
        if isinstance(value, FileUpload):
            value.seek(0, SEEK_END)
            empty = value.tell() == 0
            value.seek(0)
            if empty and not value.filename:
                return default
            value.seek(0)
            session = ISession(self.request)[SESSION_PKG_KEY]
            if self.unique_token not in session:
                self.uploaded_token = self.unique_token
                value = IDataConverter(self).toFieldValue(value)
                session[self.unique_token] = value
        elif not value:
            return default
        return value
Exemplo n.º 20
0
 def authenticateCredentials(self, credentials):
     USER_SESSION_KEY = "adhoc.authentication"
     request = uvcsite.getRequest()
     session = ISession(request)['adhoc.authentication']
     authenticated = session.get(USER_SESSION_KEY)
     if authenticated is None:
         if not isinstance(credentials, dict):
             return
         account = self.getAccount(credentials["login"])
         if account is None:
             return None
         if not account.checkPassword(
                 credentials["password"],
                 credentials.get("gebdate", '99.99.9999')):
             return None
         else:
             authenticated = session[USER_SESSION_KEY] = dict(id=account.az)
     return PrincipalInfo(**authenticated)
Exemplo n.º 21
0
    def authenticateCredentials(self, credentials):
        """
        Check if username and password match
        get the credentials from the IUserManagement Utility
        """
        request = zope.security.management.getInteraction().participations[0]
        session = ISession(request)['uvcsite.authentication']
        authenticated = session.get(USER_SESSION_KEY)
        if authenticated is None:
            if not (credentials and 'login' in credentials
                    and 'password' in credentials):
                return
            login, password = credentials['login'], credentials['password']

            utility = getUtility(IUserManagement)

            if hasattr(utility, 'changeLogin'):
                login = utility.changeLogin(login)

            if not utility.checkRule(login):
                return
            if '@' in login:
                user = utility.getUserByEMail(login)
            else:
                user = utility.getUser(login)
            if not user:
                return

            if hasattr(utility, 'checkPW'):
                if not utility.checkPW(password, user.get('passwort')):
                    return
            else:
                if password != user.get('passwort'):
                    return
            user_id = user['mnr']
            if user['az'] != '00':
                user_id = "%s-%s" % (user['mnr'], user['az'])
            authenticated = session[USER_SESSION_KEY] = dict(
                id=user_id,
                title=login,
                description=login,
                login=login)
        return PrincipalInfo(**authenticated)
Exemplo n.º 22
0
    def authenticateCredentials(self, credentials):
        """
        Check if username and password match
        get the credentials from the IUserManagement Utility
        """
        request = zope.security.management.getInteraction().participations[0]
        session = ISession(request)['uvcsite.authentication']
        authenticated = session.get(USER_SESSION_KEY)
        if authenticated is None:
            if not (credentials and 'login' in credentials
                    and 'password' in credentials):
                return
            login, password = credentials['login'], credentials['password']

            utility = getUtility(IUserManagement)

            if hasattr(utility, 'changeLogin'):
                login = utility.changeLogin(login)

            if not utility.checkRule(login):
                return
            if '@' in login:
                user = utility.getUserByEMail(login)
            else:
                user = utility.getUser(login)
            if not user:
                return

            if hasattr(utility, 'checkPW'):
                if not utility.checkPW(password, user.get('passwort')):
                    return
            else:
                if password != user.get('passwort'):
                    return
            user_id = user['mnr']
            if user['az'] != '00':
                user_id = "%s-%s" % (user['mnr'], user['az'])
            authenticated = session[USER_SESSION_KEY] = dict(id=user_id,
                                                             title=login,
                                                             description=login,
                                                             login=login)
        return PrincipalInfo(**authenticated)
Exemplo n.º 23
0
    def __init__(self, sequence, start=0, size=20,
                 batches=None, context=None, request=None,
                 prefix='', queryparams={}):
        self.context = context
        self.request = request
        self.prefix = prefix

        if request is not None:
            rkey = self.prefix + 'bstart'

            if context is None:
                key = rkey
            else:
                key = '%s:%s'%(getPath(context), rkey)

            if rkey in request:
                try:
                    rstart = int(request.get(rkey, start))

                    data = ISession(request)[SESSIONKEY]
                    data[key] = rstart

                    start = rstart
                except:
                    pass
            else:
                data = ISession(request)[SESSIONKEY]
                start = data.get(key, start)

        if start >= len(sequence):
            start = 0

        super(SessionBatch, self).__init__(sequence, start, size, batches)

        if batches is None:
            self.batches = Batches(self)

        self.queryparams = queryparams
Exemplo n.º 24
0
def getCredentials(request):
    session = ISession(request)
    sessionData = session.get('zope.pluggableauth.browserplugins')
    if not sessionData:
        return None
    return sessionData.get('credentials')
Exemplo n.º 25
0
 def getContent(self):
     session = ISession(self.request)[PersonWizard.sessionKey]
     return session.get('content')
Exemplo n.º 26
0
 def getContent(self):
     session = ISession(self.request)[self.sessionKey]
     obj = session.get('content')
     if obj is None:
         obj = session['content'] = content.Person()
     return obj
Exemplo n.º 27
0
 def get(self):
     session = ISession(self.request)[SESSION_KEY]
     return session.get('selectedContact')
Exemplo n.º 28
0
def getCredentials(request):
    session = ISession(request)
    sessionData = session.get('zope.pluggableauth.browserplugins')
    if not sessionData:
        return None
    return sessionData.get('credentials')
Exemplo n.º 29
0
    def clearPasswordManager(self, request):
        """If there is a mistmatch between the encryption used by the
        principal and the encryption used for the session, then there
        is no possible recovery. Trigger this function, which will 
        clear the encryption used for the session. Clear text passwords
        can flow through to the principal machinery, which can then use
        it's own configured password manager to do the encryption.
        
        To demonstrate, first set up a plugin with a passwordManager

          >>> from zope.publisher.browser import TestRequest

          >>> from zope.session.session import RAMSessionDataContainer
          >>> from tests import sessionSetUp
          >>> sessionSetUp(RAMSessionDataContainer)

          >>> plugin = SessionCredentialsPlugin()

          >>> class NullManager:
          ...     implements(IPasswordManager)
          ...     def encodePassword(self, password):
          ...         return password.lower()
          ...     def checkPassword(self, storedPassword, password):
          ...         return storedPassword == self.encodePassword(password)

          >>> from zope.app.authentication.interfaces import IPasswordManager
          >>> manager = NullManager()
          >>> from zope.component import getGlobalSiteManager
          >>> gsm = getGlobalSiteManager()
          >>> gsm.registerUtility(manager, IPasswordManager, 'manager')
          >>> plugin.passwordManagerName = "manager"
                
          >>> request = TestRequest(login='******', password='******')
          >>> credentials = plugin.extractCredentials(request) 
          >>> credentials['password']
          'tiger'

        Next, clear the password manager

          >>> plugin.clearPasswordManager(request)

        The cached credentials are cleared. The password was encrypted so that it
        is unusable.

          >>> plugin.extractCredentials(TestRequest())  == None
          True

        Subsequent login attempts will return unencrypted credentials.

          >>> credentials = plugin.extractCredentials(request) 
          >>> credentials['passwordManager'] == None
          True
          >>> credentials['password']
          'TIGER'

        """

        # FORCE THE CHANGE - TODO: LOG, TODO: Work with published interface
        #print 'clearPasswordManager'

        self.passwordManagerName = None

        session = ISession(request)
        sessionData = session.get('zope.app.authentication.browserplugins')
        del sessionData['credentials']
Exemplo n.º 30
0
class CompleteOpenIdSignIn(PageletForm):
    interface.implements(IPrincipalPasswordForm, IMailAuthorizationAware)

    label = _("Register new user")

    ignoreContext = True
    fields = Fields(IRegistrationForm, IPrincipalPasswordForm)

    registeredPrincipal = None

    def update(self):
        self.registration = getUtility(IPortalRegistration)

        super(CompleteOpenIdSignIn, self).update()

        request = self.request

        self.portalURL = u'%s/'%absoluteURL(self.context, request)
        self.loginURL = u'%s@@completeOpenIdSignIn'%self.portalURL

        if 'form.zojax-auth-login' in request:
            principal = request.principal
            if IUnauthenticatedPrincipal.providedBy(principal):
                IStatusMessage(request).add(_('Login failed.'), 'warning')
            else:
                principal = IPrincipal(principal)
                principal.identifiers = \
                    principal.identifiers + (self.data['identifier'],)

                del self.data['reqregister']
                del self.data['identifier']

                IStatusMessage(request).add(_('You successfully logged in.'))
                self.redirect('./')

    @button.buttonAndHandler(_(u"Register"), provides=IMemberRegisterAction)
    def handle_register(self, action):
        request = self.request

        data, errors = self.extractData()
        if errors:
            IStatusMessage(request).add(self.formErrorsMessage, 'error')
            return

        plugin = queryUtility(IUsersPlugin)

        login = data['login'].lower()

        # create principal
        principal = Principal(login, data['firstname'], data['lastname'], '')

        # set password
        passwordtool = getUtility(IPasswordTool)
        principal.password = passwordtool.encodePassword(data['password'])

        event.notify(ObjectCreatedEvent(principal))

        # save principal to folder
        name = INameChooser(plugin).chooseName('', principal)

        plugin[name] = principal

        # register principal in registration tool
        auth = getUtility(IAuthentication)
        authprincipal = auth.getPrincipal(auth.prefix + plugin.prefix + name)

        status = self.registration.registerPrincipal(authprincipal, request)
        if status == STATUS_CONTINUE:
            updateCredentials(request, login, data['password'])

            principal.identifiers = \
                principal.identifiers + (self.data['identifier'],)

            del self.data['reqregister']
            del self.data['identifier']

            IStatusMessage(request).add(
                _('You have been successfully registered.'))
            self.redirect(absoluteURL(getSite(), request))

        # IMemberRegistrationForm attribute
        self.registeredPrincipal = authprincipal

    def __call__(self, *args, **kw):
        self.data = ISession(self.request)[SESSION_KEY]

        if not self.data.get('reqregister', False):
            self.redirect(
                u'%s/successOpenIdSignIn?processed=1'%absoluteURL(
                    self.context, self.request))
            return u''

        return super(CompleteOpenIdSignIn, self).__call__(*args, **kw)
Exemplo n.º 31
0
    def update(self):
        name = self.name
        request = self.request
        context = self.form.context

        self.auth = getUtility(IAuthentication)

        key = u'%s:%s'%(getPath(context), name)
        self.sessionKey = key
        self.selectedName = u'%s-selectedItem'%name

        super(BasePrincipalWidget, self).update()

        tp = []
        if IUserField.providedBy(self.field):
            tp = ('user',)
        elif IGroupField.providedBy(self.field):
            tp = ('group',)
        else:
            tp = ('user', 'group')

        # search text
        data = ISession(request)[SESSIONKEY]
        if '%s-empty-marker'%name not in request and key in data:
            del data[key]

        if u'%s.searchButton'%name in request:
            searching = True
            searchtext = request.get(u'%s.searchText'%name, u'')
            data[key] = (searchtext, True)
            if searchtext:
                try:
                    principals = searchPrincipals(
                        tp, searchableText = searchtext)
                except:
                    principals = []
            else:
                principals = []
        elif u'%s.searchClear'%name in request:
            if key in data:
                del data[key]
            searchtext = u''
            searching = False
            principals = searchPrincipals(tp)
        else:
            searchtext, searching = data.get(key, (u'', False))
            if searchtext:
                try:
                    principals = searchPrincipals(
                        tp, searchableText = searchtext)
                except:
                    principals = []
            else:
                principals = searchPrincipals(tp)

        self.searching = searching
        self.searchtext = searchtext

        self.principals = SessionBatch(
            principals, size=self.pageSize,
            context=context, request=request, prefix=name,
            queryparams = {'%s-empty-marker'%self.name: '1'})
Exemplo n.º 32
0
 def get(self):
     session = ISession(self.request)[SESSION_KEY]
     return session.get('selectedContact')
Exemplo n.º 33
0
 def getContent(self):
     session = ISession(self.request)[PersonWizard.sessionKey]
     return session.get('content')
Exemplo n.º 34
0
 def getContent(self):
     session = ISession(self.request)[self.sessionKey]
     obj = session.get('content')
     if obj is None:
         obj = session['content'] = content.Person()
     return obj
Exemplo n.º 35
0
 def __get__(self, inst, klass):
     session = ISession(inst.request)[SESSION_KEY]
     return session.get(self.name, self.default)