Пример #1
0
 def entries(self):
     context = self.context
     user = authenticated_user(self.request)
     entries = get_current_registry().getAdapters((context, user, self.request), ILocalMenuEntry)
     entries = [ entry[1] for entry in entries ]
     while not entries and context is not None:
         context = context.__parent__
         entries = get_current_registry().getAdapters((context, user, self.request), ILocalMenuEntry)
         entries = [ entry[1] for entry in entries ]
     
     entries = [ entry for entry in entries if entry.condition ]
     entries = sorted(entries, key=lambda entry: entry.weight)
     return entries
Пример #2
0
    def entries(self):
        context = self.context
        user = authenticated_user(self.request)
        entries = get_current_registry().getAdapters(
            (context, user, self.request), ILocalMenuEntry)
        entries = [entry[1] for entry in entries]
        while not entries and context is not None:
            context = context.__parent__
            entries = get_current_registry().getAdapters(
                (context, user, self.request), ILocalMenuEntry)
            entries = [entry[1] for entry in entries]

        entries = [entry for entry in entries if entry.condition]
        entries = sorted(entries, key=lambda entry: entry.weight)
        return entries
Пример #3
0
 def entries(self):
     user = authenticated_user(self.request)
     entries = get_current_registry().getAdapters((user, self.request), IGlobalMenuEntry)
     entries = [ entry[1] for entry in entries ]
     entries = [ entry for entry in entries if entry.condition ]
     entries = sorted(entries, key=lambda entry: entry.weight)
     return entries
Пример #4
0
    def test___call__bad_key(self):
        # register dummy renderer for the email template
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template('templates/reset_failed.pt')

        request = self.request
        # no key
        controller = self._makeOne(self.context, request)
        response = controller()
        from webob.response import Response
        self.assertEqual(response.__class__, Response)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset URL Problem')

        # reset renderer.api value so we know the test is useful
        renderer = config.testing_add_template('templates/reset_failed.pt')
        # key of wrong length
        request.params['key'] = 'foofoofoo'
        controller = self._makeOne(self.context, request)
        response = controller()
        from webob.response import Response
        self.assertEqual(response.__class__, Response)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset URL Problem')
Пример #5
0
    def test_handle_submit_wrong_key(self):
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template('templates/reset_failed.pt')
        request = self.request
        request.params['key'] = '0' * 40
        self._setupUsers()
        context = self.context
        context['profiles'] = testing.DummyModel()
        context['profiles']['me'] = testing.DummyModel()
        controller = self._makeOne(context, request)
        converted = {'login': '******'}
        # first w/ no profile reset key
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Problem')

        # now w/ wrong profile reset key
        renderer = config.testing_add_template('templates/reset_failed.pt')
        context['profiles']['me'].password_reset_key = '1' * 40
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Problem')
Пример #6
0
    def send(self, recipient, subject, body, attachments=[], sender=None):
        
        if not sender:
            settings = get_settings()
            sender = settings.get('from_mail_address')

        if attachments:
            msg = email.MIMEMultipart.MIMEMultipart()
            msg.attach(email.MIMEText.MIMEText(body.encode('UTF-8'), 'plain', 'UTF-8'))
        
            for name, fd in attachments:
                part = email.MIMEBase.MIMEBase('application', "octet-stream")
                part.set_payload(fd.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 
                                'attachment; filename="%s"' % name)
                msg.attach(part)
        else:
            msg = email.MIMEText.MIMEText(body.encode('UTF-8'), 'plain', 'UTF-8')
    
        msg["From"] = sender
        msg["To"] = recipient.encode('utf-8')
        msg["Subject"] = email.Header.Header(subject.encode('UTF-8'), 'UTF-8')

        mailer = get_current_registry().getUtility(IMailDelivery)
        mailer.send(sender, [recipient.encode('UTF-8')], msg)
Пример #7
0
    def test_handle_submit_key_expired(self):
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template('templates/reset_failed.pt')
        request = self.request
        request.params['key'] = '0' * 40
        self._setupUsers()
        context = self.context
        context['profiles'] = testing.DummyModel()
        profile = context['profiles']['me'] = testing.DummyModel()
        profile.password_reset_key = '0' * 40
        controller = self._makeOne(context, request)
        converted = {'login': '******'}
        # first w/ no profile reset time
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Key Expired')

        # now w/ expired key
        renderer = config.testing_add_template('templates/reset_failed.pt')
        from karl.views.resetpassword import max_reset_timedelta
        import datetime
        keytime = datetime.datetime.now() - max_reset_timedelta
        profile.password_reset_time = keytime
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Key Expired')
Пример #8
0
 def test_handle_submit_utf8_password(self):
     password = u'password\xe1'
     reg = get_current_registry()
     config = Configurator(reg)
     renderer = config.testing_add_template('templates/reset_complete.pt')
     request = self.request
     request.params['key'] = '0' * 40
     self._setupUsers()
     context = self.context
     context['profiles'] = testing.DummyModel()
     profile = context['profiles']['me'] = testing.DummyModel()
     profile.password_reset_key = '0' * 40
     controller = self._makeOne(context, request)
     converted = {'login': '******', 'password': password}
     import datetime
     keytime = datetime.datetime.now()
     profile.password_reset_time = keytime
     response = controller.handle_submit(converted)
     self.failUnless(hasattr(renderer, 'api'))
     self.assertEqual(renderer.api.page_title,
                      'Password Reset Complete')
     renderer.assert_(login='******', password=password)
     self.failUnless(profile.password_reset_key is None)
     self.failUnless(profile.password_reset_time is None)
     user = self.context.users.get(login='******')
     from repoze.who.plugins.zodb.users import get_sha_password
     self.assertEqual(user['password'], get_sha_password(password.encode('utf8')))
Пример #9
0
 def _registerComponents(self):
     # Install a bit of configuration that make_app() usually
     # does for us.
     reg = get_current_registry()
     config = Configurator(reg)
     config.setup_registry()
     config.load_zcml('opencore.includes:configure.zcml')
Пример #10
0
def route_url(route_name, request, *elements, **kw):
    """
    This is culted from repoze.bfg.url. I just didn't want the path segments (shorturl) percent encoded.
    Read the docstring in repoze.bfg.url for details.
    """
    try:
        reg = request.registry
    except AttributeError:
        reg = get_current_registry()  # b/c
    mapper = reg.getUtility(IRoutesMapper)

    anchor = ""
    qs = ""

    if "_query" in kw:
        qs = "?" + urlencode(kw.pop("_query"), doseq=True)

    if "_anchor" in kw:
        anchor = kw.pop("_anchor")
        if isinstance(anchor, unicode):
            anchor = anchor.encode("utf-8")
        anchor = "#" + anchor

    path = mapper.generate(route_name, kw)  # raises KeyError if generate fails

    if elements:
        suffix = _join_elements(elements)
        if not path.endswith("/"):
            suffix = "/" + suffix
    else:
        suffix = ""

    return request.application_url + path + suffix + qs + anchor
Пример #11
0
def register_skin_object(relative_path, path, request_type):
    registry = get_current_registry()

    ext = os.path.splitext(path)[1]
    factory = registry.queryUtility(ISkinObjectFactory, name=ext) or \
              SkinObject

    name = factory.component_name(relative_path)

    if request_type is not None:
        inst = registry.adapters.lookup(
            (request_type, ), ISkinObject, name=name, default=None
            )
    else:
        inst = registry.queryUtility(ISkinObject, name=name)

    if inst is not None:
        inst.path = path
        if request_type is not None:
            inst(request_type).refresh()
        else:
            inst.refresh()
    else:
        inst = factory(relative_path, path)

        def adapter(request):
            return inst

        if request_type is not None:
            registry.registerAdapter(
                adapter, (request_type, ), ISkinObject, name=name
                )
        else:
            registry.registerUtility(inst, ISkinObject, name)
Пример #12
0
 def entries(self):
     user = authenticated_user(self.request)
     entries = get_current_registry().getAdapters((user, self.request),
                                                  IGlobalMenuEntry)
     entries = [entry[1] for entry in entries]
     entries = [entry for entry in entries if entry.condition]
     entries = sorted(entries, key=lambda entry: entry.weight)
     return entries
Пример #13
0
def _find_view(context, request, name):
    # Cribbed from repoze.bfg.view.render_view_to_response
    provides = map(providedBy, (request, context))
    try:
        reg = request.registry
    except AttributeError:
        reg = get_current_registry()
    return reg.adapters.lookup(provides, IView, name=name)
