/usr/share/pyshared/acct_mgr/api.py is in trac-accountmanager 0.4.3-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Matthew Good <trac@matt-good.net>
# Copyright (C) 2011,2012 Steffen Hoffmann <hoff.st@web.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# Author: Matthew Good <trac@matt-good.net>
from pkg_resources import resource_filename
from trac.config import BoolOption, Configuration, ExtensionOption, \
Option, OrderedExtensionsOption
from trac.core import Component, ExtensionPoint, Interface, TracError, \
implements
from trac.perm import IPermissionRequestor
from trac.web.chrome import ITemplateProvider
# Import i18n methods. Fallback modules maintain compatibility to Trac 0.11
# by keeping Babel optional here.
try:
from trac.util.translation import domain_functions
add_domain, _, N_, gettext, ngettext, tag_ = \
domain_functions('acct_mgr', ('add_domain', '_', 'N_', 'gettext',
'ngettext', 'tag_'))
dgettext = None
except ImportError:
from genshi.builder import tag as tag_
from trac.util.translation import gettext
_ = gettext
N_ = lambda text: text
def add_domain(a,b,c=None):
pass
def dgettext(domain, string, **kwargs):
return safefmt(string, kwargs)
def ngettext(singular, plural, num, **kwargs):
string = num == 1 and singular or plural
kwargs.setdefault('num', num)
return safefmt(string, kwargs)
def safefmt(string, kwargs):
if kwargs:
try:
return string % kwargs
except KeyError:
pass
return string
from acct_mgr.model import delete_user, get_user_attribute, \
prime_auth_session, set_user_attribute
class IPasswordStore(Interface):
"""An interface for Components that provide a storage method for users and
passwords.
"""
def config_key():
"""'''Deprecated''': New implementations should not use this method.
The prefered way to configure an `IPasswordStore` implemenation is by
using its class name in the `password_store` option.
Returns a string used to identify this implementation in the config.
This password storage implementation will be used, if the value of
config property "account-manager.password_format" matches.
"""
def get_users():
"""Returns an iterable of the known usernames."""
def has_user(user):
"""Returns whether the user account exists."""
def set_password(user, password, old_password = None):
"""Sets the password for the user.
This should create the user account, if it doesn't already exist.
Returns True, if a new account was created, False if an existing
account was updated.
"""
def check_password(user, password):
"""Checks if the password is valid for the user.
Returns True, if the correct user and password are specfied.
Returns False, if the incorrect password was specified.
Returns None, if the user doesn't exist in this password store.
Note: Returing `False` is an active rejection of the login attempt.
Return None to let the authentication eventually fall through to
next store in a chain.
"""
def delete_user(user):
"""Deletes the user account.
Returns True, if the account existed and was deleted, False otherwise.
"""
class IAccountChangeListener(Interface):
"""An interface for receiving account change events."""
def user_created(user, password):
"""New user (account) created."""
def user_password_changed(user, password):
"""Password changed."""
def user_deleted(user):
"""User and related account information have been deleted."""
def user_password_reset(user, email, password):
"""User password has been reset.
Note, that this is no longer final, and the old password could still
be recovered before first successful login with the new password.
"""
def user_email_verification_requested(user, token):
"""User verification has been requested."""
class IAccountRegistrationInspector(Interface):
"""An interface for Components, that wish to participate in examining
requests for account creation.
The check method is called not only by RegistrationModule but when adding
new users from the user editor in AccountManagerAdminPanel too.
"""
def render_registration_fields(req, data):
"""Emit one or multiple additional fields for registration form built.
Returns a dict containing a 'required' and/or 'optional' tuple of
* Genshi Fragment or valid XHTML markup for registration form
* modified or unchanged data object (used to render `register.html`)
If the return value is just a single tuple, its fragment or markup
will be inserted into the 'required' section.
"""
def validate_registration(req):
"""Check registration form input.
Returns a RegistrationError with error message, or None on success.
"""
class AccountManager(Component):
"""The AccountManager component handles all user account management methods
provided by the IPasswordStore interface.
The methods will be handled by underlying password storage implementations
set in trac.ini with the "account-manager.password_store" option.
The "account-manager.password_store" may be an ordered list of password
stores, and if so, then each password store is queried in turn.
"""
implements(IAccountChangeListener, IPermissionRequestor)
_password_store = OrderedExtensionsOption(
'account-manager', 'password_store', IPasswordStore,
include_missing=False,
doc = N_("Ordered list of password stores, queried in turn."))
_password_format = Option('account-manager', 'password_format',
doc="Legacy option, deprecated since acct_mgr-0.1.2")
_register_check = OrderedExtensionsOption(
'account-manager', 'register_check', IAccountRegistrationInspector,
default="""BasicCheck, EmailCheck, BotTrapCheck, RegExpCheck,
UsernamePermCheck""",
include_missing=False,
doc="""Ordered list of IAccountRegistrationInspector's to use for
registration checks.""")
stores = ExtensionPoint(IPasswordStore)
change_listeners = ExtensionPoint(IAccountChangeListener)
allow_delete_account = BoolOption(
'account-manager', 'allow_delete_account', True,
doc="Allow users to delete their own account.")
force_passwd_change = BoolOption(
'account-manager', 'force_passwd_change', True,
doc="Force the user to change password when it's reset.")
persistent_sessions = BoolOption(
'account-manager', 'persistent_sessions', False,
doc="""Allow the user to be remembered across sessions without
needing to re-authenticate. This is, user checks a
\"Remember Me\" checkbox and, next time he visits the site,
he'll be remembered.""")
refresh_passwd = BoolOption(
'account-manager', 'refresh_passwd', False,
doc="""Re-set passwords on successful authentication.
This is most useful to move users to a new password store or
enforce new store configuration (i.e. changed hash type),
but should be disabled/unset otherwise.""")
verify_email = BoolOption(
'account-manager', 'verify_email', True,
doc="Verify the email address of Trac users.")
username_char_blacklist = Option(
'account-manager', 'username_char_blacklist', ':[]',
doc="""Always exclude some special characters from usernames.
This is enforced upon new user registration.""")
def __init__(self):
# Bind the 'acct_mgr' catalog to the specified locale directory.
locale_dir = resource_filename(__name__, 'locale')
add_domain(self.env.path, locale_dir)
# Public API
def get_users(self):
"""Get usernames from all active stores.
Because we allow concurrent active stores, and some stores even don't
warrant uniqueness within itself, multiple usernames should be
expected.
"""
users = []
for store in self._password_store:
users.extend(store.get_users())
return users
def has_user(self, user):
exists = False
user = self.handle_username_casing(user)
for store in self._password_store:
if store.has_user(user):
exists = True
break
continue
return exists
def set_password(self, user, password, old_password = None):
user = self.handle_username_casing(user)
store = self.find_user_store(user)
if store and not hasattr(store, 'set_password'):
raise TracError(_(
"""The authentication backend for user %s does not support
setting the password.
""" % user))
elif not store:
store = self.get_supporting_store('set_password')
if store:
if store.set_password(user, password, old_password):
self._notify('created', user, password)
else:
self._notify('password_changed', user, password)
else:
raise TracError(_(
"""None of the IPasswordStore components listed in the
trac.ini supports setting the password or creating users.
"""))
def check_password(self, user, password):
valid = False
user = self.handle_username_casing(user)
for store in self._password_store:
valid = store.check_password(user, password)
if valid:
if valid == True and (self.refresh_passwd == True) and \
self.get_supporting_store('set_password'):
self._maybe_update_hash(user, password)
break
return valid
def delete_user(self, user):
user = self.handle_username_casing(user)
# Delete from password store
store = self.find_user_store(user)
del_method = getattr(store, 'delete_user', None)
if callable(del_method):
del_method(user)
# Delete session attributes, session and any custom permissions
# set for the user.
delete_user(self.env, user)
self._notify('deleted', user)
def supports(self, operation):
try:
stores = self.password_store
except AttributeError:
return False
else:
if self.get_supporting_store(operation):
return True
else:
return False
def password_store(self):
try:
return self._password_store
except AttributeError:
# fall back on old "password_format" option
fmt = self._password_format
for store in self.stores:
config_key = getattr(store, 'config_key', None)
if config_key is None:
continue
if config_key() == fmt:
return [store]
# if the "password_format" is not set re-raise the AttributeError
raise
password_store = property(password_store)
def get_supporting_store(self, operation):
"""Returns the IPasswordStore that implements the specified operation.
None is returned if no supporting store can be found.
"""
supports = False
for store in self.password_store:
if hasattr(store, operation):
supports = True
break
continue
store = supports and store or None
return store
def get_all_supporting_stores(self, operation):
"""Returns a list of stores that implement the specified operation"""
stores = []
for store in self.password_store:
if hasattr(store, operation):
stores.append(store)
continue
return stores
def find_user_store(self, user):
"""Locates which store contains the user specified.
If the user isn't found in any IPasswordStore in the chain, None is
returned.
"""
user_stores = []
for store in self._password_store:
userlist = store.get_users()
user_stores.append((store, userlist))
continue
user = self.handle_username_casing(user)
for store in user_stores:
if user in store[1]:
return store[0]
continue
return None
def handle_username_casing(self, user):
"""Enforce lowercase usernames if required.
Comply with Trac's own behavior, when case-insensitive
user authentication is set to True.
"""
ignore_auth_case = self.config.getbool('trac', 'ignore_auth_case')
return ignore_auth_case and user.lower() or user
def validate_registration(self, req):
"""Run configured registration checks and prime account on success."""
for inspector in self._register_check:
inspector.validate_registration(req)
username = self.handle_username_casing(
req.args.get('username').strip())
name = req.args.get('name').strip()
email = req.args.get('email', '').strip()
# Create the user in the configured (primary) password store.
self.set_password(username, req.args.get('password'))
# Output of a successful account creation request is a made-up
# authenticated session, that a new user can refer to later on.
prime_auth_session(self.env, username)
# Save attributes for the user with reference to that session ID.
for attribute in ('name', 'email'):
value = req.args.get(attribute)
if not value:
continue
set_user_attribute(self.env, username, attribute, value)
def _maybe_update_hash(self, user, password):
if not get_user_attribute(self.env, 1, user, 'password_refreshed', 1):
self.log.debug("Refresh password for user: %s" % user)
store = self.find_user_store(user)
pwstore = self.get_supporting_store('set_password')
if pwstore.set_password(user, password) == True:
# Account re-created according to current settings.
if store and not (store.delete_user(user) == True):
self.log.warn(
"Failed to remove old entry for user: %s" % user)
set_user_attribute(self.env, user, 'password_refreshed', 1)
def _notify(self, mod, *args):
mod = '_'.join(['user', mod])
for listener in self.change_listeners:
getattr(listener, mod)(*args)
# IAccountChangeListener methods
def user_created(self, user, password):
self.log.info("Created new user: %s" % user)
def user_password_changed(self, user, password):
self.log.info("Updated password for user: %s" % user)
def user_deleted(self, user):
self.log.info("Deleted user: %s" % user)
def user_password_reset(self, user, email, password):
self.log.info("Password reset for user: %s, %s" % (user, email))
def user_email_verification_requested(self, user, token):
self.log.info("Email verification requested for user: %s" % user)
# IPermissionRequestor methods
def get_permission_actions(self):
action = ['ACCTMGR_CONFIG_ADMIN', 'ACCTMGR_USER_ADMIN', 'EMAIL_VIEW',
'USER_VIEW']
actions = [('ACCTMGR_ADMIN', action), action[0],
(action[1], action[2:]), action[3]]
return actions
class CommonTemplateProvider(Component):
"""Generic template provider."""
implements(ITemplateProvider)
abstract = True
# ITemplateProvider methods
def get_htdocs_dirs(self):
"""Return the absolute path of a directory containing additional
static resources (such as images, style sheets, etc).
"""
return [('acct_mgr', resource_filename(__name__, 'htdocs'))]
def get_templates_dirs(self):
"""Return the absolute path of the directory containing the provided
Genshi templates.
"""
return [resource_filename(__name__, 'templates')]
|