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