Пример #14
0
 def _registerComponents(self):
     # Install a bit of configuration that make_app() usually
     # does for us.
     reg = get_current_registry()
     config = Configurator(reg)
     config.setup_registry()
     config.load_zcml('karl.includes:configure.zcml')
     from zope.interface import Interface
     testing.registerAdapter(DummyToolAddables, (Interface, Interface),
                             IToolAddables)
Пример #15
0
def logged_in_view(context, request):
    
    user = authenticated_user(request)
    
    # Direct to the url of the "home" menu item which is user type specific.
    home_entry = get_current_registry().queryMultiAdapter((user, request), IGlobalMenuEntry, name="home")
    if home_entry:
        return HTTPFound(location = home_entry.url)
    else:
        return HTTPFound(location = model_url(context, request, 'login.html', query={'login_failed' : '1'}))
Пример #16
0
 def test_handle_submit_bad_key(self):
     reg = get_current_registry()
     config = Configurator(reg)
     renderer = config.testing_add_template('templates/reset_failed.pt')
     request = self.request
     request.params['key'] = 'foofoofoo'
     controller = self._makeOne(self.context, request)
     response = controller.handle_submit({})
     self.failUnless(hasattr(renderer, 'api'))
     self.assertEqual(renderer.api.page_title,
                      'Password Reset URL Problem')
Пример #17
0
 def __acl__(self):
     """
     Returns ACL for this object.
     """
     acl = []
     
     adapter = get_current_registry().queryAdapter(self, IPermissionProvider)
     if adapter:
         acl = adapter.acl()
     
     return acl
Пример #18
0
    def __acl__(self):
        """
        Returns ACL for this object.
        """
        acl = []

        adapter = get_current_registry().queryAdapter(self,
                                                      IPermissionProvider)
        if adapter:
            acl = adapter.acl()

        return acl
Пример #19
0
    def __init__(self, context, path=None, discovery=False, request_type=None):
        self.registry = get_current_registry()
        self.context = context
        self.path = os.path.realpath(path).encode('utf-8')
        self.views = []
        self.request_type = Configurator(self.registry, package=package).\
                            maybe_dotted(request_type)

        if discovery:
            thread = self.threads.get(id(self.registry))
            if thread is None:
                thread = self.threads[id(self.registry)] = Discoverer()
            thread.watch(self.path, self)
Пример #20
0
def logged_in_view(context, request):

    user = authenticated_user(request)

    # Direct to the url of the "home" menu item which is user type specific.
    home_entry = get_current_registry().queryMultiAdapter((user, request),
                                                          IGlobalMenuEntry,
                                                          name="home")
    if home_entry:
        return HTTPFound(location=home_entry.url)
    else:
        return HTTPFound(location=model_url(
            context, request, 'login.html', query={'login_failed': '1'}))
Пример #21
0
    def send_password_reset(self, reset_url):
        # Send password e-mail to user if password field is empty
        key = self.password_reset_key()
        reset_url = '%s?key=%s' % (reset_url, key)
        mail_text = chameleon_text.render_template('eportfolio:views/templates/pw_reset_mail.txt',
                                                   reset_url=reset_url,
                                                   first_name=self.first_name,
                                                   last_name=self.last_name)

        mail_service = get_current_registry().getUtility(IMailService)

        mail_service.send('%s %s <%s>' % (self.first_name, self.last_name, self.email),
            u'COBAL e-Portfolio Passwort',
            mail_text)
Пример #22
0
def register_skin_view(relative_path, path, kwargs):
    registry = get_current_registry()

    for inst in registry.getAllUtilitiesRegisteredFor(ISkinObject):
        if inst.path == path:
            break
    else:
        raise RuntimeError("Skin object not found: %s." % relative_path)

    name = type(inst).component_name(relative_path).replace('/', '_')

    context = ConfigurationMachine()
    register_bfg_view(
        context, name=name, view=inst, **kwargs)
    context.execute_actions()
Пример #23
0
    def send_password_reset(self, reset_url):
        # Send password e-mail to user if password field is empty
        key = self.password_reset_key()
        reset_url = '%s?key=%s' % (reset_url, key)
        mail_text = chameleon_text.render_template(
            'eportfolio:views/templates/pw_reset_mail.txt',
            reset_url=reset_url,
            first_name=self.first_name,
            last_name=self.last_name)

        mail_service = get_current_registry().getUtility(IMailService)

        mail_service.send(
            '%s %s <%s>' % (self.first_name, self.last_name, self.email),
            u'COBAL e-Portfolio Passwort', mail_text)
