• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python perm.PermissionSystem类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中trac.perm.PermissionSystem的典型用法代码示例。如果您正苦于以下问题:Python PermissionSystem类的具体用法?Python PermissionSystem怎么用?Python PermissionSystem使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了PermissionSystem类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:pkdevbox,项目名称:trac,代码行数:26,代码来源:default_workflow.py


示例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
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:35,代码来源:admin.py


示例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
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:27,代码来源:handler.py


示例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)
开发者ID:t-kenji,项目名称:trac-account-manager-plugin,代码行数:27,代码来源:admin.py


示例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')}
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-autocomplete,代码行数:27,代码来源:autocomplete.py


示例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)
开发者ID:djangsters,项目名称:agilo,代码行数:7,代码来源:admin.py


示例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    
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:25,代码来源:ticket_policy.py


示例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)
开发者ID:okamototk,项目名称:kanonconductor,代码行数:28,代码来源:admin_um.py


示例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
开发者ID:trac-ja,项目名称:trac-ja,代码行数:26,代码来源:authz_policy.py


示例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, [])
开发者ID:trac-hacks,项目名称:trac-wikinotification,代码行数:25,代码来源:notification.py


示例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)
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-createtemplate,代码行数:32,代码来源:importer.py


示例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
开发者ID:zjj,项目名称:trac_hack,代码行数:31,代码来源:web_ui.py


示例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
开发者ID:UfSoft,项目名称:trac-l10n-manager,代码行数:59,代码来源:locales.py


示例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
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:8,代码来源:admin.py


示例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]
开发者ID:thimalk,项目名称:bloodhound,代码行数:8,代码来源:perm.py


示例16: check_permission

 def check_permission(self, doc, context):
     product, doctype, id = doc['product'], doc['type'], doc['id']
     username = context.req.authname
     env = self.env
     if product:
         env = ProductEnvironment(self.env, product)
     perm = PermissionSystem(env)
     action = self._required_permissions[doctype]
     return perm.check_permission(action, username, id)
开发者ID:Stackato-Apps,项目名称:bloodhound,代码行数:9,代码来源:security.py


示例17: _reporter

 def _reporter(self, message):
     """return the ticket updater"""
     user = emailaddr2user(self.env, message['from'])
     # check permissions
     perm = PermissionSystem(self.env)
     if not perm.check_permission('MAIL2TICKET_COMMENT', user) : # None -> 'anoymous'
         raise EmailException("%s does not have MAIL2TRAC_COMMENT permissions" % (user or 'anonymous'))
     
     reporter = user or message['from']
     return reporter
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:10,代码来源:email2ticket.py


示例18: remove_permissions

 def remove_permissions(self, permissions):
     perm = PermissionSystem(self.env)
     for agent, p in permissions.items():
         if '*' in p:
             p = [ i for i, j in perm.get_user_permissions(agent).items() if j]
         for permission in p:
             
             try:
                 perm.revoke_permission(agent, permission)
             except:
                 continue
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:11,代码来源:admin.py


示例19: _expand_perms

 def _expand_perms(self, env):
     permsys = PermissionSystem(env)
     grant = frozenset(permsys.expand_actions(self.grant))
     revoke = frozenset(permsys.expand_actions(self.revoke))
     # Double check ambiguous action lists
     if grant & revoke:
         raise ValueError('Impossible to grant and revoke (%s)' %
                          ', '.join(sorted(grant & revoke)))
     self.grant = grant
     self.revoke = revoke
     self._expanded = True
开发者ID:thimalk,项目名称:bloodhound,代码行数:11,代码来源:perm.py


示例20: ResetActionTestCase

class ResetActionTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(default_data=True)
        self.perm_sys = PermissionSystem(self.env)
        self.ctlr = TicketSystem(self.env).action_controllers[0]
        self.req1 = Mock(authname='user1', args={},
                         perm=PermissionCache(self.env, 'user1'))
        self.req2 = Mock(authname='user2', args={},
                         perm=PermissionCache(self.env, 'user2'))
        self.ticket = Ticket(self.env)
        self.ticket['status'] = 'invalid'
        self.ticket.insert()

    def tearDown(self):
        self.env.reset_db()

    def _reload_workflow(self):
        self.ctlr.actions = self.ctlr.get_all_actions()

    def test_default_reset_action(self):
        """Default reset action."""
        self.perm_sys.grant_permission('user2', 'TICKET_ADMIN')
        self._reload_workflow()

        actions1 = self.ctlr.get_ticket_actions(self.req1, self.ticket)
        actions2 = self.ctlr.get_ticket_actions(self.req2, self.ticket)
        chgs2 = self.ctlr.get_ticket_changes(self.req2, self.ticket, '_reset')

        self.assertEqual(1, len(actions1))
        self.assertNotIn((0, '_reset'), actions1)
        self.assertEqual(2, len(actions2))
        self.assertIn((0, '_reset'), actions2)
        self.assertEqual('new', chgs2['status'])

    def test_custom_reset_action(self):
        """Custom reset action in [ticket-workflow] section."""
        config = self.env.config['ticket-workflow']
        config.set('_reset', '-> review')
        config.set('_reset.operations', 'reset_workflow')
        config.set('_reset.permissions', 'TICKET_BATCH_MODIFY')
        config.set('_reset.default', 2)
        self.perm_sys.grant_permission('user2', 'TICKET_BATCH_MODIFY')
        self._reload_workflow()

        actions1 = self.ctlr.get_ticket_actions(self.req1, self.ticket)
        actions2 = self.ctlr.get_ticket_actions(self.req2, self.ticket)
        chgs2 = self.ctlr.get_ticket_changes(self.req2, self.ticket, '_reset')

        self.assertEqual(1, len(actions1))
        self.assertNotIn((2, '_reset'), actions1)
        self.assertEqual(2, len(actions2))
        self.assertIn((2, '_reset'), actions2)
        self.assertEqual('review', chgs2['status'])
开发者ID:pkdevbox,项目名称:trac,代码行数:54,代码来源:default_workflow.py



注:本文中的trac.perm.PermissionSystem类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python resource.get_resource_description函数代码示例发布时间:2022-05-27
下一篇:
Python notification.NotifyEmail类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap