本文整理汇总了Python中trac.perm.PermissionSystem类的典型用法代码示例。如果您正苦于以下问题:Python PermissionSystem类的具体用法?Python PermissionSystem怎么用?Python PermissionSystem使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PermissionSystem类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _to_users
def _to_users(self, users_perms_and_groups, ticket):
"""Finds all users contained in the list of `users_perms_and_groups`
by recursive lookup of users when a `group` is encountered.
"""
ps = PermissionSystem(self.env)
groups = ps.get_groups_dict()
def append_owners(users_perms_and_groups):
for user_perm_or_group in users_perms_and_groups:
if user_perm_or_group == 'authenticated':
owners.update(set(u[0] for u in self.env.get_known_users()))
elif user_perm_or_group.isupper():
perm = user_perm_or_group
for user in ps.get_users_with_permission(perm):
if perm in PermissionCache(self.env, user,
ticket.resource):
owners.add(user)
elif user_perm_or_group not in groups:
owners.add(user_perm_or_group)
else:
append_owners(groups[user_perm_or_group])
owners = set()
append_owners(users_perms_and_groups)
return sorted(owners)
示例2: _do_notice
def _do_notice(self, req):
perm = PermissionSystem(self.env)
perms = perm.get_all_permissions()
self._get_notice_options()
(userinfos, groupinfos) = self._get_infos(perms)
if req.method == 'POST':
if req.args.get('fill'):
self._set_notice_options(req)
if req.args.get('use_ldap'):
self._fill_from_ldap(userinfos,groupinfos)
if req.args.get('use_file'):
self._fill_from_file(req,userinfos,groupinfos)
if req.args.get('change'):
self._fill_from_fields(req,userinfos,groupinfos)
if req.args.get('rmuser'):
self._rm_user(req,userinfos,groupinfos)
(userinfos, groupinfos) = self._get_infos(perms)
if req.args.get('rminfo'):
self._rm_info(req,userinfos,groupinfos)
if req.args.get('rmall'):
self._rm_all(req,userinfos,groupinfos)
(userinfos, groupinfos) = self._get_infos(perms)
if (len(userinfos) > 0) or (len(groupinfos)>0):
self.error_message = "As long as permissions are defined for users/group, " + \
"they cannot be delete from this list."
if req.args.get('extract'):
self._extract_groups(req,userinfos,groupinfos)
req.hdf['admin.userinfos'] = userinfos
req.hdf['admin.groupinfos'] = groupinfos
req.hdf['admin.options'] = self.options
if self.error_message:
req.hdf['admin.error_message'] = self.error_message
return 'admin_notice.cs', None
示例3: authenhandler
def authenhandler(req):
pw = req.get_basic_auth_pw()
user = req.user
env = _get_env(req)
if env is None:
return apache.HTTP_FORBIDDEN
global acct_mgr
if acct_mgr is None:
from acct_mgr.api import AccountManager
acct_mgr = AccountManager
options = req.get_options()
#if 'TracPerm' not in options:
# req.log_error('mod_auth_acctmgr: You must specify a permission')
# return apache.HTTP_FORBIDDEN
perm = options.get('TracPerm')
if acct_mgr(env).check_password(user, pw):
if perm:
user_perms = PermissionSystem(env).get_user_permissions(user)
if not user_perms.get(perm):
return apache.HTTP_FORBIDDEN
return apache.OK
else:
return apache.HTTP_UNAUTHORIZED
示例4: _BaseTestCase
class _BaseTestCase(unittest.TestCase):
def setUp(self):
self.env = EnvironmentStub(enable=[
'trac.*', 'acct_mgr.api.*', 'acct_mgr.admin.*',
'acct_mgr.db.*', 'acct_mgr.register.*',
'acct_mgr.pwhash.HtDigestHashMethod',
'acct_mgr.tests.admin.BadCheck',
'acct_mgr.tests.admin.DummyCheck'
])
self.env.path = tempfile.mkdtemp()
self.perm = PermissionSystem(self.env)
# Create a user reference in the permission system.
self.perm.grant_permission('admin', 'ACCTMGR_ADMIN')
# Prepare a generic request object for admin actions.
self.req = Mock(authname='admin', method='GET',
args=dict(), abs_href=self.env.abs_href,
chrome=dict(notices=[], warnings=[]),
href=self.env.abs_href, locale='',
redirect=lambda x: None, session=dict(), tz=''
)
self.req.perm = PermissionCache(self.env, 'admin')
self.acctmgr = AccountManager(self.env)
def tearDown(self):
shutil.rmtree(self.env.path)
示例5: _users_query
def _users_query(self, q, limit=10):
from simplifiedpermissionsadminplugin.simplifiedpermissions import SimplifiedPermissions
if SimplifiedPermissions and self.env.is_enabled(SimplifiedPermissions):
sp = SimplifiedPermissions(self.env)
# Keep track of users that have already been found to prevent
# yielding duplicates of users belonging to several groups
yielded_sids = set()
for group, data in sp.group_memberships().items():
for member in data['members']:
if q in member.sid and member.sid not in yielded_sids:
# if the 'never logged in' text changes, then update
# plugins/open/autocompleteplugin/autocompleteplugin/htdocs/js/jquery.tracautocomplete.js
yield {'sid': member.sid,
'name': member.get('name', member.sid),
'email': member.get('email','')}
yielded_sids.add(member.sid)
else:
perm = PermissionSystem(self.env)
users = [sid
for sid, permission in perm.get_all_permissions()
if sid not in set("anonymous", "authenticated", "admin")]
for sid in sorted(set(users)):
if q in sid:
session = DetachedSession(self.env, sid)
yield {'sid': sid,
'name': session.get('name',''),
'email': session.get('email','Never logged in')}
示例6: create_user_and_grant_permissions
def create_user_and_grant_permissions(self, req, team_member):
if self.use_account_manager_integration(team_member.name):
password = team_member.name
AccountManager(self.env).set_password(team_member.name, password)
permission_system = PermissionSystem(self.env)
if not permission_system.check_permission(Role.TEAM_MEMBER, team_member.name):
permission_system.grant_permission(team_member.name, Role.TEAM_MEMBER)
示例7: _get_groups
def _get_groups(self, user):
# Get initial subjects
groups = set([user])
for provider in self.group_providers:
for group in provider.get_permission_groups(user):
groups.add(group)
# Essentially the default trac PermissionStore ignores user provided
# groups so we have to look them up manually:
# changed this to only do this for the default permission
# store this has been reported as broken/very slow for the
# LDAP permission store
ps = PermissionSystem(self.env)
if isinstance(ps.store, DefaultPermissionStore):
perms = ps.get_all_permissions()
repeat = True
while repeat:
repeat = False
for subject, action in perms:
if subject in groups and not action.isupper() and action not in groups:
groups.add(action)
repeat = True
return groups
示例8: render_usermanager_admin_panel
def render_usermanager_admin_panel(self, req, panel, user, path_info):
user_actions = self._get_user_permissions(user)
all_user_actions = PermissionSystem(self.env).get_user_permissions(user.username)
actions = PermissionSystem(self.env).get_actions()+list(set([group for group, permissions in PermissionSystem(self.env).get_all_permissions()]))
data = dict(actions=actions,
all_user_actions=all_user_actions,
user_actions=user_actions,
permsys = PermissionSystem(self.env),
messages=[], errors=[])
if req.method=="POST":
updated_user_permissions = req.args.getlist('um_permission')
for action in actions:
if action in updated_user_permissions:
if not all_user_actions.has_key(action):
try:
PermissionSystem(self.env).grant_permission(user.username, action)
data['messages'].append(_("Granted permission [%s] for user [%s].")%(action, user.username))
except Exception, e:
data['errors'].append(e)
else:
if user_actions.has_key(action):
try:
PermissionSystem(self.env).revoke_permission(user.username, action)
data['messages'].append(_("Revoked permission [%s] for user [%s].")%(action, user.username))
except Exception, e:
data['errors'].append(e)
示例9: check_permission
def check_permission(self, action, username, resource, perm):
if ConfigObj is None:
self.log.error('configobj package not found')
return None
if self.authz_file and not self.authz_mtime or \
os.path.getmtime(self.get_authz_file()) > self.authz_mtime:
self.parse_authz()
resource_key = self.normalise_resource(resource)
self.log.debug('Checking %s on %s', action, resource_key)
permissions = self.authz_permissions(resource_key, username)
if permissions is None:
return None # no match, can't decide
elif permissions == ['']:
return False # all actions are denied
# FIXME: expand all permissions once for all
ps = PermissionSystem(self.env)
for deny, perms in groupby(permissions,
key=lambda p: p.startswith('!')):
if deny and action in ps.expand_actions([p[1:] for p in perms]):
return False # action is explicitly denied
elif action in ps.expand_actions(perms):
return True # action is explicitly granted
return None # no match for action, can't decide
示例10: get_recipients
def get_recipients(self, pagename):
QUERY_SIDS = """SELECT sid from session_attribute
WHERE name=%s AND value LIKE %s"""
QUERY_EMAILS = """SELECT value FROM session_attribute
WHERE name=%s AND sid=%s"""
tos = []
with self.env.db_query as db:
cursor = db.cursor()
cursor.execute(
QUERY_SIDS, ('watched_pages', '%,' + pagename + ',%'))
sids = cursor.fetchall()
self.env.log.debug("SID'S TO NOTIFY: %s", sids)
perm = PermissionSystem(self.env)
resource = Resource('wiki', pagename)
for sid in sids:
if sid[0] != self.change_author and perm.check_permission(action='WIKI_VIEW', username=sid[0], resource=resource):
self.env.log.debug('SID: %s', sid[0])
cursor.execute(QUERY_EMAILS, ('email', sid[0]))
sid_email = cursor.fetchone()
if sid_email is not None:
tos.append(sid_email[0])
self.env.log.debug("TO's TO NOTIFY: %s", tos)
return (tos, [])
示例11: import_perms
def import_perms(self, template_path):
"""Creates permissions from data stored in groups.xml.
Parses this XML file to get the data we need to insert into the
permissions table. If we have this data we clear the existing
permission data, and then insert the template data using the
PermissionSystem API.
If we don't create a perm_data list, we exit the function and
continue to use default data.
"""
# parse the tree to get username, action data
# we know the file exists as we check that in import_groups()
tree = ET.ElementTree(file=template_path)
perm_data = [(subelement.attrib['name'], subelement.attrib['action'])
for perm in tree.getroot() for subelement in perm
if subelement.attrib['name'].strip()]
@self.env.with_transaction()
def clear_perms(db):
"""Clears the whole permissions table of default data."""
cursor = db.cursor()
self.log.info("Clearing permissions table")
# cant pass the table name as an arg so its hard coded
cursor.execute("DELETE FROM permission")
self.log.info("Inserting template data into permissions table")
perm_system = PermissionSystem(self.env).store
for username, action in perm_data:
perm_system.grant_permission(username, action)
示例12: _has_edit_perm
def _has_edit_perm(self,pagename,username,req):
perm_obj=PermissionSystem(self.env)
user_permissions=perm_obj.get_user_permissions(username)
perm_list=[]
for i in user_permissions:
if user_permissions[i]==True:
perm_list.append(i)
if "WIKI_MODIFY" in perm_list:
if self._is_the_creator(pagename,username,req)==True:
return True
if "TRAC_ADMIN" in perm_list:
return True
else:
cnx=self.env.get_db_cnx()
cur=cnx.cursor()
cur.execute("select count() from wiki_permission where pagename=\"%s\";"%(pagename,))
exist=cur.fetchone()
if exist[0] == 0:
cur.close()
cnx.commit()
cnx.close()
return True
cur.execute("select perm_w from wiki_permission where pagename=\"%s\" and username=\"%s\";"%(pagename,username))
perm=cur.fetchone()
cur.close()
cnx.commit()
cnx.close()
if perm and perm[0]==1:
return True
return False
return False
示例13: handle_edit_locale_admins
def handle_edit_locale_admins(self, req, locale_id):
if not locale_id:
req.redirect(req.href.admin('translations', 'locales'))
Session = session(self.env)
locale = Session.query(Locale).get(int(locale_id))
known_users = self.env.get_known_users()
errors = []
perm = PermissionSystem(self.env)
sids_without_necessary_perms = []
for admin in locale.admins:
if not 'L10N_MODERATE' in perm.get_user_permissions(admin.sid):
sids_without_necessary_perms.append(admin.sid)
if sids_without_necessary_perms:
msg = ngettext(
"%s does not have the required permissions to administrate." % \
', '.join(["'%s'" % s for s in sids_without_necessary_perms]),
"%s don't have the required permissions to administrate." % \
', '.join(["'%s'" % s for s in sids_without_necessary_perms]),
len(sids_without_necessary_perms))
errors.append(
tag(msg, _(" Don't forget to "),
tag.a(_('update permissions'),
href=req.href.admin('general', 'perm')), '.'))
if req.method == 'POST' and len(req.args.getlist('admins')) >= 1:
current_admins = req.args.getlist('current_admins')
selected = req.args.getlist('admins')
self.log.debug('Current Admins: %s', current_admins)
self.log.debug('Selected Admins: %s', selected)
allow_delete_admins = len(selected) >= 1
if not allow_delete_admins:
errors.append(
tag(_("There must be at least on admin for each locale.")))
for admin in current_admins:
if not allow_delete_admins:
break
if admin not in selected:
locale_admin = Session.query(LocaleAdmin). \
filter(locale_admin_table.c.sid==admin).first()
Session.delete(locale_admin)
for admin in selected:
if admin not in locale.admins:
locale.admins.append(LocaleAdmin(locale, admin))
Session.commit()
req.redirect(req.href.admin('translations', 'locales'))
elif req.method == 'POST' and len(req.args.getlist('admins')) < 1:
errors.append(
tag(_("There must be at least on admin for each locale.")))
data = {'locale': locale, 'known_users': known_users}
if errors:
data['error'] = tag.ul(*[tag.li(e) for e in errors if e])
return 'l10n_admin_locale_admins.html', data
示例14: add_permissions
def add_permissions(self, permissions):
perm = PermissionSystem(self.env)
for agent, p in permissions.items():
for permission in p:
try:
perm.grant_permission(agent, permission)
except:
continue
示例15: permissions
def permissions(self):
"""Deprecated (but still used by the HDF compatibility layer)
"""
self.perm.env.log.warning("perm.permissions() is deprecated and "
"is only present for HDF compatibility")
permsys = PermissionSystem(self.perm.env)
actions = permsys.get_user_permissions(self.perm.username)
return [action for action in actions if action in self]