Benutzer-Werkzeuge

Webseiten-Werkzeuge


python:grok-1.4-ldapauth

Dies ist eine alte Version des Dokuments!


LDAP-Auth in grok-1.4

Motivaton

Nur User des zentralen Verzeichnisses dürfen diese Webseiten anschauen. Sie müssen sich vorher mit ihrer uid anmelden. Das Attribut „cn“ aus LDAP wird als principal.title übergeben.

Voraussetzungen

grok-1.4 python-ldap

bitte testen Sie unbedingt mit der grok-Konsole, ob das Modul ldap importiert werden kann:

bin/python-console
>>> import ldap

Implementation

app.py

import grok
import rolesAndPerms
import ldapauth
 
from demo import resource
 
from zope.pluggableauth.authentication import PluggableAuthentication
from zope.authentication.interfaces import IAuthentication
 
 
class Demo(grok.Application, grok.Container):
    grok.local_utility(
         PluggableAuthentication, provides=IAuthentication,
              setup=ldapauth.setup_authentication,
                   )
 
class Index(grok.View):
    grok.require("mysite.View")
    def update(self):
        resource.style.need()
 
 
from zope.interface import Interface
 
class MyLogin(grok.Form):
    grok.context(Interface)
    grok.require('zope.Public')
 
    @grok.action('login')
    def handle_login(self, **data):
      self.redirect(self.request.form.get('camefrom',''))
 
from zope.pluggableauth.interfaces import ILogout
from zope.authentication.interfaces import IUnauthenticatedPrincipal
 
