Ejemplo n.º 1
0
def specialGroups(event):
    """Set groups for IGroupAwarePrincipal."""

    principal = event.principal
    # only apply to non groups because it will end in cycle dependencies
    # since the principal will have tis role anyway
    if (IGroup.providedBy(principal) or
        not (IGroupAwarePrincipal.providedBy(principal) or
             IUnauthenticatedPrincipal.providedBy(principal))):
        return

    # global utility registered by everybodyGroup directive
    everyone = zope.component.queryUtility(IEveryoneGroup)
    if everyone is not None and everyone.id != principal.id and \
        everyone.id not in principal.groups:
        principal.groups.append(everyone.id)

    if IUnauthenticatedPrincipal.providedBy(principal):
        # global utility registered by unauthenticatedGroup directive
        unAuthGroup = zope.component.queryUtility(IUnauthenticatedGroup)
        if unAuthGroup is not None and unAuthGroup.id != principal.id and \
            unAuthGroup.id not in principal.groups:
            principal.groups.append(unAuthGroup.id)
    else:
        # global utility registered by authenticatedGroup directive
        authGroup = zope.component.queryUtility(IAuthenticatedGroup)
        if authGroup is not None and authGroup.id != principal.id and \
            authGroup.id not in principal.groups:
            principal.groups.append(authGroup.id)
Ejemplo n.º 2
0
def adjust_request_interface_for_preferred_languages(event):
    """
    Checks the conditions outlined in this package's documentation and
    adds a marker interface (:class:`.IPreferredLanguagesRequest`) to
    the request if they hold true.

    This is registered as a subscriber for Pyramid's
    :class:`.IContextFound` event by this package's ``configure.zcml``
    """
    request = event.request
    # Does pyramid's default negotiator, which uses explicit settings
    # like a request param or cookie have an answer? If so, we need
    # our custom policy...these override the Accept-Language header
    if default_locale_negotiator(request):
        interface.alsoProvides(request, IPreferredLanguagesRequest)
        return

    # What about the zope/plone cookie?
    if request.cookies.get('I18N_LANGUAGE'):
        # For benefit of the default localization machinery
        # in case it's used, copy
        request._LOCALE_ = request.cookies.get('I18N_LANGUAGE')
        interface.alsoProvides(request, IPreferredLanguagesRequest)
        return

    # Ok, is there an authenticated user with preferred languages?
    # (We leave detecting defaults up to the actual policy)
    remote_user = IPrincipal(request, None)
    if remote_user and not IUnauthenticatedPrincipal.providedBy(remote_user):
        remote_user_langs = IUserPreferredLanguages(remote_user)
        if remote_user_langs and remote_user_langs.getPreferredLanguages():  # pylint:disable=too-many-function-args
            interface.alsoProvides(request, IPreferredLanguagesRequest)
Ejemplo n.º 3
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
Ejemplo n.º 4
0
    def _maybePlacefullyAuthenticate(self, request, ob):
        if not IUnauthenticatedPrincipal.providedBy(request.principal):
            # We've already got an authenticated user. There's nothing to do.
            # Note that beforeTraversal guarentees that user is not None.
            return

        if not zope.component.interfaces.ISite.providedBy(ob):
            # We won't find an authentication utility here, so give up.
            return

        sm = removeSecurityProxy(ob).getSiteManager()

        auth = sm.queryUtility(IAuthentication)
        if auth is None:
            # No auth utility here
            return

        # Try to authenticate against the auth utility
        principal = auth.authenticate(request)
        if principal is None:
            principal = auth.unauthenticatedPrincipal()
            if principal is None:
                # nothing to do here
                return

        request.setPrincipal(principal)
Ejemplo n.º 5
0
    def _maybePlacefullyAuthenticate(self, request, ob):
        if not IUnauthenticatedPrincipal.providedBy(request.principal):
            # We've already got an authenticated user. There's nothing to do.
            # Note that beforeTraversal guarentees that user is not None.
            return

        if not zope.component.interfaces.ISite.providedBy(ob):
            # We won't find an authentication utility here, so give up.
            return

        sm = removeSecurityProxy(ob).getSiteManager()

        auth = sm.queryUtility(IAuthentication)
        if auth is None:
            # No auth utility here
            return

        # Try to authenticate against the auth utility
        principal = auth.authenticate(request)
        if principal is None:
            principal = auth.unauthenticatedPrincipal()
            if principal is None:
                # nothing to do here
                return

        request.setPrincipal(principal)
Ejemplo n.º 6
0
def homefolder_url(request):
    principal = request.principal
    if IUnauthenticatedPrincipal.providedBy(principal):
        return
    homefolders = getUtility(IHomefolders)
    homefolder = homefolders.get(principal.id)
    return homefolder and IAbsoluteURL(homefolder, request) or None
Ejemplo n.º 7
0
    def render(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            auth = component.getUtility(IAuthentication)
            ILogout(auth).logout(self.request)

        self.flash(_(u'Usted ha deslogueado'), type=u'message')
        return self.redirect(self.application_url())
Ejemplo n.º 8
0
    def getLoggedInPerson(self):
        """Return the currently logged-in person.

        If no one is logged in, return None. If there is an anonymous user
        logged in, then return ANONYMOUS. Otherwise, return the logged-in
        `IPerson`.
        """
        # I don't really know the canonical way of asking for "the logged-in
        # person", so instead I'm using all the ways I can find and making
        # sure they match each other. -- jml
        by_launchbag = getUtility(IOpenLaunchBag).user
        principal = get_current_principal()
        if principal is None:
            return None
        elif IUnauthenticatedPrincipal.providedBy(principal):
            if by_launchbag is None:
                return ANONYMOUS
            else:
                raise ValueError(
                    "Unauthenticated principal, but launchbag thinks "
                    "%r is logged in." % (by_launchbag, ))
        else:
            by_principal = principal.person
            self.assertEqual(by_launchbag, by_principal)
            return by_principal
Ejemplo n.º 9
0
Archivo: login.py Proyecto: bcgsc/gum
 def __call__(self):
     request = self.request
     if (not IUnauthenticatedPrincipal.providedBy(request.principal)
         and 'gum.Login' in request):
         request.response.redirect( self.url(grok.getApplication()) )
     else:
         return self.template.render(self)
Ejemplo n.º 10
0
    def render(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            auth = component.getUtility(IAuthentication)
            ILogout(auth).logout(self.request)

        self.flash(_(u'Usted ha deslogueado'), type=u'message')
        return self.redirect(self.application_url())
Ejemplo n.º 11
0
    def getLoggedInPerson(self):
        """Return the currently logged-in person.

        If no one is logged in, return None. If there is an anonymous user
        logged in, then return ANONYMOUS. Otherwise, return the logged-in
        `IPerson`.
        """
        # I don't really know the canonical way of asking for "the logged-in
        # person", so instead I'm using all the ways I can find and making
        # sure they match each other. -- jml
        by_launchbag = getUtility(IOpenLaunchBag).user
        principal = get_current_principal()
        if principal is None:
            return None
        elif IUnauthenticatedPrincipal.providedBy(principal):
            if by_launchbag is None:
                return ANONYMOUS
            else:
                raise ValueError(
                    "Unauthenticated principal, but launchbag thinks "
                    "%r is logged in." % (by_launchbag,))
        else:
            by_principal = principal.person
            self.assertEqual(by_launchbag, by_principal)
            return by_principal
Ejemplo n.º 12
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         self.http_status_code = 401
         self.additional_headers.update(
             [("WWW-Authenticate", "Basic realm=Bungeni")]
         )
     return super(Unauthorized, self).__call__()
Ejemplo n.º 13
0
def setGroupsForPrincipal(event):
    """Set local group information when a principal is created.

    Note: IUnauthenticatedPrincipal does not provide IGroupAwarePrincipal which
    is just wrong and makes the conditions a little bit complicated.
    """

    principal = event.principal
    # set only groups for group aware principals or unauthenticated which are
    # group aware too. This allows us to apply local roles to unautenticated
    # principals which allows to apply permissions/roles via local groups which
    # the application does not provide at global level.
    if not (IGroupAwarePrincipal.providedBy(principal) or
            IUnauthenticatedPrincipal.providedBy(principal)):
        return

    authentication = event.authentication
    for name, plugin in authentication.getAuthenticatorPlugins():
        if not interfaces.IGroupContainer.providedBy(plugin):
            continue
        # set groups for principals but not a group to itself. This could happen
        # for global defined groups
        principal.groups.extend(
            [id for id in plugin.getGroupsForPrincipal(principal.id)
             if id != principal.id])
Ejemplo n.º 14
0
 def update(self):
     if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
         for key in self.KEYS:
             self.request.response.expireCookie(key, path='/', domain="bgetem.de")
             self.request.response.expireCookie(key, path='/')
         self.request.response.expireCookie('beaker.session.id', path='/')
         self.request['beaker.session'].delete()
Ejemplo n.º 15
0
 def getURL(self, type=""):
     principal = self.request.principal
     if IUnauthenticatedPrincipal.providedBy(principal):
         return
     homeFolder = IHomeFolder(principal).homeFolder
     homeFolder = grok.url(self.request, homeFolder, type)
     return homeFolder
Ejemplo n.º 16
0
 def __call__(node, request):
     if not checkPermission(permission, node.context):
         # You are not allowed here.
         if IUnauthenticatedPrincipal.providedBy(request.principal):
             raise Unauthorized
         raise Forbidden
     return method(node, request)
Ejemplo n.º 17
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
Ejemplo n.º 18
0
 def update(self):
     if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
         for key in self.KEYS:
             self.request.response.expireCookie(key,
             path='/', domain="bg-kooperation.de")
     else:
         self.request.response.expireCookie("auth_pubtkt",
             path='/', domain="bg-kooperation.de")
Ejemplo n.º 19
0
 def login(self, nextURL=None):
     # we don't want to keep challenging if we're authenticated
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         # hard-code basic auth challenge
         self.request.unauthorized('basic realm="Zope"')
         return self.failed()
     else:
         return self._confirm(nextURL)
Ejemplo n.º 20
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
Ejemplo n.º 21
0
 def url(self):
     principal = self.request.principal
     if IUnauthenticatedPrincipal.providedBy(principal):
         return
     hf = IHomeFolder(principal, None)
     if hf:
         return urllib.parse.unquote(grok.util.url(self.request, hf))
     return ""
Ejemplo n.º 22
0
def redirect_on_empty_props(event):
    principal = event.request.principal
    if IUnauthenticatedPrincipal.providedBy(principal):
        return
    if "stammdaten" in event.request.environment.get("PATH_INFO"):
        return
    if event.request.principal.id == u"servicetelefon-0":
        return
Ejemplo n.º 23
0
 def url(self):
     principal = self.request.principal
     if IUnauthenticatedPrincipal.providedBy(principal):
         return
     homeFolder = IHomeFolder(principal, None)
     if homeFolder:
         return str(absoluteURL(homeFolder, self.request)) + "/enms"
     return ""
Ejemplo n.º 24
0
 def login(self, nextURL=None):
     # we don't want to keep challenging if we're authenticated
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         component.getUtility(IAuthentication).unauthorized(
             self.request.principal.id, self.request)
         return self.failed()
     else:
         return self._confirm(nextURL)
Ejemplo n.º 25
0
def test_traverse(url):
    """Traverse the url in the same way normal publishing occurs.

    Returns a tuple of (object, view, request) where:
      object is the last model object in the traversal chain
      view is the defined view for the object at the specified url (if
        the url didn't directly specify a view, then the view is the
        default view for the object.
      request is the request object resulting from the traversal.  This
        contains a populated traversed_objects list just as a browser
        request would from a normal call into the app servers.

    This call uses the currently logged in user, and does not start a new
    transaction.
    """
    url_parts = urlsplit(url)
    server_url = '://'.join(url_parts[0:2])
    path_info = url_parts[2]
    request, publication = get_request_and_publication(
        host=url_parts[1], extra_environment={
            'SERVER_URL': server_url,
            'PATH_INFO': path_info})

    request.setPublication(publication)
    # We avoid calling publication.beforePublication because this starts a new
    # transaction, which causes an abort of the existing transaction, and the
    # removal of any created and uncommitted objects.

    # Set the default layer.
    adapters = getGlobalSiteManager().adapters
    layer = adapters.lookup((providedBy(request),), IDefaultSkin, '')
    if layer is not None:
        layers.setAdditionalLayer(request, layer)

    principal = get_current_principal()

    if IUnauthenticatedPrincipal.providedBy(principal):
        login = None
    else:
        login = principal.person
    setupInteraction(principal, login, request)

    getUtility(IOpenLaunchBag).clear()
    app = publication.getApplication(request)
    view = request.traverse(app)
    # Find the object from the view instead on relying that it stays
    # in the traversed_objects stack. That doesn't apply to the web
    # service for example.
    try:
        obj = removeSecurityProxy(view).context
    except AttributeError:
        # But sometime the view didn't store the context...
        # Use the last traversed object in these cases.
        obj = request.traversed_objects[-2]

    restoreInteraction()

    return obj, view, request
Ejemplo n.º 26
0
 def update(self):
     if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
         for key in self.KEYS:
             self.request.response.expireCookie(key,
                                                path='/',
                                                domain="bgetem.de")
             self.request.response.expireCookie(key, path='/')
         self.request.response.expireCookie('beaker.session.id', path='/')
         self.request['beaker.session'].delete()
Ejemplo n.º 27
0
 def render(self):
     nextURL = self.request.get('nextURL')
     if IUnauthenticatedPrincipal(self.request.principal, False):
         component.getUtility(IAuthentication).unauthorized(
             self.request.principal.id, self.request)
         return self.failed()
     if nextURL is None:
         return self.confirmation()
     self.request.response.redirect(nextURL)
Ejemplo n.º 28
0
 def getSession(self):
     """Get the session data container that stores the OpenID request."""
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         # A dance to assert that we want to break the rules about no
         # unauthenticated sessions. Only after this next line is it
         # safe to set session values.
         allowUnauthenticatedSession(
             self.request, duration=timedelta(minutes=60))
     return ISession(self.request)[SESSION_PKG_KEY]
Ejemplo n.º 29
0
 def url(self):
     principal = self.request.principal
     if IUnauthenticatedPrincipal.providedBy(principal):
         return
     hf = IHomeFolder(principal, None)
     if None:
         return ""
     viewname = "personalpanelview"
     return urllib.parse.unquote(grok.util.url(self.request, hf, viewname))
Ejemplo n.º 30
0
 def getSession(self):
     """Get the session data container that stores the OpenID request."""
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         # A dance to assert that we want to break the rules about no
         # unauthenticated sessions. Only after this next line is it
         # safe to set session values.
         allowUnauthenticatedSession(self.request,
                                     duration=timedelta(minutes=60))
     return ISession(self.request)[SESSION_PKG_KEY]
Ejemplo n.º 31
0
 def render(self):
     nextURL = self.request.get('nextURL')
     if not IUnauthenticatedPrincipal(self.request.principal, False):
         auth = component.getUtility(IAuthentication)
         ILogout(auth).logout(self.request)
         if nextURL:
             return self.redirect()
     if nextURL is None:
         return self.confirmation()
     return self.request.response.redirect(nextURL)
Ejemplo n.º 32
0
    def traverse(self, path):

        if path == 'profile':
            if IUnauthenticatedPrincipal.providedBy(self.request.principal):
                return self.context
            else:
                session = ISession(self.request)['OAuth2']
                if 'principal' in session.keys():
                    user = session['principal']
                    return IUserProfile(user)
Ejemplo n.º 33
0
 def logout(self, nextURL=None):
     if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
         auth = component.getUtility(IAuthentication)
         ILogout(auth).logout(self.request)
         if nextURL:
             return self.redirect()
     if nextURL is None:
         return self.confirmation()
     else:
         return self.request.response.redirect(nextURL)
Ejemplo n.º 34
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         self.request.principal.__parent__.unauthorized(
             self.request.principal.id, self.request)
         return 'Launchpad basic auth login page'
     referer = self.request.getHeader('referer')  # Traditional w3c speling
     if referer and self.isSameHost(referer):
         self.request.response.redirect(referer)
     else:
         self.request.response.redirect(self.request.getURL(1))
     return ''
Ejemplo n.º 35
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         self.request.principal.__parent__.unauthorized(
             self.request.principal.id, self.request)
         return 'Launchpad basic auth login page'
     referer = self.request.getHeader('referer')  # Traditional w3c speling
     if referer and self.isSameHost(referer):
         self.request.response.redirect(referer)
     else:
         self.request.response.redirect(self.request.getURL(1))
     return ''
Ejemplo n.º 36
0
 def render(self):
     nextURL = self.request.get('nextURL')
     if IUnauthenticatedPrincipal(self.request.principal, False):
         # changed by Christian Lu&uuml;ck
         component.getUtility(IAuthentication,
                              context=self.context).unauthorized(
                                  self.request.principal.id, self.request)
         return self.failed()
     if nextURL is None:
         return self.confirmation()
     self.request.response.redirect(nextURL)
Ejemplo n.º 37
0
Archivo: login.py Proyecto: louika/vivi
    def __call__(self):
        logged_out = IUnauthenticatedPrincipal.providedBy(
            self.request.principal)

        if not logged_out:
            auth = zope.component.getUtility(
                zope.authentication.interfaces.IAuthentication)
            zope.authentication.interfaces.ILogout(auth).logout(self.request)
            self._delete_sso_cookies()

        return self.request.response.redirect(
            zope.traversing.browser.absoluteURL(self.context, self.request))
Ejemplo n.º 38
0
    def _maybePlacefullyAuthenticate(self, request, ob):
        if not IUnauthenticatedPrincipal.providedBy(request.principal):
            # We've already got an authenticated user. There's nothing to do.
            # Note that beforeTraversal guarentees that user is not None.
            return

        if not ISite.providedBy(ob):
            # We won't find an authentication utility here, so give up.
            return

        sm = removeSecurityProxy(ob).getSiteManager()
        self.authenticate(request, sm)
Ejemplo n.º 39
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         return u'<a href="@@login.html?nextURL=%s">%s</a>' % (
             urllib.quote(self.request.getURL()),
             translate(_('[Login]'), context=self.request,
                       default='[Login]'))
     elif ILogoutSupported(self.request, None) is not None:
         return u'<a href="@@logout.html?nextURL=%s">%s</a>' % (
             urllib.quote(self.request.getURL()),
             translate(_('[Logout]'), context=self.request,
                       default='[Logout]'))
     else:
         return None
Ejemplo n.º 40
0
 def handle_login(self, **data):
     authenticated = not IUnauthenticatedPrincipal.providedBy(
         self.request.principal, )
     if authenticated:
         camefrom = self.request.form.get('camefrom')
         if camefrom:
             self.redirect(camefrom, self.url(grok.getSite()))
         else:
             self.redirect(self.url(grok.getSite()))
         self.flash(u'Logueado!', type=u'message')
     else:
         self.status = u'Autenticación fallida'
         self.errors += (Invalid(u'Usuario y/o contraseña invalidos'), )
         self.form_reset = False
Ejemplo n.º 41
0
 def handle_login(self, **data):
     authenticated = not IUnauthenticatedPrincipal.providedBy(
         self.request.principal,
     )
     if authenticated:
         camefrom = self.request.form.get('camefrom')
         if camefrom:
             self.redirect(camefrom, self.url(grok.getSite()))
         else:
             self.redirect(self.url(grok.getSite()))
         self.flash(u'Logueado!', type=u'message')
     else:
         self.status = u'Autenticación fallida'
         self.errors += (Invalid(u'Usuario y/o contraseña invalidos'),)
         self.form_reset = False
Ejemplo n.º 42
0
def allowUnauthenticatedSession(request, duration=timedelta(minutes=10)):
    # As a rule, we do not want to send a cookie to an unauthenticated user,
    # because it breaks cacheing; and we do not want to create a session for
    # an unauthenticated user, because it unnecessarily consumes valuable
    # database resources. We have an assertion to ensure this. However,
    # sometimes we want to break the rules. To do this, first we set the
    # session cookie; then we assert that we only want it to last for a given
    # duration, so that, if the user does not log in, they can go back to
    # getting cached pages. Only after an unauthenticated user's session
    # cookie is set is it safe to write to it.
    if not IUnauthenticatedPrincipal.providedBy(request.principal):
        return
    client_id_manager = getUtility(IClientIdManager)
    if request.response.getCookie(client_id_manager.namespace) is None:
        client_id_manager.setRequestId(
            request, client_id_manager.getClientId(request))
        expireSessionCookie(request, client_id_manager, duration)
Ejemplo n.º 43
0
def allowUnauthenticatedSession(request, duration=timedelta(minutes=10)):
    # As a rule, we do not want to send a cookie to an unauthenticated user,
    # because it breaks cacheing; and we do not want to create a session for
    # an unauthenticated user, because it unnecessarily consumes valuable
    # database resources. We have an assertion to ensure this. However,
    # sometimes we want to break the rules. To do this, first we set the
    # session cookie; then we assert that we only want it to last for a given
    # duration, so that, if the user does not log in, they can go back to
    # getting cached pages. Only after an unauthenticated user's session
    # cookie is set is it safe to write to it.
    if not IUnauthenticatedPrincipal.providedBy(request.principal):
        return
    client_id_manager = getUtility(IClientIdManager)
    if request.response.getCookie(client_id_manager.namespace) is None:
        client_id_manager.setRequestId(request,
                                       client_id_manager.getClientId(request))
        expireSessionCookie(request, client_id_manager, duration)
Ejemplo n.º 44
0
 def _ensureClientId(self):
     if self._have_ensured_client_id:
         return
     # We want to make sure the browser cookie and the database both know
     # about our client id. We're doing it lazily to try and keep anonymous
     # users from having a session.
     self.store.execute("SELECT ensure_session_client_id(?)",
                        (self.client_id, ),
                        noresult=True)
     request = get_current_browser_request()
     if request is not None:
         client_id_manager = getUtility(IClientIdManager)
         if IUnauthenticatedPrincipal.providedBy(request.principal):
             # it would be nice if this could be a monitored, logged
             # message instead of an instant-OOPS.
             assert (
                 client_id_manager.namespace in request.cookies
                 or request.response.getCookie(
                     client_id_manager.namespace) is not None
             ), ('Session data should generally only be stored for '
                 'authenticated users, and for users who have just logged '
                 'out.  If an unauthenticated user has just logged out, '
                 'they should have a session cookie set for ten minutes. '
                 'This should be plenty of time for passing notifications '
                 'about successfully logging out.  Because this assertion '
                 'failed, it means that some code is trying to set '
                 'session data for an unauthenticated user who has been '
                 'logged out for more than ten minutes: something that '
                 'should not happen.  The code setting the session data '
                 'should be reviewed; and failing that, the cookie '
                 'timeout after logout (set in '
                 'webapp.login) should perhaps be '
                 'increased a bit, if a ten minute fudge factor is not '
                 'enough to handle the vast majority of computers with '
                 'not-very-accurate system clocks.  In an exceptional '
                 'case, the code may set the necessary cookies itself to '
                 'assert that yes, it *should* set the session for an '
                 'unauthenticated user.  See the webapp.login module for '
                 'an example of this, as well.')
         else:
             client_id_manager.setRequestId(request, self.client_id)
     self._have_ensured_client_id = True
Ejemplo n.º 45
0
    def maybeRestrictToTeam(self, request):
        restrict_to_team = config.launchpad.restrict_to_team
        if not restrict_to_team:
            return

        restrictedlogin = '******'
        restrictedinfo = '+restricted-info'

        # Always allow access to +restrictedlogin and +restrictedinfo.
        traversal_stack = request.getTraversalStack()
        if (traversal_stack == [restrictedlogin]
                or traversal_stack == [restrictedinfo]):
            return

        principal = request.principal
        team = getUtility(IPersonSet).getByName(restrict_to_team)
        if team is None:
            raise AssertionError('restrict_to_team "%s" not found' %
                                 restrict_to_team)
        elif not ITeam.providedBy(team):
            raise AssertionError('restrict_to_team "%s" is not a team' %
                                 restrict_to_team)

        if IUnauthenticatedPrincipal.providedBy(principal):
            location = '/%s' % restrictedlogin
        else:
            # We have a team we can work with.
            user = IPerson(principal)
            if (user.inTeam(team)
                    or user.inTeam(getUtility(ILaunchpadCelebrities).admin)):
                return
            else:
                location = '/%s' % restrictedinfo

        non_restricted_url = self.getNonRestrictedURL(request)
        if non_restricted_url is not None:
            location += '?production=%s' % urllib.quote(non_restricted_url)

        request.response.setResult('')
        request.response.redirect(location, temporary_if_possible=True)
        # Quash further traversal.
        request.setTraversalStack([])
Ejemplo n.º 46
0
    def maybeRestrictToTeam(self, request):
        restrict_to_team = config.launchpad.restrict_to_team
        if not restrict_to_team:
            return

        restrictedlogin = '******'
        restrictedinfo = '+restricted-info'

        # Always allow access to +restrictedlogin and +restrictedinfo.
        traversal_stack = request.getTraversalStack()
        if (traversal_stack == [restrictedlogin] or
            traversal_stack == [restrictedinfo]):
            return

        principal = request.principal
        team = getUtility(IPersonSet).getByName(restrict_to_team)
        if team is None:
            raise AssertionError(
                'restrict_to_team "%s" not found' % restrict_to_team)
        elif not ITeam.providedBy(team):
            raise AssertionError(
                'restrict_to_team "%s" is not a team' % restrict_to_team)

        if IUnauthenticatedPrincipal.providedBy(principal):
            location = '/%s' % restrictedlogin
        else:
            # We have a team we can work with.
            user = IPerson(principal)
            if (user.inTeam(team) or
                user.inTeam(getUtility(ILaunchpadCelebrities).admin)):
                return
            else:
                location = '/%s' % restrictedinfo

        non_restricted_url = self.getNonRestrictedURL(request)
        if non_restricted_url is not None:
            location += '?production=%s' % urllib.quote(non_restricted_url)

        request.response.setResult('')
        request.response.redirect(location, temporary_if_possible=True)
        # Quash further traversal.
        request.setTraversalStack([])
Ejemplo n.º 47
0
    def __call__(self):
        request = self.request
        principal = request.principal

        unauthenticated = IUnauthenticatedPrincipal.providedBy(principal)
        self.unauthenticated = unauthenticated
        
        camefrom = request.get('camefrom')
        if isinstance(camefrom, list):
            # this can happen on python2.6, as it changed the
            # behaviour of cgi.FieldStorage a bit.
            camefrom = camefrom[0]
        self.camefrom = camefrom
        
        if (not unauthenticated) and ('SUBMIT' in request):
            # authenticated by submitting
            request.response.redirect(camefrom or '.')
            return ''
        
        return self.index() # call template
Ejemplo n.º 48
0
 def _ensureClientId(self):
     if self._have_ensured_client_id:
         return
     # We want to make sure the browser cookie and the database both know
     # about our client id. We're doing it lazily to try and keep anonymous
     # users from having a session.
     self.store.execute(
         "SELECT ensure_session_client_id(?)", (self.client_id,),
         noresult=True)
     request = get_current_browser_request()
     if request is not None:
         client_id_manager = getUtility(IClientIdManager)
         if IUnauthenticatedPrincipal.providedBy(request.principal):
             # it would be nice if this could be a monitored, logged
             # message instead of an instant-OOPS.
             assert (client_id_manager.namespace in request.cookies or
                     request.response.getCookie(
                         client_id_manager.namespace) is not None), (
                 'Session data should generally only be stored for '
                 'authenticated users, and for users who have just logged '
                 'out.  If an unauthenticated user has just logged out, '
                 'they should have a session cookie set for ten minutes. '
                 'This should be plenty of time for passing notifications '
                 'about successfully logging out.  Because this assertion '
                 'failed, it means that some code is trying to set '
                 'session data for an unauthenticated user who has been '
                 'logged out for more than ten minutes: something that '
                 'should not happen.  The code setting the session data '
                 'should be reviewed; and failing that, the cookie '
                 'timeout after logout (set in '
                 'webapp.login) should perhaps be '
                 'increased a bit, if a ten minute fudge factor is not '
                 'enough to handle the vast majority of computers with '
                 'not-very-accurate system clocks.  In an exceptional '
                 'case, the code may set the necessary cookies itself to '
                 'assert that yes, it *should* set the session for an '
                 'unauthenticated user.  See the webapp.login module for '
                 'an example of this, as well.')
         else:
             client_id_manager.setRequestId(request, self.client_id)
     self._have_ensured_client_id = True
Ejemplo n.º 49
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         if 'loggingout' in self.request.form:
             target = '%s?loggingout=1' % self.request.URL[-2]
             self.request.response.redirect(target)
             return ''
         if self.request.method == 'POST':
             # If we got a POST then that's a problem.  We can only
             # redirect with a GET, so when we redirect after a successful
             # login, the wrong method would be used.
             # If we get a POST here, it is an application error.  We
             # must ensure that form pages require the same rights
             # as the pages that process those forms.  So, we should never
             # need to newly authenticate on a POST.
             self.request.response.setStatus(500)  # Internal Server Error
             self.request.response.setHeader('Content-type', 'text/plain')
             return ('Application error.  Unauthenticated user POSTing to '
                     'page that requires authentication.')
         # If we got any query parameters, then preserve them in the
         # new URL. Except for the BrowserNotifications
         current_url = self.request.getURL()
         while True:
             nextstep = self.request.stepstogo.consume()
             if nextstep is None:
                 break
             current_url = urlappend(current_url, nextstep)
         query_string = self.request.get('QUERY_STRING', '')
         if query_string:
             query_string = '?' + query_string
         target = self.getRedirectURL(current_url, query_string)
         # A dance to assert that we want to break the rules about no
         # unauthenticated sessions. Only after this next line is it safe
         # to use the ``addInfoNotification`` method.
         allowUnauthenticatedSession(self.request)
         self.request.response.redirect(target)
         # Maybe render page with a link to the redirection?
         return ''
     else:
         self.request.response.setStatus(403)  # Forbidden
         return self.template()
Ejemplo n.º 50
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         if 'loggingout' in self.request.form:
             target = '%s?loggingout=1' % self.request.URL[-2]
             self.request.response.redirect(target)
             return ''
         if self.request.method == 'POST':
             # If we got a POST then that's a problem.  We can only
             # redirect with a GET, so when we redirect after a successful
             # login, the wrong method would be used.
             # If we get a POST here, it is an application error.  We
             # must ensure that form pages require the same rights
             # as the pages that process those forms.  So, we should never
             # need to newly authenticate on a POST.
             self.request.response.setStatus(500)  # Internal Server Error
             self.request.response.setHeader('Content-type', 'text/plain')
             return ('Application error.  Unauthenticated user POSTing to '
                     'page that requires authentication.')
         # If we got any query parameters, then preserve them in the
         # new URL. Except for the BrowserNotifications
         current_url = self.request.getURL()
         while True:
             nextstep = self.request.stepstogo.consume()
             if nextstep is None:
                 break
             current_url = urlappend(current_url, nextstep)
         query_string = self.request.get('QUERY_STRING', '')
         if query_string:
             query_string = '?' + query_string
         target = self.getRedirectURL(current_url, query_string)
         # A dance to assert that we want to break the rules about no
         # unauthenticated sessions. Only after this next line is it safe
         # to use the ``addInfoNotification`` method.
         allowUnauthenticatedSession(self.request)
         self.request.response.redirect(target)
         # Maybe render page with a link to the redirection?
         return ''
     else:
         self.request.response.setStatus(403)  # Forbidden
         return self.template()
Ejemplo n.º 51
0
def new_import(code_import, event):
    """Email the vcs-imports team about a new code import."""
    if (event.user is None
        or IUnauthenticatedPrincipal.providedBy(event.user)):
        # If there is no logged in user, then we are most likely in a
        # test.
        return
    user = IPerson(event.user)
    subject = 'New code import: %s/%s' % (
        code_import.branch.target.name, code_import.branch.name)
    if code_import.rcs_type == RevisionControlSystems.CVS:
        location = '%s, %s' % (code_import.cvs_root, code_import.cvs_module)
    else:
        location = code_import.url
    rcs_type_map = {
        RevisionControlSystems.CVS: 'CVS',
        RevisionControlSystems.SVN: 'subversion',
        RevisionControlSystems.BZR_SVN: 'subversion',
        RevisionControlSystems.GIT: 'git',
        RevisionControlSystems.BZR: 'bazaar',
        }
    body = get_email_template('new-code-import.txt', app='code') % {
        'person': code_import.registrant.displayname,
        'branch': canonical_url(code_import.branch),
        'rcs_type': rcs_type_map[code_import.rcs_type],
        'location': location,
        }

    from_address = format_address(
        user.displayname, user.preferredemail.email)

    vcs_imports = getUtility(ILaunchpadCelebrities).vcs_imports
    headers = {'X-Launchpad-Branch': code_import.branch.unique_name,
               'X-Launchpad-Message-Rationale':
                   'Operator @%s' % vcs_imports.name,
               'X-Launchpad-Notification-Type': 'code-import',
               }
    for address in get_contact_email_addresses(vcs_imports):
        simple_sendmail(from_address, address, subject, body, headers)
Ejemplo n.º 52
0
    def login(self):
        data, errors = self.extractData()
        if errors:
            return FAILURE

        principal = self.request.principal
        if IUnauthenticatedPrincipal.providedBy(principal):
            self.status = _(u"Login failed")
            return FAILURE

        self.flash(_('You are now logged in as ${name}',
                     mapping={"name": principal.id}))
        notify(UserLoginEvent(principal))
        camefrom = self.request.get('camefrom', None)
        if not camefrom:
            if ILocation.providedBy(principal):
                camefrom = absoluteURL(principal, self.request)
            else:
                camefrom = absoluteURL(self.context, self.request)

        self.redirect(camefrom)
        return SUCCESS
Ejemplo n.º 53
0
    def authenticated(self):
        """Check whether context is an authenticated principal.

        Sample usage in a page template:

            <tal:span tal:define="user request/principal"
                      tal:condition="user/schooltool:authenticated"
                      tal:replace="user/title">
              User title
            </tal:span>
            <tal:span tal:define="user request/principal"
                      tal:condition="not:user/schooltool:authenticated">
              Anonymous
            </tal:span>

        """
        if self.context is None: # no one is logged in
            return False
        if not IPrincipal.providedBy(self.context):
            raise TypeError("schooltool:authenticated can only be applied"
                            " to a principal but was applied on %r" % self.context)
        return not IUnauthenticatedPrincipal.providedBy(self.context)
Ejemplo n.º 54
0
def new_import(code_import, event):
    """Email the vcs-imports team about a new code import."""
    if (event.user is None
            or IUnauthenticatedPrincipal.providedBy(event.user)):
        # If there is no logged in user, then we are most likely in a
        # test.
        return
    user = IPerson(event.user)
    subject = 'New code import: %s/%s' % (code_import.branch.target.name,
                                          code_import.branch.name)
    if code_import.rcs_type == RevisionControlSystems.CVS:
        location = '%s, %s' % (code_import.cvs_root, code_import.cvs_module)
    else:
        location = code_import.url
    rcs_type_map = {
        RevisionControlSystems.CVS: 'CVS',
        RevisionControlSystems.SVN: 'subversion',
        RevisionControlSystems.BZR_SVN: 'subversion',
        RevisionControlSystems.GIT: 'git',
        RevisionControlSystems.BZR: 'bazaar',
    }
    body = get_email_template('new-code-import.txt', app='code') % {
        'person': code_import.registrant.displayname,
        'branch': canonical_url(code_import.branch),
        'rcs_type': rcs_type_map[code_import.rcs_type],
        'location': location,
    }

    from_address = format_address(user.displayname, user.preferredemail.email)

    vcs_imports = getUtility(ILaunchpadCelebrities).vcs_imports
    headers = {
        'X-Launchpad-Branch': code_import.branch.unique_name,
        'X-Launchpad-Message-Rationale': 'Operator @%s' % vcs_imports.name,
        'X-Launchpad-Notification-Type': 'code-import',
    }
    for address in get_contact_email_addresses(vcs_imports):
        simple_sendmail(from_address, address, subject, body, headers)
Ejemplo n.º 55
0
    def login(self):
        data, errors = self.extractData()
        if errors:
            return FAILURE
        principal = self.request.principal
        if IUnauthenticatedPrincipal.providedBy(principal):
            self.status = _("Login failed")
            return FAILURE

        self.flash(
            _("You are now logged in as ${name}",
              mapping={"name": principal.id}))

        grok.notify(UserLoggedInEvent(principal))
        camefrom = self.request.get("camefrom", None)
        if not camefrom:
            if ILocation.providedBy(principal):
                camefrom = absoluteURL(principal, self.request)
            else:
                camefrom = absoluteURL(self.context, self.request)

        self.redirect(camefrom)
        return SUCCESS
Ejemplo n.º 56
0
def setupInteraction(principal, login=None, participation=None):
    """Sets up a new interaction with the given principal.

    The login gets added to the launch bag.

    You can optionally pass in a participation to be used.  If no
    participation is given, a Participation is used.
    """
    # If principal is None, this method acts just like endInteraction.
    if principal is None:
        endInteraction()
        return

    if principal == ANONYMOUS:
        authutil = getUtility(IPlacelessAuthUtility)
        principal = authutil.unauthenticatedPrincipal()

    if participation is None:
        participation = Participation()

    # First end any running interaction, and start a new one.
    endInteraction()
    newInteraction(participation)

    launchbag = getUtility(IOpenLaunchBag)
    if IUnauthenticatedPrincipal.providedBy(principal):
        launchbag.setLogin(None)
    else:
        launchbag.setLogin(login)

    if IPublicationRequest.providedBy(participation):
        # principal is a read-only attribute on requests.
        participation.setPrincipal(principal)
    else:
        # Try setting the attribute directly.
        participation.principal = principal
Ejemplo n.º 57
0
def setupInteraction(principal, login=None, participation=None):
    """Sets up a new interaction with the given principal.

    The login gets added to the launch bag.

    You can optionally pass in a participation to be used.  If no
    participation is given, a Participation is used.
    """
    # If principal is None, this method acts just like endInteraction.
    if principal is None:
        endInteraction()
        return

    if principal == ANONYMOUS:
        authutil = getUtility(IPlacelessAuthUtility)
        principal = authutil.unauthenticatedPrincipal()

    if participation is None:
        participation = Participation()

    # First end any running interaction, and start a new one.
    endInteraction()
    newInteraction(participation)

    launchbag = getUtility(IOpenLaunchBag)
    if IUnauthenticatedPrincipal.providedBy(principal):
        launchbag.setLogin(None)
    else:
        launchbag.setLogin(login)

    if IPublicationRequest.providedBy(participation):
        # principal is a read-only attribute on requests.
        participation.setPrincipal(principal)
    else:
        # Try setting the attribute directly.
        participation.principal = principal
Ejemplo n.º 58
0
 def __call__(self):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         self.http_status_code = 401
         self.additional_headers.update([("WWW-Authenticate",
                                          "Basic realm=Bungeni")])
     return super(Unauthorized, self).__call__()