Пример #24
0
def registerTile(
    name, path=None, attribute="render", interface=Interface, class_=Tile, permission="view", strict=True, _level=2
):
    """registers a tile.
    
    ``name``
        identifier of the tile (for later lookup).
    
    ``path``
        either relative path to the template or absolute path or path prefixed
        by the absolute package name delimeted by ':'. If ``path`` is used
        ``attribute`` is ignored. 
        
    ``attribute``
        attribute on the given _class to be used to render the tile. Defaults to
        ``render``.
        
    ``interface`` 
        Interface or Class of the bfg model the tile is registered for.
        
    ``class_``
        Class to be used to render the tile. usally ``bda.bfg.tile.Tile`` or a
        subclass of. Promises to implement ``bda.bfg.ITile``.
        
    ``permission`` 
        Enables security checking for this tile. Defaults to ``view``. If set to
        ``None`` security checks are disabled.
        
    ``strict``
        Wether to raise ``Forbidden`` or not. Defaults to ``True``. If set to 
        ``False`` the exception is consumed and an empty unicode string is 
        returned.

    ``_level`` 
        is a bit special to make doctests pass the magic path-detection.
        you must never touch it in application code.
    """
    if path and not (":" in path or os.path.isabs(path)):
        path = "%s:%s" % (caller_package(_level).__name__, path)
    tile = class_(path, attribute, name)
    registry = get_current_registry()
    if permission is not None:
        authn_policy = registry.queryUtility(IAuthenticationPolicy)
        authz_policy = registry.queryUtility(IAuthorizationPolicy)
        tile = _secure_tile(tile, permission, authn_policy, authz_policy, strict)
    registry.registerAdapter(tile, [interface, IRequest], ITile, name, event=False)
Пример #25
0
def route_url(route_name, request, *elements, **kw):
    try:
        reg = request.registry
    except AttributeError:
        reg = get_current_registry()  # b/c
    mapper = reg.getUtility(IRoutesMapper)

    route = mapper.routes.get(route_name)
    if route and 'custom_url_generator' in route.__dict__:
        route_name, request, elements, kw = route.custom_url_generator(
            route_name, request, *elements, **kw)
    anchor = ''
    qs = ''
    app_url = None

    if '_query' in kw:
        qs = '?' + urlencode(kw.pop('_query'), doseq=True)

    if '_anchor' in kw:
        anchor = kw.pop('_anchor')
        if isinstance(anchor, unicode):
            anchor = anchor.encode('utf-8')
        anchor = '#' + anchor

    if '_app_url' in kw:
        app_url = kw.pop('_app_url')

    path = mapper.generate(route_name, kw)  # raises KeyError if generate fails

    if elements:
        suffix = _join_elements(elements)
        if not path.endswith('/'):
            suffix = '/' + suffix
    else:
        suffix = ''

    if app_url is None:
        # we only defer lookup of application_url until here because
        # it's somewhat expensive; we won't need to do it if we've
        # been passed _app_url
        app_url = request.application_url

    return app_url + path + suffix + qs + anchor
Пример #26
0
    def traverse_view(self, path, REQUEST=None):
        viewdef = traverse(self, path)
        if REQUEST is None:
            REQUEST = self._request()
        request = REQUEST
        #gsm = registry._registry
        #/gsm = zope.component.getSiteManager()
        try:
            reg = request.registry
        except AttributeError:
            reg = get_current_registry()

        context = viewdef['context']
        name = viewdef['view_name']
        provides = map(providedBy, (request, context))  #BREAKPOINT()
        #view = gsm.getMultiAdapter((c,REQUEST),repoze.bfg.interfaces.IView,n)
        view = reg.adapters.lookup(provides,
                                   repoze.bfg.interfaces.IView,
                                   name=name)
        return view(context, request)
Пример #27
0
    def resolve(self, context, request, notag=False):

        #BREAKPOINT()

        container = context
        if context.kind() not in ['Folder', 'Root']:
            container = context.getParent()

        ac = utils.ActionContext(
            request, {
                'context': context,
                'object': context,
                'request': request,
                'container': container
            })
        expr = self.engine.compile(self.expr)
        name = expr(ac)

        #gsm = zope.component.getSiteManager()
        try:
            reg = request.registry
        except AttributeError:
            reg = get_current_registry()
        pc = PortletContext(context, self)
        provides = map(zope.interface.providedBy, (request, pc))
        #objs = map(zope.interface.providedBy,(PortletContext(context,self),request))
        #result = zope.component.queryMultiAdapter((PortletContext(context,self),request),repoze.bfg.interfaces.IView,name)
        #result = reg.queryMultiAdapter((PortletContext(context,self),request),repoze.bfg.interfaces.IView)
        #result = reg.queryMultiAdapter((PortletContext(context,self),request),interfaces.IPortlet,name)
        #result = zope.component.queryMultiAdapter(objs,repoze.bfg.interfaces.IView,name)
        result = reg.adapters.lookup(provides,
                                     repoze.bfg.interfaces.IView,
                                     name=name)

        if result is None:
            result = ""
        else:
            result = result(pc, request)
        #logging.info('***resolved portlet (%s): %s - %s' % (name,type(result),repr(result)))
        return result
Пример #28
0
 def local_menu(self):
     menu = get_current_registry().queryMultiAdapter((self.request.context, self.request), ILocalMenu)
     if menu:
         return menu.render()
     return ''
Пример #29
0
def debug_asm():
    print_adapters(getSiteManager())    
    print_adapters(get_current_registry())
Пример #30
0
    def test_handle_submit(self):
        context = self.context
        request = self.request

        # fake the mailer
        from repoze.sendmail.interfaces import IMailDelivery
        from karl.testing import DummyMailer
        mailer = DummyMailer()
        testing.registerUtility(mailer, IMailDelivery)

        # fake catalog search
        from karl.models.interfaces import ICatalogSearch
        from zope.interface import Interface
        testing.registerAdapter(
            DummyProfileSearch, (Interface,), ICatalogSearch)

        # fake a staff user
        from karl.testing import DummyUsers
        context.users = DummyUsers()
        context.users.add('me', 'me', 'password', ['group.KarlStaff'])

        # register dummy renderer for email template
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template(
            'templates/email_reset_password.pt')

        # test w/ staff user
        controller = self._makeOne(context, request)
        converted = {'email': '*****@*****.**'}
        response = controller.handle_submit(converted)
        self.failIf(len(mailer))
        self.assertEqual(response.location,
            'http://login.example.com/resetpassword?email=me%40example.com'
            '&came_from=http%3A%2F%2Fexample.com%2Flogin.html')

        # register dummy profile search
        profile_search = DummyProfileSearch(context)
        def search_adapter(context):
            return profile_search
        testing.registerAdapter(search_adapter, (Interface,), ICatalogSearch)

        # convert to non-staff user and test again, email should
        # go out this time
        context.users._by_id['me']['groups'] = []
        response = controller.handle_submit(converted)
        self.assertEqual(response.location,
            'http://example.com/reset_sent.html?email=me%40example.com')
        profile = profile_search.profile
        self.failUnless(profile.password_reset_key)
        self.failUnless(profile.password_reset_time)
        self.assertEqual(len(mailer), 1)
        msg = mailer.pop()
        self.assertEqual(len(msg.mto), 1)
        self.assertEqual(msg.mto[0], '*****@*****.**')
        self.assertEqual(dict(msg.msg._headers)['Subject'],
                         'karl3test Password Reset Request')
        renderer.assert_(login='******', system_name='karl3test')
        self.failUnless(hasattr(renderer, 'reset_url'))
        self.failUnless(renderer.reset_url.startswith(
            'http://example.com/reset_confirm.html?key='), renderer.reset_url)
Пример #31
0
 def global_menu(self):
     menu = get_current_registry().queryAdapter(self.request, IGlobalMenu)
     if menu:
         return menu.render()
     return ''
Пример #32
0
def debug_sm():
    
    print_utils(getSiteManager())    
    print_utils(get_current_registry())
Пример #33
0
 def local_menu(self):
     menu = get_current_registry().queryMultiAdapter(
         (self.request.context, self.request), ILocalMenu)
     if menu:
         return menu.render()
     return ''
Пример #34
0
 def global_menu(self):
     menu = get_current_registry().queryAdapter(self.request, IGlobalMenu)
     if menu:
         return menu.render()
     return ''