from zope.component import getUtility
class Logout(grok.View):
    grok.context(Interface)
    grok.require('zope.Public')
 
    def update(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            auth = getUtility(IAuthentication)
            ILogout(auth).logout(self.request)
    def render(self):
      return "logout successful!!"

rolesAndPerms.py

import grok
from zope.pluggableauth.interfaces import IAuthenticatedPrincipalCreated
from zope.securitypolicy.interfaces import IRolePermissionManager,IPrincipalRoleManager
 
@grok.subscribe(IAuthenticatedPrincipalCreated)
def update_principal_info_from_ldap(event):
 principal = event.principal
 app = grok.getSite()
 prm = IPrincipalRoleManager(app)
 prm.assignRoleToPrincipal('mysite.Viewer', principal.id)
 
 
class ViewDemo(grok.Permission):
    grok.name('mysite.View')
    grok.title('View this Demo') # optional
 
class Viewer(grok.Role):
    """
    A Viewer can view.
    """
    grok.name('mysite.Viewer')
    grok.title('The Viewer')
    grok.description('A Viewer.')
    grok.permissions('mysite.View')
    # alternatively, use permission names
    # grok.permissions(
    #    'paint.ViewPainting', 'paint.EditPainting', 'paint.ErasePainting')

ldapauth.py

import grok
 
 
def setup_authentication(pau):
    """Set up pluggable authentication utility.
 
    Sets up an IAuthenticatorPlugin and
    ICredentialsPlugin (for the authentication mechanism)
    """
    pau.credentialsPlugins = ['credentials']
    pau.authenticatorPlugins = ['ldapusers']
    pau.prefix = u'pau3.'
 
from zope.pluggableauth.plugins.session import SessionCredentialsPlugin
from zope.pluggableauth.interfaces import ICredentialsPlugin
 
class MyCreds(grok.GlobalUtility, SessionCredentialsPlugin):
    grok.provides(ICredentialsPlugin)
    grok.name('credentials')
 
    loginpagename = 'mylogin'
    loginfield = 'form.login'
    passwordfield = 'form.password'
 
 
from zope.pluggableauth.interfaces import IAuthenticatorPlugin
 
class UserAuthenticatorPlugin(grok.GlobalUtility):
    grok.provides(IAuthenticatorPlugin)
    grok.name('ldapusers')
 
    def authenticateCredentials(self, credentials):
        if not isinstance(credentials, dict):
            return None
        if not ('login' in credentials and 'password' in credentials):
            return None
        account = self.getAccount(credentials['login'].strip().lower())
 
        if account is None:
            return None
        if not account.checkPassword(credentials['password']):
            return None
        return PrincipalInfo(id=account.name,
                             title=account.cn,
                             description=account.cn)
 
    def principalInfo(self, id):
        account = self.getAccount(id)
        if account is None:
            return None
        return PrincipalInfo(id=account.name,
                             title=account.name,
                             description=account.name)
 
    def getAccount(self, login):
      #  ... look up the account object and return it ...
      return Account(login)
 
 
from zope.pluggableauth.interfaces import IPrincipalInfo
 
class PrincipalInfo(object):
    grok.implements(IPrincipalInfo)
 
    def __init__(self, id, title, description):
        self.id = id
        self.title = title
        self.description = description
        self.credentialsPlugin = None
        self.authenticatorPlugin = None
 
 
import ldap
from zope import component
from zope.password.interfaces import IPasswordManager
 
class Account(object):
    """ erzeugt einen account und stellt eine methode 
    checkpassword bereit, um das passwort zu testen 
 
    todo: das passwort wird bei jedem seitenaufruf ueberprueft,
    hier sollte irgendwas in der session gemerkt werden (user is
    authenticated oder sowas)
 
    """
    def __init__(self, name):
        self.name = name
        self.password = None
 
    def checkPassword(self, password):
      """ hier wird das passwort ueberprueft, kann gegen beliebige
          auth-quellen gemacht werden
 
          in diesem fall gegen ldap
      """
 
      lconn=ldap.initialize('ldaps://'+LDAPSERVER)
      if True:
        lconn.simple_bind_s()
        r=lconn.search_s(LDAPSEARCHBASE,
                            ldap.SCOPE_SUBTREE,
                            '(uid=%s)' % self.name,
                            ['cn'])
        if len(r)==1:
          dn,atts=r[0]
          try:
            lconn.simple_bind_s(dn,password)
          except:
            return False   
          self.cn=atts['cn'][0].decode('utf8')
          return True
        else:
          return False

app_templates/mylogin.pt

<html>
<head>
</head>
 
<body>
<form action=""
      method="post" class="edit-form"
      enctype="multipart/form-data">
 
  <table class="form-fields">
    <tbody>
 
        <tr>
          <td class="label">
 
            <label for="form.login">
              <span class="required">*</span><span>Username</span>
            </label>
          </td>
          <td class="field">
            <div class="widget"><input class="textType" id="form.login" name="form.login" size="20" type="text" value=""  /></div>
 
          </td>
        </tr>
 
 
        <tr>
          <td class="label">
 
            <label for="form.password">
              <span class="required">*</span><span>Password</span>
            </label>
          </td>
          <td class="field">
            <div class="widget"><input class="passwordType" id="form.password" name="form.password" size="20" type="password" value=""  /></div>
 
          </td>
        </tr>
 
    </tbody>
  </table>
 
  <div id="actionsView">
    <span class="actionButtons">
      <input type="submit" id="form.actions.login" name="form.actions.login" value="login" class="button" />
    </span>
  </div>
 
  <input tal:condition="request/camefrom | nothing" type="hidden"
       name="camefrom" tal:attributes="value request/form/camefrom | nothing" />
 
</form>
 
</body>
</html>

index.pt

<html>
<head>
</head>
<body>
  <h1>Congratulations!</h1>
 
  <p>Your Grok application is up and running.
  Edit <nowiki><code></nowiki>demo/app_templates/index.pt<nowiki>

</nowiki> to change

this page.</p>
<img tal:attributes="src static/evencaveman.jpg"/>
<p>
  <span i18n:translate="">User:
     <span tal:replace="request/principal/title"
        i18n:name="user_title">User</span>
  </span>
<a href="@@logout">Logout</a>

</body> </html> </code>

resource.py

from fanstatic import Library, Resource
 
library = Library('demo', 'static')
 
style = Resource(library, 'style.css'
python/grok-1.4-ldapauth.1319098048.txt.gz · Zuletzt geändert: 2024/08/07 13:35 (Externe Bearbeitung)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki