/usr/share/pyshared/acct_mgr/register.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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Matthew Good <trac@matt-good.net>
# Copyright (C) 2010-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>
import base64
import re
import time
from genshi.core import Markup
from genshi.builder import tag
from os import urandom
from trac import perm, util
from trac.core import Component, TracError, implements
from trac.config import Option
from trac.env import open_environment
from trac.web import auth, chrome
from trac.web.main import IRequestHandler, IRequestFilter
from acct_mgr.api import AccountManager, CommonTemplateProvider, \
IAccountRegistrationInspector, \
_, N_, dgettext, gettext, tag_
from acct_mgr.model import email_associated, set_user_attribute
from acct_mgr.util import containsAny, is_enabled
class RegistrationError(TracError):
"""Exception raised when a registration check fails."""
def __init__(self, message, *args, **kwargs):
"""TracError sub-class with extended i18n support.
It eases error initialization with messages optionally including
arguments meant for string substitution after deferred translation.
"""
title = N_("Registration Error")
tb = 'show_traceback'
# Care for the 2nd TracError standard keyword argument only.
show_traceback = tb in kwargs and kwargs.pop(tb, False)
super(RegistrationError, self).__init__(message, title, show_traceback)
self.msg_args = args
class GenericRegistrationInspector(Component):
"""Generic check class, great for creating simple checks quickly."""
implements(IAccountRegistrationInspector)
abstract = True
def render_registration_fields(self, 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.
"""
template = ''
return template, data
def validate_registration(self, req):
"""Check registration form input.
Returns a RegistrationError with error message, or None on success.
"""
# Nicer than a plain NotImplementedError.
raise NotImplementedError, _(
"No check method 'validate_registration' defined in %(module)s",
module=self.__class__.__name__)
class BasicCheck(GenericRegistrationInspector):
"""A collection of basic checks.
This includes checking for
* emptiness (no user input for username and/or password)
* some blacklisted username characters
* upper-cased usernames (reserved for Trac permission actions)
* some reserved usernames
* a username duplicate in configured password stores
"""
def validate_registration(self, req):
acctmgr = AccountManager(self.env)
username = acctmgr.handle_username_casing(
req.args.get('username', '').strip())
if not username:
raise RegistrationError(N_("Username cannot be empty."))
# Always exclude some special characters, i.e.
# ':' can't be used in HtPasswdStore
# '[' and ']' can't be used in SvnServePasswordStore
blacklist = acctmgr.username_char_blacklist
if containsAny(username, blacklist):
pretty_blacklist = ''
for c in blacklist:
if pretty_blacklist == '':
pretty_blacklist = tag(' \'', tag.b(c), '\'')
else:
pretty_blacklist = tag(pretty_blacklist,
', \'', tag.b(c), '\'')
raise RegistrationError(N_(
"The username must not contain any of these characters: %s"),
tag.b(pretty_blacklist)
)
# All upper-cased names are reserved for permission action names.
if username.isupper():
raise RegistrationError(N_(
"A username with only upper-cased characters is not allowed.")
)
# Prohibit some user names, that are important for Trac and therefor
# reserved, even if not in the permission store for some reason.
if username.lower() in ['anonymous', 'authenticated']:
raise RegistrationError(N_("Username %s is not allowed."),
tag.b(username)
)
# NOTE: A user may exist in a password store but not in the permission
# store. I.e. this happens, when the user (from the password store)
# never logged in into Trac. So we have to perform this test here
# and cannot just check for the user being in the permission store.
# And better obfuscate whether an existing user or group name
# was responsible for rejection of this user name.
for store_user in acctmgr.get_users():
# Do it carefully by disregarding case.
if store_user.lower() == username.lower():
raise RegistrationError(N_(
"Another account or group already exists, who's name "
"differs from %s only by case or is identical."),
tag.b(username)
)
# Password consistency checks follow.
password = req.args.get('password')
if not password:
raise RegistrationError(N_("Password cannot be empty."))
elif password != req.args.get('password_confirm'):
raise RegistrationError(N_("The passwords must match."))
class BotTrapCheck(GenericRegistrationInspector):
"""A collection of simple bot checks.
This check is bypassed for requests by an admin user.
"""
reg_basic_token = Option('account-manager', 'register_basic_token', '',
doc="A string required as input to pass verification.")
def render_registration_fields(self, req, data):
"""Add a hidden text input field to the registration form, and
a visible one with mandatory input as well, if token is configured.
"""
if self.reg_basic_token:
# Preserve last input for editing on failure instead of typing
# everything again.
old_value = req.args.get('basic_token', '')
# TRANSLATOR: Hint for visible bot trap registration input field.
hint = tag.p(Markup(_(
"""Please type [%(token)s] as verification token,
exactly replicating everything within the braces.""",
token=tag.b(self.reg_basic_token))), class_='hint')
insert = tag(
tag.label(_("Parole:"),
tag.input(type='text', name='basic_token', size=20,
class_='textwidget', value=old_value)),
hint
)
else:
insert = None
# TRANSLATOR: Registration form hint for hidden bot trap input field.
insert = tag(insert,
tag.input(type='hidden', name='sentinel',
title=_("Better do not fill this field."))
)
return insert, data
def validate_registration(self, req):
if req.perm.has_permission('ACCTMGR_USER_ADMIN'):
return
# Input must be an exact replication of the required token.
basic_token = req.args.get('basic_token', '')
# Unlike the former, the hidden bot-trap input field must stay empty.
keep_empty = req.args.get('sentinel', '')
if keep_empty or self.reg_basic_token and \
self.reg_basic_token != basic_token:
raise RegistrationError(N_("Are you human? If so, try harder!"))
class EmailCheck(GenericRegistrationInspector):
"""A collection of checks for email addresses.
This check is bypassed, if account verification is disabled.
"""
def render_registration_fields(self, req, data):
"""Add an email address text input field to the registration form."""
# Preserve last input for editing on failure instead of typing
# everything again.
old_value = req.args.get('email', '').strip()
insert = tag.label(_("Email:"),
tag.input(type='text', name='email', size=20,
class_='textwidget', value=old_value)
)
# Deferred import required to aviod circular import dependencies.
from acct_mgr.web_ui import AccountModule
reset_password = AccountModule(self.env).reset_password_enabled
verify_account = is_enabled(self.env, EmailVerificationModule) and \
AccountManager(self.env).verify_email
if verify_account:
# TRANSLATOR: Registration form hints for a mandatory input field.
hint = tag.p(_("""The email address is required for Trac to send
you a verification token."""), class_='hint')
if reset_password:
hint = tag(hint, tag.p(_(
"""Entering your email address will also enable you
to reset your password if you ever forget it."""),
class_='hint')
)
return tag(insert, hint), data
elif reset_password:
# TRANSLATOR: Registration form hint, if email input is optional.
hint = tag.p(_("""Entering your email address will enable you to
reset your password if you ever forget it."""),
class_='hint')
return dict(optional=tag(insert, hint)), data
else:
# Always return the email text input itself as optional field.
return dict(optional=insert), data
def validate_registration(self, req):
acctmgr = AccountManager(self.env)
email = req.args.get('email', '').strip()
if is_enabled(self.env, EmailVerificationModule) and \
acctmgr.verify_email:
if not email:
raise RegistrationError(N_(
"You must specify a valid email address.")
)
elif email_associated(self.env, email):
raise RegistrationError(N_(
"The email address specified is already in use. "
"Please specify a different one.")
)
class RegExpCheck(GenericRegistrationInspector):
"""A collection of checks based on regular expressions.
It depends on EmailCheck being enabled too for using it's input field.
Likewise email checking is bypassed, if account verification is disabled.
"""
username_regexp = Option('account-manager', 'username_regexp',
r'(?i)^[A-Z0-9.\-_]{5,}$',
doc="A validation regular expression describing new usernames.")
email_regexp = Option('account-manager', 'email_regexp',
r'(?i)^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$',
doc="A validation regular expression describing new account emails.")
def validate_registration(self, req):
acctmgr = AccountManager(self.env)
username = acctmgr.handle_username_casing(
req.args.get('username', '').strip())
if self.username_regexp != "" and \
not re.match(self.username_regexp.strip(), username):
raise RegistrationError(N_(
"Username %s doesn't match local naming policy."),
tag.b(username)
)
email = req.args.get('email', '').strip()
if acctmgr.verify_email and is_enabled(self.env, EmailCheck) and \
is_enabled(self.env, EmailVerificationModule):
if self.email_regexp.strip() != "" and \
not re.match(self.email_regexp.strip(), email):
raise RegistrationError(N_(
"The email address specified appears to be invalid. "
"Please specify a valid email address.")
)
class UsernamePermCheck(GenericRegistrationInspector):
"""Check for usernames referenced in the permission system.
This check is bypassed for requests by an admin user.
"""
def validate_registration(self, req):
if req.perm.has_permission('ACCTMGR_USER_ADMIN'):
return
username = AccountManager(self.env).handle_username_casing(
req.args.get('username', '').strip())
# NOTE: We can't use 'get_user_permissions(username)' here
# as this always returns a list - even if the user doesn't exist.
# In this case the permissions of "anonymous" are returned.
#
# Also note that we can't simply compare the result of
# 'get_user_permissions(username)' to some known set of permission,
# i.e. "get_user_permissions('authenticated') as this is always
# false when 'username' is the name of an existing permission group.
#
# And again obfuscate whether an existing user or group name
# was responsible for rejection of this username.
for (perm_user, perm_action) in \
perm.PermissionSystem(self.env).get_all_permissions():
if perm_user.lower() == username.lower():
raise RegistrationError(N_(
"Another account or group already exists, who's name "
"differs from %s only by case or is identical."),
tag.b(username)
)
class RegistrationModule(CommonTemplateProvider):
"""Provides users the ability to register a new account.
Requires configuration of the AccountManager module in trac.ini.
"""
implements(chrome.INavigationContributor, IRequestHandler)
def __init__(self):
self.acctmgr = AccountManager(self.env)
self._enable_check(log=True)
def _enable_check(self, log=False):
env = self.env
writable = self.acctmgr.supports('set_password')
ignore_case = auth.LoginModule(env).ignore_case
if log:
if not writable:
self.log.warn('RegistrationModule is disabled because the '
'password store does not support writing.')
if ignore_case:
self.log.debug('RegistrationModule will allow lowercase '
'usernames only and convert them forcefully '
'as required, while \'ignore_auth_case\' is '
'enabled in [trac] section of your trac.ini.')
return is_enabled(env, self.__class__) and writable
enabled = property(_enable_check)
# INavigationContributor methods
def get_active_navigation_item(self, req):
return 'register'
def get_navigation_items(self, req):
if not self.enabled:
return
if req.authname == 'anonymous':
yield 'metanav', 'register', tag.a(_("Register"),
href=req.href.register())
# IRequestHandler methods
def match_request(self, req):
return req.path_info == '/register' and self._enable_check(log=True)
def process_request(self, req):
acctmgr = self.acctmgr
if req.authname != 'anonymous':
req.redirect(req.href.prefs('account'))
action = req.args.get('action')
name = req.args.get('name', '').strip()
username = acctmgr.handle_username_casing(req.args.get('username',
'').strip())
data = {
'_dgettext': dgettext,
'acctmgr': dict(name=name, username=username),
'ignore_auth_case': self.config.getbool('trac', 'ignore_auth_case')
}
verify_enabled = is_enabled(self.env, EmailVerificationModule) and \
acctmgr.verify_email
data['verify_account_enabled'] = verify_enabled
if req.method == 'POST' and action == 'create':
try:
# Check request and prime account on success.
acctmgr.validate_registration(req)
except RegistrationError, e:
# Attempt deferred translation.
message = gettext(e.message)
# Check for (matching number of) message arguments before
# attempting string substitution.
if e.msg_args and \
len(e.msg_args) == len(re.findall('%s', message)):
message = message % e.msg_args
chrome.add_warning(req, Markup(message))
else:
if verify_enabled:
chrome.add_notice(req, Markup(tag.span(Markup(_(
"""Your username has been successfully registered but
your account still requires activation. Please login
as user %(user)s, and follow the instructions.""",
user=tag.b(username)))))
)
req.redirect(req.href.login())
chrome.add_notice(req, Markup(tag.span(Markup(_(
"""Registration has been finished successfully.
You may log in as user %(user)s now.""",
user=tag.b(username)))))
)
req.redirect(req.href.login())
# Collect additional fields from IAccountRegistrationInspector's.
fragments = dict(required=[], optional=[])
for inspector in acctmgr._register_check:
try:
fragment, f_data = inspector.render_registration_fields(req,
data)
except TypeError, e:
# Add some robustness by logging the most likely errors.
self.env.log.warn("%s.render_registration_fields failed: %s"
% (inspector.__class__.__name__, e))
fragment = None
if fragment:
try:
# Python<2.5: Can't have 'except' and 'finally' in same
# 'try' statement together.
try:
if 'optional' in fragment.keys():
fragments['optional'].append(fragment['optional'])
except AttributeError:
# No dict, just append Genshi Fragment or str/unicode.
fragments['required'].append(fragment)
else:
fragments['required'].append(fragment.get('required',
''))
finally:
data.update(f_data)
data['required_fields'] = fragments['required']
data['optional_fields'] = fragments['optional']
return 'register.html', data, None
class EmailVerificationModule(CommonTemplateProvider):
"""Performs email verification on every new or changed address.
A working email sender for Trac (!TracNotification or !TracAnnouncer)
is strictly required to enable this module's functionality.
Anonymous users should register and perms should be tweaked, so that
anonymous users can't edit wiki pages and change or create tickets.
So this email verification code won't be used on them.
"""
implements(IRequestFilter, IRequestHandler)
def __init__(self, *args, **kwargs):
self.email_enabled = True
if self.config.getbool('announcer', 'email_enabled') != True and \
self.config.getbool('notification', 'smtp_enabled') != True:
self.email_enabled = False
if is_enabled(self.env, self.__class__) == True:
self.env.log.warn(
' '.join([self.__class__.__name__,
"can't work because of missing email setup."])
)
# IRequestFilter methods
def pre_process_request(self, req, handler):
if not req.session.authenticated:
# Permissions for anonymous users remain unchanged.
return handler
elif req.path_info == '/prefs' and req.method == 'POST' and \
not 'restore' in req.args:
try:
EmailCheck(self.env).validate_registration(req)
# Check passed without error: New email address seems good.
except RegistrationError, e:
# Attempt to change email to an empty or invalid
# address detected, resetting to previously stored value.
chrome.add_warning(
req, Markup(gettext(e.message)))
req.redirect(req.href.prefs(None))
if AccountManager(self.env).verify_email and handler is not self and \
'email_verification_token' in req.session and \
not req.perm.has_permission('ACCTMGR_ADMIN'):
# TRANSLATOR: Your permissions have been limited until you ...
link = tag.a(_("verify your email address"),
href=req.href.verify_email()
)
# TRANSLATOR: ... verify your email address
chrome.add_warning(req, Markup(tag.span(Markup(_(
"Your permissions have been limited until you %(link)s.",
link=link))))
)
req.perm = perm.PermissionCache(self.env, 'anonymous')
return handler
def post_process_request(self, req, template, data, content_type):
if not req.session.authenticated:
# Don't start the email verification procedure on anonymous users.
return template, data, content_type
email = req.session.get('email')
# Only send verification if the user entered an email address.
acctmgr = AccountManager(self.env)
if acctmgr.verify_email and self.email_enabled is True and email and \
email != req.session.get('email_verification_sent_to') and \
not req.perm.has_permission('ACCTMGR_ADMIN'):
req.session['email_verification_token'] = self._gen_token()
req.session['email_verification_sent_to'] = email
acctmgr._notify(
'email_verification_requested',
req.authname,
req.session['email_verification_token']
)
# TRANSLATOR: An email has been sent to <%(email)s>
# with a token to ... (the link label for following message)
link = tag.a(_("verify your new email address"),
href=req.href.verify_email()
)
# TRANSLATOR: ... verify your new email address
chrome.add_notice(req, Markup(tag.span(Markup(_(
"""An email has been sent to <%(email)s> with a token to
%(link)s.""", email=email, link=link))))
)
return template, data, content_type
# IRequestHandler methods
def match_request(self, req):
return req.path_info == '/verify_email'
def process_request(self, req):
if not req.session.authenticated:
chrome.add_warning(req, Markup(tag.span(tag_(
"Please log in to finish email verification procedure.")))
)
req.redirect(req.href.login())
if 'email_verification_token' not in req.session:
chrome.add_notice(req, _("Your email is already verified."))
elif req.method == 'POST' and 'resend' in req.args:
AccountManager(self.env)._notify(
'email_verification_requested',
req.authname,
req.session['email_verification_token']
)
chrome.add_notice(req,
_("A notification email has been resent to <%s>."),
req.session.get('email')
)
elif 'verify' in req.args:
# allow via POST or GET (the latter for email links)
if req.args['token'] == req.session['email_verification_token']:
del req.session['email_verification_token']
chrome.add_notice(
req, _("Thank you for verifying your email address.")
)
req.redirect(req.href.prefs())
else:
chrome.add_warning(req, _("Invalid verification token"))
data = {'_dgettext': dgettext}
if 'token' in req.args:
data['token'] = req.args['token']
if 'email_verification_token' not in req.session:
data['button_state'] = { 'disabled': 'disabled' }
return 'verify_email.html', data, None
def _gen_token(self):
return base64.urlsafe_b64encode(urandom(6))
|