Tip: Click lines to highlight, hold ctrl/cmd to multi-select

http://codedumper.com/ixele (24-May @ 05:28)

Syntax Highlighted Code

  1. import grok
  2. from urllib import urlencode
  3. from zope.interface import Interface, implements, classImplements
  4. from zope.component import getUtility, provideAdapter
  5. from zope.app.authentication import PluggableAuthentication
  6. from zope.app.authentication.principalfolder import PrincipalFolder
  7. from zope.app.authentication.principalfolder import InternalPrincipal
  8. from zope.app.authentication.session import SessionCredentialsPlugin
  9. # XXX: Failed attempt to display the password_encoding field
  10. # from zope.app.form.browser.source import SourceDropdownWidget
  11. from zope.app.security.interfaces import IAuthentication
  12. from zope.app.security.interfaces import IUnauthenticatedPrincipal
  13. from zope.app.securitypolicy.interfaces import IPrincipalPermissionManager
  14. from zope.annotation.interfaces import IAttributeAnnotatable
  15. from zope.i18n import MessageFactory
  16.  
  17.  
  18. from interfaces import IUser, UserDataAdapter  
  19.  
  20. _ = MessageFactory('logindemo')
  21.  
  22. def setup_pau(pau):
  23.     '''
  24.    Callback to setup the Pluggable Authentication Utility
  25.       A reference to this function is passed as a parameter in the
  26.    declaration of the PAU (see LoginDemo class)
  27.    '''
  28.     # the principal source is a PrincipalFolder, stored in ZODB
  29.     pau['principals'] = PrincipalFolder()
  30.     pau.authenticatorPlugins = ('principals',)
  31.     # the SessionCredentialsPlugin isused for cookie-based authentication
  32.     pau['session'] = session = SessionCredentialsPlugin()
  33.     session.loginpagename = 'login' # the page to redirect for login
  34.     # configuration of the credentials plugin
  35.     pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
  36.        
  37. class LoginDemo(grok.Application, grok.Container):
  38.     """
  39.    An app that lets you create an account and change your password.
  40.    """
  41.     # register the authentication utility; see setup_pau for settings
  42.     grok.local_utility(PluggableAuthentication, IAuthentication,
  43.                        setup=setup_pau)
  44.     # make InternalPrincipal instances annotatable
  45.     classImplements(InternalPrincipal,IAttributeAnnotatable)
  46.     # register the adapter for IInternalPrincipal which provides IUser
  47.     provideAdapter(UserDataAdapter)
  48.            
  49. class ViewMemberListing(grok.Permission):
  50.     ''' Permission to see the member listing '''
  51.     grok.name('logindemo.ViewMemberListing')
  52.  
  53. class Master(grok.View):
  54.     """
  55.    The master page template macro.
  56.    
  57.    The template master.pt is used as page macro in most views. Since this
  58.    template uses the logged_in method and message attributes below, it's best
  59.    to make all other views in this app subclasses of Master.
  60.    """
  61.     grok.context(Interface)  # register this view for all objects
  62.  
  63.     message = '' # used to give feedback
  64.  
  65.     def logged_in(self):
  66.         # this is the canonical way to tell whether the user is authenticated
  67.         # in Zope 3: check if the principal provides IUnauthenticatedPrincipal
  68.         return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
  69.    
  70. class Index(Master):
  71.     """
  72.    The main page, showing user data and member count.
  73.    """
  74.  
  75.     def members(self):
  76.         # get the authentication utility
  77.         pau = getUtility(IAuthentication)
  78.         result = len(pau['principals'])
  79.         if result == 0:
  80.             return _(u'No one has')
  81.         elif result == 1:
  82.             return _(u'One member has')
  83.         else:
  84.             return unicode(result) + _(u' members have')
  85.  
  86.    
  87. class Login(Master):
  88.     """
  89.    Login form and handler.
  90.    """
  91.     def update(self, login_submit=None):
  92.         if login_submit is not None: # we are handling the login submission
  93.             if self.logged_in(): # if the login was accepted then...
  94.                 # redirect to where the user came from, or to the main page
  95.                 dest = self.request.get('camefrom', self.application_url())
  96.                 self.redirect(dest)
  97.             else: # if the user is still not logged in...
  98.                 # then an incorrect login or password was provided
  99.                 self.message = _(u'Invalid login name and/or password')
  100.  
  101. class Logout(grok.View):
  102.     """
  103.    Logout handler.
  104.    """
  105.     grok.context(Interface)
  106.     def render(self):
  107.         # get the session plugin and tell it to logout
  108.         session = getUtility(IAuthentication)['session']
  109.         session.logout(self.request)
  110.         # redirect to the main page
  111.         self.redirect(self.application_url())
  112.        
  113. class Join(grok.AddForm, Master):
  114.     """
  115.    User registration form.
  116.    """
  117.     form_fields = grok.AutoFields(IUser)
  118.     # XXX: Failed attempt to display the password_encoding field
  119.     #form_fields[u'password_encoding'].custom_widget = SourceDropdownWidget
  120.     label = u'User registration'
  121.     template = grok.PageTemplateFile('form.pt')
  122.    
  123.     @grok.action('Save')
  124.     def save(self, **data):
  125.         '''
  126.        Create an InternalPrincipal with the user data.
  127.        
  128.        This method also sets extra fields using an annotations through
  129.        the IUser adapter, and grants the ViewMemberListing permission to
  130.        the principal just created.
  131.        '''
  132.         login = data['login']
  133.         pau = getUtility(IAuthentication)
  134.         principals = pau['principals']
  135.         # create an instance of InternalPrincipal
  136.         principal = InternalPrincipal(login, data['password'], data['name'],
  137.                                       passwordManagerName='SHA1')
  138.         # add principal to principal folder; we may assume that the login
  139.         # name is unique because of validation on the IUser interface
  140.         # but to be doubly sure, we assert this
  141.         assert(login not in principals)
  142.         principals[login] = principal
  143.         # save the e-mail
  144.         user = IUser(principal)
  145.         user.email = data['email']
  146.         # grant the user permission to view the member listing
  147.         permission_mngr = IPrincipalPermissionManager(grok.getSite())
  148.         permission_mngr.grantPermissionToPrincipal(
  149.            'logindemo.ViewMemberListing', principals.prefix + login)
  150.  
  151.         self.redirect(self.url('login')+'?'+urlencode({'login':login}))
  152.                    
  153. class Account(grok.View):
  154.    
  155.     def render(self):
  156.         return 'Not implemented'
  157.    
  158. class Listing(Master):
  159.     '''
  160.    Member listing view. This demonstrates how to require a permission to view, and also how to
  161.    obtain a list of annotated principals.
  162.    '''
  163.  
  164.     grok.require('logindemo.ViewMemberListing')
  165.  
  166.     def fieldNames(self):
  167.         return (f for f in IUser)
  168.  
  169.     def members(self):
  170.         pau = getUtility(IAuthentication)
  171.         principals = pau['principals']
  172.         roster = []
  173.         for id in sorted(principals.keys()):
  174.             # adapt the principals to IUser to get all fields
  175.             user = IUser(principals[id])
  176.             fields = {}
  177.             for field in IUser:
  178.                 fields[field] = getattr(user, field)
  179.             roster.append(fields)
  180.         return roster
  181.  
  182.  

Plain Code

import grok
from urllib import urlencode
from zope.interface import Interface, implements, classImplements
from zope.component import getUtility, provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.app.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory


from interfaces import IUser, UserDataAdapter  

_ = MessageFactory('logindemo')

def setup_pau(pau):
    '''
    Callback to setup the Pluggable Authentication Utility
       A reference to this function is passed as a parameter in the
    declaration of the PAU (see LoginDemo class)
    '''
    # the principal source is a PrincipalFolder, stored in ZODB
    pau['principals'] = PrincipalFolder() 
    pau.authenticatorPlugins = ('principals',)
    # the SessionCredentialsPlugin isused for cookie-based authentication
    pau['session'] = session = SessionCredentialsPlugin()
    session.loginpagename = 'login' # the page to redirect for login
    # configuration of the credentials plugin
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
        
class LoginDemo(grok.Application, grok.Container):
    """
    An app that lets you create an account and change your password.
    """
    # register the authentication utility; see setup_pau for settings
    grok.local_utility(PluggableAuthentication, IAuthentication,
                       setup=setup_pau)
    # make InternalPrincipal instances annotatable
    classImplements(InternalPrincipal,IAttributeAnnotatable)
    # register the adapter for IInternalPrincipal which provides IUser
    provideAdapter(UserDataAdapter)
           
class ViewMemberListing(grok.Permission):
    ''' Permission to see the member listing '''
    grok.name('logindemo.ViewMemberListing')

class Master(grok.View):
    """
    The master page template macro.
    
    The template master.pt is used as page macro in most views. Since this
    template uses the logged_in method and message attributes below, it's best
    to make all other views in this app subclasses of Master.
    """
    grok.context(Interface)  # register this view for all objects

    message = '' # used to give feedback

    def logged_in(self):
        # this is the canonical way to tell whether the user is authenticated
        # in Zope 3: check if the principal provides IUnauthenticatedPrincipal
        return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
    
class Index(Master):
    """
    The main page, showing user data and member count.
    """

    def members(self):
        # get the authentication utility
        pau = getUtility(IAuthentication)
        result = len(pau['principals'])
        if result == 0:
            return _(u'No one has')
        elif result == 1:
            return _(u'One member has')
        else:
            return unicode(result) + _(u' members have')

    
class Login(Master):
    """
    Login form and handler.
    """
    def update(self, login_submit=None):
        if login_submit is not None: # we are handling the login submission
            if self.logged_in(): # if the login was accepted then...
                # redirect to where the user came from, or to the main page
                dest = self.request.get('camefrom', self.application_url())
                self.redirect(dest)
            else: # if the user is still not logged in...
                # then an incorrect login or password was provided
                self.message = _(u'Invalid login name and/or password')

class Logout(grok.View):
    """
    Logout handler.
    """
    grok.context(Interface)
    def render(self):
        # get the session plugin and tell it to logout
        session = getUtility(IAuthentication)['session']
        session.logout(self.request)
        # redirect to the main page
        self.redirect(self.application_url())
        
class Join(grok.AddForm, Master):
    """
    User registration form.
    """
    form_fields = grok.AutoFields(IUser)
    # XXX: Failed attempt to display the password_encoding field
    #form_fields[u'password_encoding'].custom_widget = SourceDropdownWidget
    label = u'User registration'
    template = grok.PageTemplateFile('form.pt')
    
    @grok.action('Save')
    def save(self, **data):
        '''
        Create an InternalPrincipal with the user data.
        
        This method also sets extra fields using an annotations through
        the IUser adapter, and grants the ViewMemberListing permission to
        the principal just created.
        '''
        login = data['login']
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        # create an instance of InternalPrincipal
        principal = InternalPrincipal(login, data['password'], data['name'],
                                      passwordManagerName='SHA1')
        # add principal to principal folder; we may assume that the login
        # name is unique because of validation on the IUser interface
        # but to be doubly sure, we assert this
        assert(login not in principals)
        principals[login] = principal
        # save the e-mail
        user = IUser(principal)
        user.email = data['email']
        # grant the user permission to view the member listing
        permission_mngr = IPrincipalPermissionManager(grok.getSite())
        permission_mngr.grantPermissionToPrincipal(
           'logindemo.ViewMemberListing', principals.prefix + login)

        self.redirect(self.url('login')+'?'+urlencode({'login':login}))
                    
class Account(grok.View):
    
    def render(self):
        return 'Not implemented'
    
class Listing(Master):
    '''
    Member listing view. This demonstrates how to require a permission to view, and also how to
    obtain a list of annotated principals.
    '''

    grok.require('logindemo.ViewMemberListing')

    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        roster = []
        for id in sorted(principals.keys()):
            # adapt the principals to IUser to get all fields
            user = IUser(principals[id])
            fields = {}
            for field in IUser:
                fields[field] = getattr(user, field)
            roster.append(fields)
        return roster

Permalink: http://codedumper.com/ixele