[7193] | 1 | ## $Id: authentication.py 17528 2023-08-01 06:40:01Z 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 | ## |
---|
[7819] | 18 | """Authentication for Kofa. |
---|
[4073] | 19 | """ |
---|
| 20 | import grok |
---|
[10055] | 21 | import time |
---|
[15286] | 22 | import re |
---|
| 23 | from zope.i18n import translate |
---|
[7169] | 24 | from zope.event import notify |
---|
[5900] | 25 | from zope.component import getUtility, getUtilitiesFor |
---|
[8973] | 26 | from zope.component.interfaces import IFactory |
---|
[10055] | 27 | from zope.interface import Interface, implementedBy |
---|
[8756] | 28 | from zope.schema import getFields |
---|
[7169] | 29 | from zope.securitypolicy.interfaces import ( |
---|
| 30 | IPrincipalRoleMap, IPrincipalRoleManager) |
---|
[7233] | 31 | from zope.pluggableauth.factories import Principal |
---|
[6610] | 32 | from zope.pluggableauth.plugins.session import SessionCredentialsPlugin |
---|
[14667] | 33 | from zope.pluggableauth.plugins.httpplugins import ( |
---|
[14669] | 34 | HTTPBasicAuthCredentialsPlugin) |
---|
[6610] | 35 | from zope.pluggableauth.interfaces import ( |
---|
[14669] | 36 | ICredentialsPlugin, IAuthenticatorPlugin, IAuthenticatedPrincipalFactory, |
---|
| 37 | AuthenticatedPrincipalCreated) |
---|
[7233] | 38 | from zope.publisher.interfaces import IRequest |
---|
[6610] | 39 | from zope.password.interfaces import IPasswordManager |
---|
[4129] | 40 | from zope.securitypolicy.principalrole import principalRoleManager |
---|
[14669] | 41 | from waeup.kofa.interfaces import ( |
---|
| 42 | ILocalRoleSetEvent, IUserAccount, IAuthPluginUtility, IPasswordValidator, |
---|
| 43 | IKofaPrincipal, IKofaPrincipalInfo, IKofaPluggable, IBatchProcessor, |
---|
| 44 | IGNORE_MARKER, IFailedLoginInfo) |
---|
[8973] | 45 | from waeup.kofa.utils.batching import BatchProcessor |
---|
[12190] | 46 | from waeup.kofa.permissions import get_all_roles |
---|
[15286] | 47 | from waeup.kofa.interfaces import MessageFactory as _ |
---|
[4073] | 48 | |
---|
[14669] | 49 | |
---|
[4073] | 50 | def setup_authentication(pau): |
---|
| 51 | """Set up plugguble authentication utility. |
---|
| 52 | |
---|
| 53 | Sets up an IAuthenticatorPlugin and |
---|
| 54 | ICredentialsPlugin (for the authentication mechanism) |
---|
[5900] | 55 | |
---|
| 56 | Then looks for any external utilities that want to modify the PAU. |
---|
[4073] | 57 | """ |
---|
[14667] | 58 | pau.credentialsPlugins = ( |
---|
[14669] | 59 | 'No Challenge if Authenticated', |
---|
| 60 | 'xmlrpc-credentials', |
---|
| 61 | 'credentials') |
---|
[6672] | 62 | pau.authenticatorPlugins = ('users',) |
---|
[4073] | 63 | |
---|
[5900] | 64 | # Give any third-party code and subpackages a chance to modify the PAU |
---|
| 65 | auth_plugin_utilities = getUtilitiesFor(IAuthPluginUtility) |
---|
[5901] | 66 | for name, util in auth_plugin_utilities: |
---|
[5900] | 67 | util.register(pau) |
---|
| 68 | |
---|
[14669] | 69 | |
---|
[6673] | 70 | def get_principal_role_manager(): |
---|
| 71 | """Get a role manager for principals. |
---|
| 72 | |
---|
| 73 | If we are currently 'in a site', return the role manager for the |
---|
| 74 | portal or the global rolemanager else. |
---|
| 75 | """ |
---|
| 76 | portal = grok.getSite() |
---|
| 77 | if portal is not None: |
---|
| 78 | return IPrincipalRoleManager(portal) |
---|
| 79 | return principalRoleManager |
---|
| 80 | |
---|
[14669] | 81 | |
---|
| 82 | class KofaSessionCredentialsPlugin( |
---|
| 83 | grok.GlobalUtility, SessionCredentialsPlugin): |
---|
[14667] | 84 | """Session plugin that picks usernames/passwords from fields in webforms. |
---|
| 85 | """ |
---|
[4073] | 86 | grok.provides(ICredentialsPlugin) |
---|
| 87 | grok.name('credentials') |
---|
| 88 | |
---|
| 89 | loginpagename = 'login' |
---|
| 90 | loginfield = 'form.login' |
---|
| 91 | passwordfield = 'form.password' |
---|
| 92 | |
---|
[14667] | 93 | |
---|
| 94 | class KofaXMLRPCCredentialsPlugin( |
---|
| 95 | grok.GlobalUtility, HTTPBasicAuthCredentialsPlugin): |
---|
| 96 | """Plugin that picks useranams/passwords from basic-auth headers. |
---|
| 97 | |
---|
| 98 | As XMLRPC requests send/post their authentication credentials in HTTP |
---|
| 99 | basic-auth headers, we need a plugin that can handle this. |
---|
| 100 | |
---|
| 101 | This plugin, however, does no challenging. If a user does not provide |
---|
| 102 | basic-auth infos, we will not ask for some. This is correct as we plan to |
---|
| 103 | communicate with machines. |
---|
| 104 | |
---|
| 105 | This plugin is planned to be used in "PluggableAuthenitications" registered |
---|
| 106 | with `University` instances. |
---|
| 107 | """ |
---|
| 108 | grok.provides(ICredentialsPlugin) |
---|
| 109 | grok.name('xmlrpc-credentials') |
---|
| 110 | |
---|
| 111 | def challenge(self, request): |
---|
| 112 | """XMLRPC is for machines. No need to challenge. |
---|
| 113 | """ |
---|
| 114 | return False |
---|
| 115 | |
---|
| 116 | def logout(self, request): |
---|
| 117 | """Basic auth does not provide any logout possibility. |
---|
| 118 | """ |
---|
| 119 | return False |
---|
| 120 | |
---|
| 121 | |
---|
[7819] | 122 | class KofaPrincipalInfo(object): |
---|
| 123 | """An implementation of IKofaPrincipalInfo. |
---|
[4073] | 124 | |
---|
[7819] | 125 | A Kofa principal info is created with id, login, title, description, |
---|
[8757] | 126 | phone, email, public_name and user_type. |
---|
[7233] | 127 | """ |
---|
[7819] | 128 | grok.implements(IKofaPrincipalInfo) |
---|
[7233] | 129 | |
---|
[10055] | 130 | def __init__(self, id, title, description, email, phone, public_name, |
---|
| 131 | user_type): |
---|
[4073] | 132 | self.id = id |
---|
| 133 | self.title = title |
---|
| 134 | self.description = description |
---|
[7233] | 135 | self.email = email |
---|
| 136 | self.phone = phone |
---|
[8757] | 137 | self.public_name = public_name |
---|
[7240] | 138 | self.user_type = user_type |
---|
[4073] | 139 | self.credentialsPlugin = None |
---|
| 140 | self.authenticatorPlugin = None |
---|
| 141 | |
---|
[10055] | 142 | def __eq__(self, obj): |
---|
| 143 | default = object() |
---|
| 144 | result = [] |
---|
| 145 | for name in ('id', 'title', 'description', 'email', 'phone', |
---|
| 146 | 'public_name', 'user_type', 'credentialsPlugin', |
---|
| 147 | 'authenticatorPlugin'): |
---|
| 148 | result.append( |
---|
| 149 | getattr(self, name) == getattr(obj, name, default)) |
---|
| 150 | return False not in result |
---|
| 151 | |
---|
[14669] | 152 | |
---|
[7819] | 153 | class KofaPrincipal(Principal): |
---|
[7233] | 154 | """A portal principal. |
---|
| 155 | |
---|
[10055] | 156 | Kofa principals provide an extra `email`, `phone`, `public_name` |
---|
| 157 | and `user_type` attribute extending ordinary principals. |
---|
[7233] | 158 | """ |
---|
| 159 | |
---|
[7819] | 160 | grok.implements(IKofaPrincipal) |
---|
[7233] | 161 | |
---|
| 162 | def __init__(self, id, title=u'', description=u'', email=u'', |
---|
[8757] | 163 | phone=None, public_name=u'', user_type=u'', prefix=None): |
---|
[7233] | 164 | self.id = id |
---|
[7239] | 165 | if prefix is not None: |
---|
| 166 | self.id = '%s.%s' % (prefix, self.id) |
---|
[7233] | 167 | self.title = title |
---|
| 168 | self.description = description |
---|
| 169 | self.groups = [] |
---|
| 170 | self.email = email |
---|
| 171 | self.phone = phone |
---|
[8757] | 172 | self.public_name = public_name |
---|
[7240] | 173 | self.user_type = user_type |
---|
[7233] | 174 | |
---|
| 175 | def __repr__(self): |
---|
[7819] | 176 | return 'KofaPrincipal(%r)' % self.id |
---|
[7233] | 177 | |
---|
[14669] | 178 | |
---|
[7819] | 179 | class AuthenticatedKofaPrincipalFactory(grok.MultiAdapter): |
---|
| 180 | """Creates 'authenticated' Kofa principals. |
---|
[7233] | 181 | |
---|
[7819] | 182 | Adapts (principal info, request) to a KofaPrincipal instance. |
---|
[7233] | 183 | |
---|
| 184 | This adapter is used by the standard PAU to transform |
---|
[7819] | 185 | KofaPrincipalInfos into KofaPrincipal instances. |
---|
[7233] | 186 | """ |
---|
[7819] | 187 | grok.adapts(IKofaPrincipalInfo, IRequest) |
---|
[7233] | 188 | grok.implements(IAuthenticatedPrincipalFactory) |
---|
| 189 | |
---|
| 190 | def __init__(self, info, request): |
---|
| 191 | self.info = info |
---|
| 192 | self.request = request |
---|
| 193 | |
---|
| 194 | def __call__(self, authentication): |
---|
[7819] | 195 | principal = KofaPrincipal( |
---|
[7233] | 196 | self.info.id, |
---|
| 197 | self.info.title, |
---|
| 198 | self.info.description, |
---|
| 199 | self.info.email, |
---|
| 200 | self.info.phone, |
---|
[8757] | 201 | self.info.public_name, |
---|
[7240] | 202 | self.info.user_type, |
---|
[7239] | 203 | authentication.prefix, |
---|
[7233] | 204 | ) |
---|
| 205 | notify( |
---|
| 206 | AuthenticatedPrincipalCreated( |
---|
| 207 | authentication, principal, self.info, self.request)) |
---|
| 208 | return principal |
---|
| 209 | |
---|
[14669] | 210 | |
---|
[10055] | 211 | class FailedLoginInfo(grok.Model): |
---|
| 212 | grok.implements(IFailedLoginInfo) |
---|
| 213 | |
---|
| 214 | def __init__(self, num=0, last=None): |
---|
| 215 | self.num = num |
---|
| 216 | self.last = last |
---|
| 217 | return |
---|
| 218 | |
---|
| 219 | def as_tuple(self): |
---|
| 220 | return (self.num, self.last) |
---|
| 221 | |
---|
| 222 | def set_values(self, num=0, last=None): |
---|
| 223 | self.num, self.last = num, last |
---|
| 224 | self._p_changed = True |
---|
| 225 | pass |
---|
| 226 | |
---|
| 227 | def increase(self): |
---|
| 228 | self.set_values(num=self.num + 1, last=time.time()) |
---|
| 229 | pass |
---|
| 230 | |
---|
| 231 | def reset(self): |
---|
| 232 | self.set_values(num=0, last=None) |
---|
| 233 | pass |
---|
| 234 | |
---|
[14669] | 235 | |
---|
[4073] | 236 | class Account(grok.Model): |
---|
[10055] | 237 | """Kofa user accounts store infos about a user. |
---|
| 238 | |
---|
| 239 | Beside the usual data and an (encrypted) password, accounts also |
---|
| 240 | have a persistent attribute `failed_logins` which is an instance |
---|
| 241 | of `waeup.kofa.authentication.FailedLoginInfo`. |
---|
| 242 | |
---|
| 243 | This attribute can be manipulated directly (set new value, |
---|
| 244 | increase values, or reset). |
---|
| 245 | """ |
---|
[4109] | 246 | grok.implements(IUserAccount) |
---|
[4129] | 247 | |
---|
[4125] | 248 | def __init__(self, name, password, title=None, description=None, |
---|
[14669] | 249 | email=None, phone=None, public_name=None, roles=[]): |
---|
[4073] | 250 | self.name = name |
---|
[4087] | 251 | if title is None: |
---|
| 252 | title = name |
---|
| 253 | self.title = title |
---|
| 254 | self.description = description |
---|
[7221] | 255 | self.email = email |
---|
[7233] | 256 | self.phone = phone |
---|
[8756] | 257 | self.public_name = public_name |
---|
[12926] | 258 | self.suspended = False |
---|
[4073] | 259 | self.setPassword(password) |
---|
[7636] | 260 | self.setSiteRolesForPrincipal(roles) |
---|
[10055] | 261 | |
---|
[6180] | 262 | # We don't want to share this dict with other accounts |
---|
| 263 | self._local_roles = dict() |
---|
[10055] | 264 | self.failed_logins = FailedLoginInfo() |
---|
[4073] | 265 | |
---|
| 266 | def setPassword(self, password): |
---|
[8343] | 267 | passwordmanager = getUtility(IPasswordManager, 'SSHA') |
---|
[4073] | 268 | self.password = passwordmanager.encodePassword(password) |
---|
| 269 | |
---|
| 270 | def checkPassword(self, password): |
---|
[13394] | 271 | try: |
---|
| 272 | blocker = grok.getSite()['configuration'].maintmode_enabled_by |
---|
[17528] | 273 | if blocker and blocker != self.name and self.name != 'admin': |
---|
[13394] | 274 | return False |
---|
| 275 | except (TypeError, KeyError): # in unit tests |
---|
| 276 | pass |
---|
[8344] | 277 | if not isinstance(password, basestring): |
---|
| 278 | return False |
---|
| 279 | if not self.password: |
---|
| 280 | # unset/empty passwords do never match |
---|
| 281 | return False |
---|
[15287] | 282 | # Do not accept password if password is insecure. |
---|
| 283 | validator = getUtility(IPasswordValidator) |
---|
| 284 | if validator.validate_secure_password(password, password): |
---|
| 285 | return False |
---|
[14669] | 286 | if self.suspended: |
---|
[12926] | 287 | return False |
---|
[8343] | 288 | passwordmanager = getUtility(IPasswordManager, 'SSHA') |
---|
[4073] | 289 | return passwordmanager.checkPassword(self.password, password) |
---|
| 290 | |
---|
[7177] | 291 | def getSiteRolesForPrincipal(self): |
---|
[6673] | 292 | prm = get_principal_role_manager() |
---|
[4129] | 293 | roles = [x[0] for x in prm.getRolesForPrincipal(self.name) |
---|
| 294 | if x[0].startswith('waeup.')] |
---|
| 295 | return roles |
---|
[5055] | 296 | |
---|
[7177] | 297 | def setSiteRolesForPrincipal(self, roles): |
---|
[6673] | 298 | prm = get_principal_role_manager() |
---|
[7177] | 299 | old_roles = self.getSiteRolesForPrincipal() |
---|
[7658] | 300 | if sorted(old_roles) == sorted(roles): |
---|
| 301 | return |
---|
[4129] | 302 | for role in old_roles: |
---|
| 303 | # Remove old roles, not to be set now... |
---|
| 304 | if role.startswith('waeup.') and role not in roles: |
---|
| 305 | prm.unsetRoleForPrincipal(role, self.name) |
---|
| 306 | for role in roles: |
---|
[7658] | 307 | # Convert role to ASCII string to be in line with the |
---|
| 308 | # event handler |
---|
| 309 | prm.assignRoleToPrincipal(str(role), self.name) |
---|
| 310 | return |
---|
[4129] | 311 | |
---|
[7177] | 312 | roles = property(getSiteRolesForPrincipal, setSiteRolesForPrincipal) |
---|
[4129] | 313 | |
---|
[6180] | 314 | def getLocalRoles(self): |
---|
| 315 | return self._local_roles |
---|
| 316 | |
---|
| 317 | def notifyLocalRoleChanged(self, obj, role_id, granted=True): |
---|
| 318 | objects = self._local_roles.get(role_id, []) |
---|
| 319 | if granted and obj not in objects: |
---|
| 320 | objects.append(obj) |
---|
| 321 | if not granted and obj in objects: |
---|
| 322 | objects.remove(obj) |
---|
| 323 | self._local_roles[role_id] = objects |
---|
| 324 | if len(objects) == 0: |
---|
| 325 | del self._local_roles[role_id] |
---|
[6182] | 326 | self._p_changed = True |
---|
[6180] | 327 | return |
---|
| 328 | |
---|
[14669] | 329 | |
---|
[4073] | 330 | class UserAuthenticatorPlugin(grok.GlobalUtility): |
---|
[6625] | 331 | grok.implements(IAuthenticatorPlugin) |
---|
[4073] | 332 | grok.provides(IAuthenticatorPlugin) |
---|
| 333 | grok.name('users') |
---|
| 334 | |
---|
| 335 | def authenticateCredentials(self, credentials): |
---|
| 336 | if not isinstance(credentials, dict): |
---|
| 337 | return None |
---|
| 338 | if not ('login' in credentials and 'password' in credentials): |
---|
| 339 | return None |
---|
| 340 | account = self.getAccount(credentials['login']) |
---|
| 341 | if account is None: |
---|
| 342 | return None |
---|
[10055] | 343 | # The following shows how 'time penalties' could be enforced |
---|
| 344 | # on failed logins. First three failed logins are 'for |
---|
| 345 | # free'. After that the user has to wait for 1, 2, 4, 8, 16, |
---|
| 346 | # 32, ... seconds before a login can succeed. |
---|
| 347 | # There are, however, some problems to discuss, before we |
---|
| 348 | # really use this in all authenticators. |
---|
| 349 | |
---|
| 350 | #num, last = account.failed_logins.as_tuple() |
---|
| 351 | #if (num > 2) and (time.time() < (last + 2**(num-3))): |
---|
| 352 | # # tried login while account still blocked due to previous |
---|
| 353 | # # login errors. |
---|
| 354 | # return None |
---|
[4073] | 355 | if not account.checkPassword(credentials['password']): |
---|
[10055] | 356 | #account.failed_logins.increase() |
---|
[4073] | 357 | return None |
---|
[7819] | 358 | return KofaPrincipalInfo( |
---|
[7315] | 359 | id=account.name, |
---|
| 360 | title=account.title, |
---|
| 361 | description=account.description, |
---|
| 362 | email=account.email, |
---|
| 363 | phone=account.phone, |
---|
[8757] | 364 | public_name=account.public_name, |
---|
[7315] | 365 | user_type=u'user') |
---|
[4073] | 366 | |
---|
| 367 | def principalInfo(self, id): |
---|
| 368 | account = self.getAccount(id) |
---|
| 369 | if account is None: |
---|
| 370 | return None |
---|
[7819] | 371 | return KofaPrincipalInfo( |
---|
[7315] | 372 | id=account.name, |
---|
| 373 | title=account.title, |
---|
| 374 | description=account.description, |
---|
| 375 | email=account.email, |
---|
| 376 | phone=account.phone, |
---|
[8757] | 377 | public_name=account.public_name, |
---|
[7315] | 378 | user_type=u'user') |
---|
[4073] | 379 | |
---|
| 380 | def getAccount(self, login): |
---|
[4087] | 381 | # ... look up the account object and return it ... |
---|
[7172] | 382 | userscontainer = self.getUsersContainer() |
---|
| 383 | if userscontainer is None: |
---|
[4087] | 384 | return |
---|
[7172] | 385 | return userscontainer.get(login, None) |
---|
[4087] | 386 | |
---|
| 387 | def addAccount(self, account): |
---|
[7172] | 388 | userscontainer = self.getUsersContainer() |
---|
| 389 | if userscontainer is None: |
---|
[4087] | 390 | return |
---|
| 391 | # XXX: complain if name already exists... |
---|
[7172] | 392 | userscontainer.addAccount(account) |
---|
[4087] | 393 | |
---|
[4091] | 394 | def addUser(self, name, password, title=None, description=None): |
---|
[7172] | 395 | userscontainer = self.getUsersContainer() |
---|
| 396 | if userscontainer is None: |
---|
[4091] | 397 | return |
---|
[7172] | 398 | userscontainer.addUser(name, password, title, description) |
---|
[5055] | 399 | |
---|
[7172] | 400 | def getUsersContainer(self): |
---|
[4087] | 401 | site = grok.getSite() |
---|
[4743] | 402 | return site['users'] |
---|
[6203] | 403 | |
---|
[14669] | 404 | |
---|
[7147] | 405 | class PasswordValidator(grok.GlobalUtility): |
---|
| 406 | |
---|
[14669] | 407 | grok.implements(IPasswordValidator) |
---|
[7147] | 408 | |
---|
[14669] | 409 | def validate_password(self, pw, pw_repeat): |
---|
| 410 | errors = [] |
---|
[15286] | 411 | if len(pw) < 6: |
---|
[15302] | 412 | errors.append(translate(_( |
---|
| 413 | 'Password must have at least 6 characters.'))) |
---|
[14669] | 414 | if pw != pw_repeat: |
---|
[15286] | 415 | errors.append(translate(_('Passwords do not match.'))) |
---|
[14669] | 416 | return errors |
---|
[7147] | 417 | |
---|
[15287] | 418 | def validate_secure_password(self, pw, pw_repeat): |
---|
[15286] | 419 | """ |
---|
| 420 | ^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$ |
---|
[14669] | 421 | |
---|
[15286] | 422 | ^ Start anchor |
---|
| 423 | (?=.*[A-Z]) Ensure password has one uppercase letters. |
---|
| 424 | (?=.*[0-9]) Ensure password has one digit. |
---|
| 425 | (?=.*[a-z]) Ensure password has one lowercase letter. |
---|
| 426 | .{8,} Ensure password is of length 8. |
---|
[15302] | 427 | $ End anchor |
---|
[15286] | 428 | """ |
---|
| 429 | check_pw = re.compile(r"^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$").match |
---|
| 430 | errors = [] |
---|
| 431 | if not check_pw(pw): |
---|
| 432 | errors.append(translate(_( |
---|
| 433 | 'Passwords must be at least 8 characters long, ' |
---|
[15287] | 434 | 'must contain at least one uppercase letter, ' |
---|
[15286] | 435 | 'one lowercase letter and one digit.'))) |
---|
| 436 | if pw != pw_repeat: |
---|
| 437 | errors.append(translate(_('Passwords do not match.'))) |
---|
| 438 | return errors |
---|
| 439 | |
---|
| 440 | |
---|
[7169] | 441 | class LocalRoleSetEvent(object): |
---|
| 442 | |
---|
| 443 | grok.implements(ILocalRoleSetEvent) |
---|
| 444 | |
---|
| 445 | def __init__(self, object, role_id, principal_id, granted=True): |
---|
| 446 | self.object = object |
---|
| 447 | self.role_id = role_id |
---|
| 448 | self.principal_id = principal_id |
---|
| 449 | self.granted = granted |
---|
| 450 | |
---|
[14669] | 451 | |
---|
[6203] | 452 | @grok.subscribe(IUserAccount, grok.IObjectRemovedEvent) |
---|
[6839] | 453 | def handle_account_removed(account, event): |
---|
[9313] | 454 | """When an account is removed, local and global roles might |
---|
| 455 | have to be deleted. |
---|
[6203] | 456 | """ |
---|
| 457 | local_roles = account.getLocalRoles() |
---|
| 458 | principal = account.name |
---|
[9313] | 459 | |
---|
[6203] | 460 | for role_id, object_list in local_roles.items(): |
---|
| 461 | for object in object_list: |
---|
| 462 | try: |
---|
| 463 | role_manager = IPrincipalRoleManager(object) |
---|
| 464 | except TypeError: |
---|
[9313] | 465 | # No Account object, no role manager, no local roles to remove |
---|
[6203] | 466 | continue |
---|
| 467 | role_manager.unsetRoleForPrincipal(role_id, principal) |
---|
[9313] | 468 | role_manager = IPrincipalRoleManager(grok.getSite()) |
---|
| 469 | roles = account.getSiteRolesForPrincipal() |
---|
| 470 | for role_id in roles: |
---|
| 471 | role_manager.unsetRoleForPrincipal(role_id, principal) |
---|
[6203] | 472 | return |
---|
[7169] | 473 | |
---|
[14669] | 474 | |
---|
[7169] | 475 | @grok.subscribe(IUserAccount, grok.IObjectAddedEvent) |
---|
| 476 | def handle_account_added(account, event): |
---|
| 477 | """When an account is added, the local owner role and the global |
---|
[7185] | 478 | AcademicsOfficer role must be set. |
---|
[7169] | 479 | """ |
---|
[7173] | 480 | # We set the local Owner role |
---|
| 481 | role_manager_account = IPrincipalRoleManager(account) |
---|
| 482 | role_manager_account.assignRoleToPrincipal( |
---|
[7169] | 483 | 'waeup.local.Owner', account.name) |
---|
[7185] | 484 | # We set the global AcademicsOfficer role |
---|
[7173] | 485 | site = grok.getSite() |
---|
| 486 | role_manager_site = IPrincipalRoleManager(site) |
---|
| 487 | role_manager_site.assignRoleToPrincipal( |
---|
[7185] | 488 | 'waeup.AcademicsOfficer', account.name) |
---|
[7173] | 489 | # Finally we have to notify the user account that the local role |
---|
[7169] | 490 | # of the same object has changed |
---|
| 491 | notify(LocalRoleSetEvent( |
---|
| 492 | account, 'waeup.local.Owner', account.name, granted=True)) |
---|
| 493 | return |
---|
| 494 | |
---|
[14669] | 495 | |
---|
[7169] | 496 | @grok.subscribe(Interface, ILocalRoleSetEvent) |
---|
| 497 | def handle_local_role_changed(obj, event): |
---|
| 498 | site = grok.getSite() |
---|
| 499 | if site is None: |
---|
| 500 | return |
---|
| 501 | users = site.get('users', None) |
---|
| 502 | if users is None: |
---|
| 503 | return |
---|
| 504 | if event.principal_id not in users.keys(): |
---|
| 505 | return |
---|
| 506 | user = users[event.principal_id] |
---|
| 507 | user.notifyLocalRoleChanged(event.object, event.role_id, event.granted) |
---|
| 508 | return |
---|
| 509 | |
---|
[14669] | 510 | |
---|
[7169] | 511 | @grok.subscribe(Interface, grok.IObjectRemovedEvent) |
---|
| 512 | def handle_local_roles_on_obj_removed(obj, event): |
---|
| 513 | try: |
---|
| 514 | role_map = IPrincipalRoleMap(obj) |
---|
| 515 | except TypeError: |
---|
| 516 | # no map, no roles to remove |
---|
| 517 | return |
---|
| 518 | for local_role, user_name, setting in role_map.getPrincipalsAndRoles(): |
---|
| 519 | notify(LocalRoleSetEvent( |
---|
[14669] | 520 | obj, local_role, user_name, granted=False)) |
---|
[7315] | 521 | return |
---|
[8756] | 522 | |
---|
[14669] | 523 | |
---|
[8973] | 524 | class UserAccountFactory(grok.GlobalUtility): |
---|
| 525 | """A factory for user accounts. |
---|
| 526 | |
---|
| 527 | This factory is only needed for imports. |
---|
| 528 | """ |
---|
| 529 | grok.implements(IFactory) |
---|
| 530 | grok.name(u'waeup.UserAccount') |
---|
| 531 | title = u"Create a user.", |
---|
| 532 | description = u"This factory instantiates new user account instances." |
---|
| 533 | |
---|
| 534 | def __call__(self, *args, **kw): |
---|
| 535 | return Account(name=None, password='') |
---|
| 536 | |
---|
| 537 | def getInterfaces(self): |
---|
| 538 | return implementedBy(Account) |
---|
| 539 | |
---|
[14669] | 540 | |
---|
[8973] | 541 | class UserProcessor(BatchProcessor): |
---|
[14669] | 542 | """The User Processor processes user accounts, i.e. `Account` objects in |
---|
| 543 | the ``users`` container. |
---|
[12869] | 544 | |
---|
| 545 | The `roles` columns must contain Python list |
---|
| 546 | expressions like ``['waeup.PortalManager', 'waeup.ImportManager']``. |
---|
| 547 | |
---|
| 548 | The processor does not import local roles. These can be imported |
---|
| 549 | by means of batch processors in the academic section. |
---|
[8973] | 550 | """ |
---|
| 551 | grok.implements(IBatchProcessor) |
---|
| 552 | grok.provides(IBatchProcessor) |
---|
| 553 | grok.context(Interface) |
---|
| 554 | util_name = 'userprocessor' |
---|
| 555 | grok.name(util_name) |
---|
| 556 | |
---|
| 557 | name = u'User Processor' |
---|
| 558 | iface = IUserAccount |
---|
| 559 | |
---|
[14669] | 560 | location_fields = ['name', ] |
---|
[8973] | 561 | factory_name = 'waeup.UserAccount' |
---|
| 562 | |
---|
| 563 | mode = None |
---|
| 564 | |
---|
| 565 | def parentsExist(self, row, site): |
---|
| 566 | return 'users' in site.keys() |
---|
| 567 | |
---|
| 568 | def entryExists(self, row, site): |
---|
| 569 | return row['name'] in site['users'].keys() |
---|
| 570 | |
---|
| 571 | def getParent(self, row, site): |
---|
| 572 | return site['users'] |
---|
| 573 | |
---|
| 574 | def getEntry(self, row, site): |
---|
| 575 | if not self.entryExists(row, site): |
---|
| 576 | return None |
---|
| 577 | parent = self.getParent(row, site) |
---|
| 578 | return parent.get(row['name']) |
---|
| 579 | |
---|
| 580 | def addEntry(self, obj, row, site): |
---|
| 581 | parent = self.getParent(row, site) |
---|
| 582 | parent.addAccount(obj) |
---|
| 583 | return |
---|
| 584 | |
---|
[13182] | 585 | def delEntry(self, row, site): |
---|
| 586 | user = self.getEntry(row, site) |
---|
| 587 | if user is not None: |
---|
| 588 | parent = self.getParent(row, site) |
---|
[14669] | 589 | grok.getSite().logger.info( |
---|
| 590 | '%s - %s - User removed' % (self.name, row['name'])) |
---|
[13182] | 591 | del parent[user.name] |
---|
| 592 | pass |
---|
| 593 | |
---|
[9706] | 594 | def updateEntry(self, obj, row, site, filename): |
---|
[9312] | 595 | """Update obj to the values given in row. |
---|
| 596 | """ |
---|
| 597 | changed = [] |
---|
| 598 | for key, value in row.items(): |
---|
[14669] | 599 | if key == 'roles': |
---|
[9312] | 600 | # We cannot simply set the roles attribute here because |
---|
| 601 | # we can't assure that the name attribute is set before |
---|
| 602 | # the roles attribute is set. |
---|
| 603 | continue |
---|
| 604 | # Skip fields to be ignored. |
---|
| 605 | if value == IGNORE_MARKER: |
---|
| 606 | continue |
---|
| 607 | if not hasattr(obj, key): |
---|
| 608 | continue |
---|
| 609 | setattr(obj, key, value) |
---|
| 610 | changed.append('%s=%s' % (key, value)) |
---|
| 611 | roles = row.get('roles', IGNORE_MARKER) |
---|
| 612 | if roles not in ('', IGNORE_MARKER): |
---|
| 613 | evalvalue = eval(roles) |
---|
| 614 | if isinstance(evalvalue, list): |
---|
| 615 | setattr(obj, 'roles', evalvalue) |
---|
| 616 | changed.append('roles=%s' % roles) |
---|
| 617 | # Log actions... |
---|
| 618 | items_changed = ', '.join(changed) |
---|
[14669] | 619 | grok.getSite().logger.info( |
---|
| 620 | '%s - %s - %s - updated: %s' % ( |
---|
| 621 | self.name, filename, row['name'], items_changed)) |
---|
[9312] | 622 | return |
---|
[8973] | 623 | |
---|
[12190] | 624 | def checkConversion(self, row, mode='ignore'): |
---|
| 625 | """Validates all values in row. |
---|
| 626 | """ |
---|
| 627 | errs, inv_errs, conv_dict = super( |
---|
| 628 | UserProcessor, self).checkConversion(row, mode=mode) |
---|
| 629 | # We need to check if roles exist. |
---|
[13181] | 630 | roles = row.get('roles', IGNORE_MARKER) |
---|
[12190] | 631 | all_roles = [i[0] for i in get_all_roles()] |
---|
| 632 | if roles not in ('', IGNORE_MARKER): |
---|
| 633 | evalvalue = eval(roles) |
---|
| 634 | for role in evalvalue: |
---|
| 635 | if role not in all_roles: |
---|
[14669] | 636 | errs.append(('roles', 'invalid role')) |
---|
[12190] | 637 | return errs, inv_errs, conv_dict |
---|
| 638 | |
---|
[14669] | 639 | |
---|
[8756] | 640 | class UsersPlugin(grok.GlobalUtility): |
---|
| 641 | """A plugin that updates users. |
---|
| 642 | """ |
---|
| 643 | grok.implements(IKofaPluggable) |
---|
| 644 | grok.name('users') |
---|
| 645 | |
---|
| 646 | deprecated_attributes = [] |
---|
| 647 | |
---|
| 648 | def setup(self, site, name, logger): |
---|
| 649 | return |
---|
| 650 | |
---|
| 651 | def update(self, site, name, logger): |
---|
| 652 | users = site['users'] |
---|
| 653 | items = getFields(IUserAccount).items() |
---|
| 654 | for user in users.values(): |
---|
| 655 | # Add new attributes |
---|
| 656 | for i in items: |
---|
[14669] | 657 | if not hasattr(user, i[0]): |
---|
| 658 | setattr(user, i[0], i[1].missing_value) |
---|
[8756] | 659 | logger.info( |
---|
| 660 | 'UsersPlugin: %s attribute %s added.' % ( |
---|
[14669] | 661 | user.name, i[0])) |
---|
[10055] | 662 | if not hasattr(user, 'failed_logins'): |
---|
| 663 | # add attribute `failed_logins`... |
---|
| 664 | user.failed_logins = FailedLoginInfo() |
---|
| 665 | logger.info( |
---|
| 666 | 'UsersPlugin: attribute failed_logins added.') |
---|
[8756] | 667 | # Remove deprecated attributes |
---|
| 668 | for i in self.deprecated_attributes: |
---|
| 669 | try: |
---|
[14669] | 670 | delattr(user, i) |
---|
[8756] | 671 | logger.info( |
---|
| 672 | 'UsersPlugin: %s attribute %s deleted.' % ( |
---|
[14669] | 673 | user.name, i)) |
---|
[8756] | 674 | except AttributeError: |
---|
| 675 | pass |
---|
[10055] | 676 | return |
---|
[14670] | 677 | |
---|
| 678 | |
---|
| 679 | class UpdatePAUPlugin(grok.GlobalUtility): |
---|
| 680 | """A plugin that updates a local PAU. |
---|
| 681 | |
---|
| 682 | We insert an 'xmlrpc-credentials' PAU-plugin into a sites PAU if it is not |
---|
| 683 | present already. There must be 'credentials' plugin registered already. |
---|
| 684 | |
---|
| 685 | XXX: This Plugin fixes a shortcoming of waeup.kofa 1.5. Sites created or |
---|
| 686 | updated afterwards do not need this plugin and it should be removed. |
---|
| 687 | """ |
---|
| 688 | grok.implements(IKofaPluggable) |
---|
| 689 | grok.name('site-pluggable-auth') |
---|
| 690 | |
---|
| 691 | def setup(self, site, name, logger): |
---|
| 692 | return |
---|
| 693 | |
---|
| 694 | def update(self, site, name, logger): |
---|
| 695 | pau = site.getSiteManager()['PluggableAuthentication'] |
---|
| 696 | if 'xmlrpc-credentials' in pau.credentialsPlugins: |
---|
| 697 | return |
---|
| 698 | plugins = list(pau.credentialsPlugins) |
---|
| 699 | plugins.insert(plugins.index('credentials'), 'xmlrpc-credentials') |
---|
| 700 | pau.credentialsPlugins = tuple(plugins) |
---|