本文整理汇总了Python中acct_mgr.api.AccountManager类的典型用法代码示例。如果您正苦于以下问题:Python AccountManager类的具体用法?Python AccountManager怎么用?Python AccountManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AccountManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_registration
def validate_registration(self, req):
if req.authname and req.authname != 'anonymous':
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)
)
示例2: post_process_request
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=tag(email), link=link))))
)
return template, data, content_type
示例3: validate_registration
def validate_registration(self, req):
if req.path_info == '/prefs':
return
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 contains_any(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(tag_(
"Another account or group already exists, who's name "
"differs from %(username)s only by case or is identical.",
username=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."))
示例4: __init__
def __init__(self):
self.account_manager = None
try:
from acct_mgr.api import AccountManager
self.account_manager = AccountManager(self.env)
except ImportError:
pass
示例5: _remote_user
def _remote_user(self, req):
"""The real authentication using configured providers and stores."""
user = req.args.get('user')
self.env.log.debug("LoginModule._remote_user: Authentication attempted for '%s'" % user)
password = req.args.get('password')
if not user or not password:
return None
acctmgr = AccountManager(self.env)
acctmod = AccountModule(self.env)
if acctmod.reset_password_enabled == True:
reset_store = acctmod.store
else:
reset_store = None
if acctmgr.check_password(user, password) == True:
if reset_store:
# Purge any temporary password set for this user before,
# to avoid DOS by continuously triggered resets from
# a malicious third party.
if reset_store.delete_user(user) == True and \
'PASSWORD_RESET' not in req.environ:
db = self.env.get_db_cnx()
cursor = db.cursor()
cursor.execute("""
DELETE
FROM session_attribute
WHERE sid=%s
AND name='force_change_passwd'
AND authenticated=1
""", (user,))
db.commit()
return user
# Alternative authentication provided by password reset procedure
elif reset_store:
if reset_store.check_password(user, password) == True:
# Lock, required to prevent another authentication
# (spawned by `set_password()`) from possibly deleting
# a 'force_change_passwd' db entry for this user.
req.environ['PASSWORD_RESET'] = user
# Change password to temporary password from reset procedure
acctmgr.set_password(user, password)
return user
return None
示例6: validate_registration
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.")
)
示例7: process_admin_request
def process_admin_request(self, req, category, page, path_info):
mgr = AccountManager(self.env)
if path_info:
return self._process_user_request(req, category, page,
path_info, mgr)
else:
if req.method == 'POST':
if req.args.get('add'):
self._do_add(req, mgr)
elif req.args.get('remove'):
self._do_remove(req, mgr)
# run user list through a set to work around a bug in
# account manager
# see http://trac-hacks.org/ticket/180
users = list(sets.Set(mgr.get_users()))
users.sort()
req.hdf['admin.users'] = \
[{'name': u,
'key': u,
'href': self.env.href.admin(category, page, u)
} for u in users]
return 'admin_users.cs', None
示例8: get_users
def get_users(self):
users = {}
try:
from acct_mgr.api import AccountManager, get_user_attribute
acct_mgr = AccountManager(self.env)
for username in acct_mgr.get_users():
users[username] = { 'username': username }
for username, status in get_user_attribute(self.env, username=None, authenticated=None).iteritems():
user = users.get(username)
if user is not None and 1 in status:
user['name'] = status[1].get('name')
user['email'] = status[1].get('email')
user.update(self.get_last_login(username))
except:
for username, name, email in self.env.get_known_users():
user = { 'username': username, 'name': name, 'email': email }
user.update(self.get_last_login(username))
users[username] = user
return users
示例9: authenticate
def authenticate(self, req):
if req.method == 'POST' and req.path_info.startswith('/login'):
user = self._remote_user(req)
acctmgr = AccountManager(self.env)
guard = AccountGuard(self.env)
if guard.login_attempt_max_count > 0:
if user is None:
if req.args.get('user_locked') is None:
# get user for failed authentication attempt
f_user = req.args.get('user')
req.args['user_locked'] = False
if acctmgr.user_known(f_user) is True:
if guard.user_locked(f_user) is False:
# log current failed login attempt
guard.failed_count(f_user, req.remote_addr)
if guard.user_locked(f_user) is True:
# step up lock time prolongation
# only when just triggering the lock
guard.lock_count(f_user, 'up')
req.args['user_locked'] = True
else:
# enforce lock
req.args['user_locked'] = True
else:
if guard.user_locked(user) is not False:
req.args['user_locked'] = True
# void successful login as long as user is locked
user = None
else:
req.args['user_locked'] = False
if req.args.get('failed_logins') is None:
# Reset failed login attempts counter
req.args['failed_logins'] = guard.failed_count(
user, reset = True)
if 'REMOTE_USER' not in req.environ:
req.environ['REMOTE_USER'] = user
return auth.LoginModule.authenticate(self, req)
示例10: fetch_user_data
def fetch_user_data(env, req):
acctmgr = AccountManager(env)
guard = AccountGuard(env)
accounts = {}
for username in acctmgr.get_users():
if req.perm.has_permission('ACCTMGR_USER_ADMIN'):
url = req.href.admin('accounts', 'users', user=username)
else:
url = None
accounts[username] = {'username': username, 'review_url': url}
if guard.user_locked(username):
accounts[username]['locked'] = True
t_lock = guard.lock_time(username)
if t_lock > 0:
t_release = guard.pretty_release_time(req, username)
accounts[username]['release_hint'] = _(
"Locked until %(t_release)s",
t_release=t_release)
for acct, status in get_user_attribute(env, username=None,
authenticated=None).iteritems():
account = accounts.get(acct)
if account is not None and 1 in status:
# Only use attributes related to authenticated
# accounts.
account['name'] = status[1].get('name')
account['email'] = status[1].get('email')
if account['email']:
account['email'] = Chrome(env).format_author(req,
account['email'])
ts_seen = last_seen(env)
if ts_seen is not None:
for username, last_visit in ts_seen:
account = accounts.get(username)
if account and last_visit:
account['last_visit'] = to_datetime(last_visit)
return sorted(accounts.itervalues(), key=lambda acct: acct['username'])
示例11: setUp
def setUp(self):
_BaseTestCase.setUp(self)
self.mgr = AccountManager(self.env)
self.store = SessionStore(self.env)
self.store.set_password('user', 'passwd')
args = dict(username='user', name='', email='')
incookie = Cookie()
incookie['trac_session'] = '123456'
self.req = Mock(authname='', args=args, authenticated=True,
base_path='/', callbacks=dict(),
chrome={'warnings': [], 'notices': []},
href=Mock(prefs=lambda x: None),
incookie=incookie, outcookie=Cookie(),
redirect=lambda x: None)
self.req.path_info = '/'
示例12: AccountManagerAdminPage
class AccountManagerAdminPage(Component):
implements(IAdminPanelProvider, ITemplateProvider)
def __init__(self):
self.account_manager = AccountManager(self.env)
# IAdminPageProvider
def get_admin_panels(self, req):
if req.perm.has_permission("TRAC_ADMIN"):
yield ("accounts", "Accounts", "config", "Configuration")
yield ("accounts", "Accounts", "users", "Users")
def render_admin_panel(self, req, cat, page, path_info):
if page == "config":
return self._do_config(req)
elif page == "users":
return self._do_users(req)
def _do_config(self, req):
stores = StoreOrder(stores=self.account_manager.stores, list=self.account_manager.password_store)
if req.method == "POST":
_setorder(req, stores)
self.config.set("account-manager", "password_store", ",".join(stores.get_enabled_store_names()))
for store in stores.get_all_stores():
for attr, option in _getoptions(store):
newvalue = req.args.get("%s.%s" % (store.__class__.__name__, attr))
self.log.debug("%s.%s: %s" % (store.__class__.__name__, attr, newvalue))
if newvalue is not None:
self.config.set(option.section, option.name, newvalue)
self.config.save()
self.config.set("account-manager", "force_passwd_change", req.args.get("force_passwd_change"))
self.config.set("account-manager", "persistent_sessions", req.args.get("persistent_sessions"))
self.config.save()
sections = []
for store in self.account_manager.stores:
options = []
for attr, option in _getoptions(store):
opt_val = option.__get__(store, store)
opt_val = isinstance(opt_val, Component) and opt_val.__class__.__name__ or opt_val
options.append({"label": attr, "name": "%s.%s" % (store.__class__.__name__, attr), "value": opt_val})
continue
sections.append(
{
"name": store.__class__.__name__,
"classname": store.__class__.__name__,
"order": stores[store],
"options": options,
}
)
continue
sections = sorted(sections, key=lambda i: i["name"])
numstores = range(0, stores.numstores() + 1)
data = {
"sections": sections,
"numstores": numstores,
"force_passwd_change": self.account_manager.force_passwd_change,
"persistent_sessions": self.account_manager.persistent_sessions,
}
return "admin_accountsconfig.html", data
def _do_users(self, req):
perm = PermissionSystem(self.env)
listing_enabled = self.account_manager.supports("get_users")
create_enabled = self.account_manager.supports("set_password")
password_change_enabled = self.account_manager.supports("set_password")
delete_enabled = self.account_manager.supports("delete_user")
data = {
"listing_enabled": listing_enabled,
"create_enabled": create_enabled,
"delete_enabled": delete_enabled,
"password_change_enabled": password_change_enabled,
"acctmgr": {"username": None, "name": None, "email": None},
}
if req.method == "POST":
if req.args.get("add"):
if create_enabled:
try:
_create_user(req, self.env, check_permissions=False)
except TracError, e:
data["registration_error"] = e.message
data["acctmgr"] = e.acctmgr
else:
data["registration_error"] = "The password store does " "not support creating users"
elif req.args.get("remove"):
if delete_enabled:
sel = req.args.get("sel")
sel = isinstance(sel, list) and sel or [sel]
for account in sel:
self.account_manager.delete_user(account)
else:
data["deletion_error"] = "The password store does not " "support deleting users"
elif req.args.get("change"):
if password_change_enabled:
try:
user = req.args.get("change_user")
acctmgr = {"change_username": user}
error = TracError("")
#.........这里部分代码省略.........
示例13: AccountManagerTestCase
class AccountManagerTestCase(_BaseTestCase):
def setUp(self):
_BaseTestCase.setUp(self)
self.mgr = AccountManager(self.env)
self.store = SessionStore(self.env)
self.store.set_password('user', 'passwd')
args = dict(username='user', name='', email='')
incookie = Cookie()
incookie['trac_session'] = '123456'
self.req = Mock(authname='', args=args, authenticated=True,
base_path='/', callbacks=dict(),
chrome={'warnings': [], 'notices': []},
href=Mock(prefs=lambda x: None),
incookie=incookie, outcookie=Cookie(),
redirect=lambda x: None)
self.req.path_info = '/'
# Tests
def test_set_password(self):
# Can't work without at least one password store.
self.assertRaises(TracError, self.mgr.set_password, 'user', 'passwd')
self.env.config.set(
'account-manager', 'password_store', 'SessionStore')
self.mgr.set_password('user', 'passwd')
# Refuse to overwrite existing credentials, if requested.
self.assertRaises(TracError, self.mgr.set_password, 'user', 'passwd',
overwrite=False)
def test_approval_admin_keep_perm(self):
self.perm.grant_permission('admin', 'ACCTMGR_ADMIN')
# Some elevated permission action.
action = 'USER_VIEW'
self.assertFalse(action in PermissionCache(self.env))
req = self.req
req.perm = PermissionCache(self.env, 'admin')
req.session = Session(self.env, req)
req.session.save()
self.mgr.pre_process_request(req, None)
self.assertTrue(action in req.perm)
# Mock an authenticated request with account approval pending.
req.session['approval'] = 'pending'
req.session.save()
# Don't touch admin user requests.
self.mgr.pre_process_request(req, None)
self.assertTrue(action in req.perm)
def test_approval_user_strip_perm(self):
# Some elevated permission action.
action = 'USER_VIEW'
self.assertFalse(action in PermissionCache(self.env))
self.perm.grant_permission('user', action)
req = self.req
req.perm = PermissionCache(self.env, 'user')
req.session = Session(self.env, req)
req.session.save()
self.mgr.pre_process_request(req, None)
self.assertTrue(action in req.perm)
# Mock an authenticated request with account approval pending.
req.session['approval'] = 'pending'
req.session.save()
# Remove elevated permission, if account approval is pending.
self.mgr.pre_process_request(req, None)
self.assertFalse(action in req.perm)
def test_maybe_update_hash(self):
# Configure another, primary password store.
self.env.config.set('account-manager', 'password_store',
'HtDigestStore, SessionStore')
self.env.config.set('account-manager', 'htdigest_file', '.htdigest')
self.env.db_transaction("""
INSERT INTO session_attribute (sid,authenticated,name,value)
VALUES (%s,%s,%s,%s)
""", ('user', 1, 'password_refreshed', '1'))
# Refresh not happening due to 'password_refreshed' attribute.
self.mgr._maybe_update_hash('user', 'passwd')
for _, in self.env.db_query("""
SELECT value FROM session_attribute
WHERE sid='user'
AND authenticated=1
AND name='password'
"""):
break
else:
self.fail("Session attribute 'password' not found.")
self.env.db_transaction("""
DELETE FROM session_attribute
WHERE sid='user'
AND authenticated=1
AND name='password_refreshed'
""")
#.........这里部分代码省略.........
示例14: __init__
def __init__(self):
self.acctmgr = AccountManager(self.env)
self._enable_check(log=True)
示例15: RegistrationModule
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)
require_approval = BoolOption(
'account-manager', 'require_approval', False, doc="""
Whether account registration requires administrative approval to
enable the account or not.
""")
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.warning("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 env.is_enabled(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', '')
if isinstance(name, list):
raise HTTPBadRequest(_("Invalid request arguments."))
name = name.strip()
username = req.args.get('username', '')
if isinstance(username, list):
raise HTTPBadRequest(_("Invalid request arguments."))
username = acctmgr.handle_username_casing(username.strip())
data = {
'_dgettext': dgettext,
'acctmgr': {'name': name, 'username': username},
'ignore_auth_case': self.config.getbool('trac',
'ignore_auth_case')
}
verify_enabled = self.env.is_enabled(EmailVerificationModule) and \
EmailVerificationModule(self.env).verify_email
data['verify_account_enabled'] = verify_enabled
if req.method == 'POST' and action == 'create':
try:
try:
# Check request and prime account on success.
acctmgr.validate_account(req, True)
except NotificationError, e:
chrome.add_warning(req, _(
"Error raised while sending a change notification."
) + _("You should report that issue to a Trac admin."))
self.log.error(
'Unable to send registration notification: %s',
exception_to_unicode(e, traceback=True))
except RegistrationError, e:
chrome.add_warning(req, e)
else:
if self.require_approval:
set_user_attribute(self.env, username, 'approval',
N_('pending'))
# Notify admin user about registration pending for review.
try:
acctmgr._notify('registration_approval_required',
username)
except NotificationError, e:
chrome.add_warning(req, _(
"Error raised while sending a change "
"notification.") + _(
#.........这里部分代码省略.........