source: main/waeup.sirp/trunk/src/waeup/sirp/students/authentication.py @ 6756

Last change on this file since 6756 was 6756, checked in by uli, 13 years ago

Merge changes from uli-studentpw back into trunk.

File size: 9.3 KB
Line 
1##
2## authentication.py
3## Login : <uli@pu.smp.net>
4## Started on  Fri Sep  2 15:22:47 2011 Uli Fouquet
5## $Id$
6##
7## Copyright (C) 2011 Uli Fouquet
8## This program is free software; you can redistribute it and/or modify
9## it under the terms of the GNU General Public License as published by
10## the Free Software Foundation; either version 2 of the License, or
11## (at your option) any later version.
12##
13## This program is distributed in the hope that it will be useful,
14## but WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16## GNU General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with this program; if not, write to the Free Software
20## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21##
22"""
23Authenticate students.
24"""
25import grok
26from zope.component import getUtility
27from zope.password.interfaces import IPasswordManager
28from zope.pluggableauth.interfaces import (
29    IAuthenticatorPlugin, ICredentialsPlugin)
30from zope.pluggableauth.plugins.session import (
31    SessionCredentialsPlugin, SessionCredentials)
32from zope.publisher.interfaces.http import IHTTPRequest
33from zope.session.interfaces import ISession
34from waeup.sirp.authentication import PrincipalInfo, get_principal_role_manager
35from waeup.sirp.interfaces import IAuthPluginUtility, IUserAccount
36from waeup.sirp.students.interfaces import IStudent
37
38class StudentAccount(grok.Adapter):
39    """An adapter to turn student objects into accounts on-the-fly.
40    """
41    grok.context(IStudent)
42    grok.implements(IUserAccount)
43
44    @property
45    def name(self):
46        return self.context.student_id
47
48    @property
49    def password(self):
50        return getattr(self.context, 'password', None)
51
52    @property
53    def title(self):
54        return self.context.name
55
56    @property
57    def description(self):
58        return self.title
59
60    def _get_roles(self):
61        prm = get_principal_role_manager()
62        roles = [x[0] for x in prm.getRolesForPrincipal(self.name)
63                 if x[0].startswith('waeup.')]
64        return roles
65
66    def _set_roles(self, roles):
67        """Set roles for principal denoted by this account.
68        """
69        prm = get_principal_role_manager()
70        old_roles = self.roles
71        for role in old_roles:
72            # Remove old roles, not to be set now...
73            if role.startswith('waeup.') and role not in roles:
74                prm.unsetRoleForPrincipal(role, self.name)
75        for role in roles:
76            prm.assignRoleToPrincipal(role, self.name)
77        return
78
79    roles = property(_get_roles, _set_roles)
80
81    def setPassword(self, password):
82        """Set a password (LDAP-compatible) SSHA encoded.
83
84        We do not store passwords in plaintext. Encrypted password is
85        stored as unicode string.
86        """
87        passwordmanager = getUtility(IPasswordManager, 'SSHA')
88        self.context.password = u'%s' % (
89            passwordmanager.encodePassword(password))
90
91    def checkPassword(self, password):
92        """Check whether the given `password` matches the one stored.
93        """
94        if not isinstance(password, basestring):
95            return False
96        passwordmanager = getUtility(IPasswordManager, 'SSHA')
97        return passwordmanager.checkPassword(
98            self.context.password.encode('utf-8'), # turn unicode into bytes
99            password)
100
101class StudentsAuthenticatorPlugin(grok.GlobalUtility):
102    grok.implements(IAuthenticatorPlugin)
103    grok.provides(IAuthenticatorPlugin)
104    grok.name('students')
105
106    def authenticateCredentials(self, credentials):
107        """Authenticate `credentials`.
108
109        `credentials` is a tuple (login, password).
110
111        We look up students to find out whether a respective student
112        exists, then check the password and return the resulting
113        `PrincipalInfo` or ``None`` if no such student can be found.
114        """
115        if not isinstance(credentials, dict):
116            return None
117        if not ('login' in credentials and 'password' in credentials):
118            return None
119        account = self.getAccount(credentials['login'])
120
121        if account is None:
122            return None
123        if not account.checkPassword(credentials['password']):
124            return None
125        return PrincipalInfo(id=account.name,
126                             title=account.title,
127                             description=account.description)
128
129    def principalInfo(self, id):
130        """Get a principal identified by `id`.
131
132        This one is required by IAuthenticatorPlugin.
133        """
134        account = self.getAccount(id)
135        if account is None:
136            return None
137        return PrincipalInfo(id=account.name,
138                             title=account.title,
139                             description=account.description)
140
141    def getAccount(self, login):
142        """Look up a student identified by `login`. Returns an account.
143
144        Currently, we simply look up the key under which the student
145        is stored in the portal. That means we hit if login name and
146        name under which the student is stored match.
147
148        Returns not a student but an account object adapted from any
149        student found.
150
151        If no such student exists, ``None`` is returned.
152        """
153        site = grok.getSite()
154        if site is None:
155            return None
156        studentscontainer = site.get('students', None)
157        if studentscontainer is None:
158            return None
159        student = studentscontainer.get(login, None)
160        if student is None:
161            return None
162        return IUserAccount(student)
163
164class PasswordChangeCredentialsPlugin(grok.GlobalUtility,
165                                      SessionCredentialsPlugin):
166    """A session credentials plugin that handles the case of a user
167       changing his/her own password.
168
169    When users change their own password they might find themselves
170    logged out on next request.
171
172    To avoid this, we support to use a 'change password' page a bit
173    like a regular login page. That means, on each request we lookup
174    the sent data for a login field called 'student_id' and a
175    password.
176
177    If both exist, this means someone sent new credentials.
178
179    We then look for the old credentials stored in the user session.
180    If the new credentials' login (the student_id) matches the old
181    one's, we set the new credentials in session _but_ we return the
182    old credentials for the authentication plugins to check as for the
183    current request (and for the last time) the old credentials apply.
184
185    No valid credentials are returned by this plugin if one of the
186    follwing circumstances is true
187
188    - the sent request is not a regular IHTTPRequest
189
190    - the credentials to set do not match the old ones
191
192    - no credentials are sent with the request
193
194    - no credentials were set before (i.e. the user has no session
195      with credentials set before)
196
197    Therefore it is mandatory to put this plugin in the line of all
198    credentials plugins _before_ other plugins, so that the regular
199    credentials plugins can drop in as a 'fallback'.
200
201    This plugin was designed for students to change their passwords,
202    but might be used to allow password resets for other types of
203    accounts as well.
204    """
205    grok.provides(ICredentialsPlugin)
206    grok.name('student_pw_change')
207
208    loginpagename = 'login'
209    loginfield = 'student_id'
210    passwordfield = 'form.password'
211
212    def extractCredentials(self, request):
213        if not IHTTPRequest.providedBy(request):
214            return None
215        login = request.get(self.loginfield, None)
216        password = request.get(self.passwordfield, None)
217        if not login or not password:
218            return None
219        session = ISession(request)
220        sessionData = session.get(
221            'zope.pluggableauth.browserplugins')
222        old_credentials = sessionData.get('credentials', None)
223        if old_credentials is None:
224            # Password changes for already authenticated users only!
225            return None
226        if old_credentials.getLogin() != login:
227            # Special treatment only for users that change their own pw.
228            return None
229        old_credentials = {
230            'login': old_credentials.getLogin(),
231            'password': old_credentials.getPassword()}
232
233        # Set new credentials in session. These will be active on next request
234        new_credentials = SessionCredentials(login, password)
235        sessionData['credentials'] = new_credentials
236
237        # Return old credentials for this one request only
238        return old_credentials
239
240class StudentsAuthenticatorSetup(grok.GlobalUtility):
241    """Register or unregister student authentication for a PAU.
242
243    This piece is called when a new site is created.
244    """
245    grok.implements(IAuthPluginUtility)
246
247    def register(self, pau):
248        plugins = list(pau.credentialsPlugins)
249        # this plugin must come before the regular credentials plugins
250        plugins.insert(0, 'student_pw_change')
251        pau.credentialsPlugins = tuple(plugins)
252        plugins = list(pau.authenticatorPlugins)
253        plugins.append('students')
254        pau.authenticatorPlugins = tuple(plugins)
255        return pau
256
257    def unregister(self, pau):
258        plugins = [x for x in pau.authenticatorPlugins
259                   if x != 'students']
260        pau.authenticatorPlugins = tuple(plugins)
261        return pau
Note: See TracBrowser for help on using the repository browser.