Beispiel #1
0
    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
Beispiel #2
0
    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
Beispiel #3
0
    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    
 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')}
 def _complete_role_add(self, args):
     if len(args) == 1:
         return self._complete_managed_repositories(args)
     elif len(args) == 2:
         return RepositoryManager(self.env).roles
     if len(args) >= 3:
         ps = PermissionSystem(self.env)
         groups = set('@' + perm[1] for perm in ps.get_all_permissions()
                      if not perm[1].isupper())
         return groups | {u[0] for u in self.env.get_known_users()}
Beispiel #6
0
 def get_permission_actions(self):
     """
     This method returnes a list with all the 
     permission that this controller requires.
     
     @return: list
     """
     permission_system = PermissionSystem(self.env)
     for subject, action in permission_system.get_all_permissions():
         if action == 'PROJECT_ADMIN':
             return []
     return ['PROJECT_ADMIN']
Beispiel #7
0
 def get_permission_actions(self):
     """
     This method returnes a list with all the 
     permission that this controller requires.
     
     @return: list
     """
     permission_system = PermissionSystem(self.env)
     for subject, action in permission_system.get_all_permissions():
         if action == 'PROJECT_ADMIN' :
             return []
     return ['PROJECT_ADMIN']
Beispiel #8
0
    def _get_all_users(self):
      """
      Fetches all users/groups from PermissionSystem
      """
      perm = PermissionSystem(self.env)
      users = ["*"]
      data = perm.get_all_permissions()
      if not data:
        return [] # we abort here

      for (subject, action) in data:
        if subject not in users and subject not in ["anonymous", "authenticated"]:
          users.append(subject)
      return users	
Beispiel #9
0
 def update_trac_permissions(self, group, env):
     if self.dummy_run:
         self.note("Would update Trac permissions for group '%s'" %
                   group.acronym)
     else:
         self.note("Updating Trac permissions for group '%s'" %
                   group.acronym)
         mgr = PermissionSystem(env)
         permission_list = mgr.get_all_permissions()
         permission_list = [(u, a) for (u, a) in permission_list
                            if not u in ['anonymous', 'authenticated']]
         permissions = {}
         for user, action in permission_list:
             if not user in permissions:
                 permissions[user] = []
             permissions[user].append(action)
         roles = (list(
             group.role_set.filter(name_id__in=set([
                 'chair',
                 'secr',
                 'ad',
                 'trac-admin',
             ] + group.features.admin_roles))) + list(
                 self.secretariat.role_set.filter(name_id__in=[
                     'trac-admin',
                 ])))
         users = []
         for role in roles:
             user = role.email.address.lower()
             users.append(user)
             if not user in permissions:
                 try:
                     mgr.grant_permission(user, 'TRAC_ADMIN')
                     self.note("  Granting admin permission for %s" % user)
                 except TracError as e:
                     self.log("While adding admin permission for %s: %s" (
                         user, e))
         for user in permissions:
             if not user in users:
                 if 'TRAC_ADMIN' in permissions[user]:
                     try:
                         self.note("  Revoking admin permission for %s" %
                                   user)
                         mgr.revoke_permission(user, 'TRAC_ADMIN')
                     except TracError as e:
                         self.log(
                             "While revoking admin permission for %s: %s" (
                                 user, e))
Beispiel #10
0
    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)

	# need a new index for clearsilver to understand names including '.'
	newuserinfos = {}
	cnt=0
	for ui in userinfos:
                auser = userinfos.get(ui)
		newuserinfos[cnt] = auser
		cnt+=1
	req.hdf['admin.userinfos'] = newuserinfos
	req.hdf['admin.groupinfos'] = groupinfos
	req.hdf['admin.ldap_import'] = ldap_import
	req.hdf['admin.options'] = self.options
	if self.error_message:
        	req.hdf['admin.error_message'] = self.error_message
	return 'admin_notice.cs', None
Beispiel #11
0
    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)

# need a new index for clearsilver to understand names including '.'
        newuserinfos = {}
        cnt = 0
        for ui in userinfos:
            auser = userinfos.get(ui)
            newuserinfos[cnt] = auser
            cnt += 1
        req.hdf['admin.userinfos'] = newuserinfos
        req.hdf['admin.groupinfos'] = groupinfos
        req.hdf['admin.ldap_import'] = ldap_import
        req.hdf['admin.options'] = self.options
        if self.error_message:
            req.hdf['admin.error_message'] = self.error_message
        return 'admin_notice.cs', None
Beispiel #12
0
    def set_password(self, user, password):
        perm = PermissionSystem(self.env)
        all_perms = [ p[0] for p in perm.get_all_permissions() ]
        if user in all_perms:
            raise TracError('%s is a reserved name that can not be registered.' % user)

        needles = [ ':', '[', ']' ]
        for needle in needles:
            if needle in user:
                raise TracError('Character "%s" may not be used in user names.' % needle)

        if len(user) < 3:
            raise TracError('User name must be at least 3 characters long.')
        if not re.match(r'^\w+$', user):
            raise TracError('User name must consist only of alpha-numeric characters.')
        if user.isupper():
            raise TracError('User name must not consist of upper-case characters only.')

        if WikiPage(self.env, user).exists:
            raise TracError('wiki page "%s" already exists' % user)

        return HtPasswdStore.set_password(self, user, password)
Beispiel #13
0
    def process_admin_request(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        perms = perm.get_all_permissions()
        subject = req.args.get('subject')
        action = req.args.get('action')
        group = req.args.get('group')

        if req.method == 'POST':
            # Grant permission to subject
            if req.args.get('add') and subject and action:
                if action not in perm.get_actions():
                    raise TracError('Unknown action')
                perm.grant_permission(subject, action)
                req.redirect(self.env.href.admin(cat, page))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                perm.grant_permission(subject, group)
                req.redirect(self.env.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                sel = req.args.get('sel')
                sel = isinstance(sel, list) and sel or [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    if (subject, action) in perms:
                        perm.revoke_permission(subject, action)
                req.redirect(self.env.href.admin(cat, page))
        
        perms.sort(lambda a, b: cmp(a[0], b[0]))
        req.hdf['admin.actions'] = perm.get_actions()
        req.hdf['admin.perms'] = [{'subject': p[0],
                                   'action': p[1],
                                   'key': '%s:%s' % p
                                  } for p in perms]
        
        return 'admin_perm.cs', None
Beispiel #14
0
class SessionHelper(Component):
    """Helper for searching/manipulating the user database.

    Note that in trac, the user account/profile database is
    implemented as part of the session state storage.  User accounts
    are refered to as "authenticated sessions".  The “username” is
    referred to as the *session id* or ``sesssion.sid``.  It is also
    called the *authname* (e.g. ``req.authname``.)

    """
    abstract = True

    def __init__(self):
        self.permissions = PermissionSystem(self.env)

    def find_session_by_attr(self, attr_name, attr_value):
        """ Find an authenticated session which contain a specific attribute.

        """
        rows = db_query(
            self.env, "SELECT session.sid"
            " FROM session"
            " INNER JOIN session_attribute AS attr"
            "                  USING(sid, authenticated)"
            " WHERE session.authenticated=%s"
            "       AND attr.name=%s AND attr.value=%s"
            " ORDER BY session.last_visit DESC", (1, attr_name, attr_value))
        return [row[0] for row in rows]

    def create_session(self, authname_base, attributes):
        """Create a new authenticated session.

        (In trac, authenticated sessions are, essentially “user accounts”,
        so this creates a new account or “login” on the trac.)

        If possible, the session is created with an ``sid`` of
        ``authname_base``.  If a session already exists with that
        ``sid``, then a suffix is added to make the ``sid`` unique.

        The attributes of the new session are initialized from the
        ``attributes`` argument, if any.

        The ``sid`` of the new session is returned.

        """
        if not attributes:
            raise ValueError("Attributes required for new session")

        for suffix in self.uniquifier_suffixes():
            authname = authname_base + suffix
            if self.permission_exists_for(authname):
                continue
            ds = DetachedSession(self.env, authname)
            # At least in 0.12.2, this means no session exists.
            is_new = ds.last_visit == 0 and len(ds) == 0
            if is_new:
                break
        for key, value in attributes.items():
            ds[key] = value or ''
        ds.save()
        return authname

    def uniquifier_suffixes(self):
        """ Suffixes used to generate unique authnames.
        """
        return chain([""], (" (%d)" % n for n in count(2)))

    def permission_exists_for(self, authname):
        return any(authname == user
                   for user, perm in self.permissions.get_all_permissions())
Beispiel #15
0
class SessionHelper(Component):
    """Helper for searching/manipulating the user database.

    Note that in trac, the user account/profile database is
    implemented as part of the session state storage.  User accounts
    are refered to as "authenticated sessions".  The “username” is
    referred to as the *session id* or ``sesssion.sid``.  It is also
    called the *authname* (e.g. ``req.authname``.)

    """
    abstract = True

    def __init__(self):
        self.permissions = PermissionSystem(self.env)

    def find_session_by_attr(self, attr_name, attr_value):
        """ Find an authenticated session which contain a specific attribute.

        """
        rows = db_query(self.env,
                        "SELECT session.sid"
                        " FROM session"
                        " INNER JOIN session_attribute AS attr"
                        "                  USING(sid, authenticated)"
                        " WHERE session.authenticated=%s"
                        "       AND attr.name=%s AND attr.value=%s"
                        " ORDER BY session.last_visit DESC",
                        (1, attr_name, attr_value))
        return [row[0] for row in rows]

    def create_session(self, authname_base, attributes):
        """Create a new authenticated session.

        (In trac, authenticated sessions are, essentially “user accounts”,
        so this creates a new account or “login” on the trac.)

        If possible, the session is created with an ``sid`` of
        ``authname_base``.  If a session already exists with that
        ``sid``, then a suffix is added to make the ``sid`` unique.

        The attributes of the new session are initialized from the
        ``attributes`` argument, if any.

        The ``sid`` of the new session is returned.

        """
        if not attributes:
            raise ValueError("Attributes required for new session")

        for suffix in self.uniquifier_suffixes():
            authname = authname_base + suffix
            if self.permission_exists_for(authname):
                continue
            ds = DetachedSession(self.env, authname)
            # At least in 0.12.2, this means no session exists.
            is_new = ds.last_visit == 0 and len(ds) == 0
            if is_new:
                break
        for key, value in attributes.items():
            ds[key] = value or ''
        ds.save()
        return authname

    def uniquifier_suffixes(self):
        """ Suffixes used to generate unique authnames.
        """
        return chain([""], (" (%d)" % n for n in count(2)))

    def permission_exists_for(self, authname):
        return any(authname == user
                   for user, perm in self.permissions.get_all_permissions())
Beispiel #16
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            target = req.args.get('target', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                    group and group.isupper() or \
                    target and target.isupper():
                raise TracError(
                    _("All upper-cased tokens are reserved for "
                      "permission names."))

            # Grant permission to subject
            if 'add' in req.args and subject and action:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_("Unknown action"))
                req.perm.require(action)
                try:
                    perm.grant_permission(subject, action)
                except TracError as e:
                    add_warning(req, e)
                else:
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been "
                            "granted the permission %(action)s.",
                            subject=subject,
                            action=action))

            # Add subject to group
            elif 'add' in req.args and subject and group:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    req.perm.require(
                        action,
                        message=_(
                            "The subject %(subject)s was not added to "
                            "the group %(group)s because the group has "
                            "%(perm)s permission and users cannot grant "
                            "permissions they don't possess.",
                            subject=subject,
                            group=group,
                            perm=action))
                try:
                    perm.grant_permission(subject, group)
                except TracError as e:
                    add_warning(req, e)
                else:
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been "
                            "added to the group %(group)s.",
                            subject=subject,
                            group=group))

            # Copy permissions to subject
            elif 'copy' in req.args and subject and target:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')

                subject_permissions = perm.get_users_dict().get(subject, [])
                if not subject_permissions:
                    add_warning(
                        req,
                        _(
                            "The subject %(subject)s does not "
                            "have any permissions.",
                            subject=subject))

                for action in subject_permissions:
                    if action not in all_actions:  # plugin disabled?
                        self.log.warning(
                            "Skipped granting %s to %s: "
                            "permission unavailable.", action, target)
                    else:
                        if action not in req.perm:
                            add_warning(
                                req,
                                _(
                                    "The permission %(action)s was "
                                    "not granted to %(subject)s "
                                    "because users cannot grant "
                                    "permissions they don't possess.",
                                    action=action,
                                    subject=subject))
                            continue
                        try:
                            perm.grant_permission(target, action)
                        except PermissionExistsError:
                            pass
                        else:
                            add_notice(
                                req,
                                _(
                                    "The subject %(subject)s has "
                                    "been granted the permission "
                                    "%(action)s.",
                                    subject=target,
                                    action=action))
                req.redirect(req.href.admin(cat, page))

            # Remove permissions action
            elif 'remove' in req.args and 'sel' in req.args:
                req.perm('admin', 'general/perm').require('PERMISSION_REVOKE')
                for key in req.args.getlist('sel'):
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req,
                           _("The selected permissions have been "
                             "revoked."))

            req.redirect(req.href.admin(cat, page))

        return 'admin_perms.html', {
            'actions': all_actions,
            'allowed_actions': [a for a in all_actions if a in req.perm],
            'perms': perm.get_users_dict(),
            'groups': perm.get_groups_dict(),
            'unicode_to_base64': unicode_to_base64
        }
Beispiel #17
0
    def runTest(self):
        """Tests for the Copy Permissions functionality
        added in http://trac.edgewall.org/ticket/11099."""
        checkbox_value = lambda s, p: '%s:%s' % (unicode_to_base64(s),
                                                 unicode_to_base64(p))
        grant_msg = "The subject %s has been granted the permission %s\."
        def grant_permission(subject, action):
            tc.formvalue('addperm', 'gp_subject', subject)
            tc.formvalue('addperm', 'action', action)
            tc.submit()
            tc.find(grant_msg % (subject, action))
            tc.find(checkbox_value(subject, action))

        env = self._testenv.get_trac_environment()

        # Copy permissions from subject to target
        self._tester.go_to_admin('Permissions')
        perm_sys = PermissionSystem(env)
        anon_perms = perm_sys.store.get_user_permissions('anonymous')
        for perm in anon_perms:
            tc.find(checkbox_value('anonymous', perm))
            tc.notfind(checkbox_value('user1', perm))
        tc.formvalue('copyperm', 'cp_subject', 'anonymous')
        tc.formvalue('copyperm', 'cp_target', 'user1')
        tc.submit()
        for perm in anon_perms:
            tc.find("The subject user1 has been granted the permission %s\."
                    % perm)
            tc.find(checkbox_value('user1', perm))

        # Subject doesn't have any permissions
        tc.notfind(checkbox_value('noperms', ''))
        tc.formvalue('copyperm', 'cp_subject', 'noperms')
        tc.formvalue('copyperm', 'cp_target', 'user1')
        tc.submit()
        tc.find("The subject noperms does not have any permissions\.")

        # Subject belongs to group but doesn't directly have any permissions
        grant_permission('group1', 'TICKET_VIEW')
        tc.formvalue('addsubj', 'sg_subject', 'noperms')
        tc.formvalue('addsubj', 'sg_group', 'group1')
        tc.submit()
        tc.find("The subject noperms has been added to the group group1\.")

        tc.formvalue('copyperm', 'cp_subject', 'noperms')
        tc.formvalue('copyperm', 'cp_target', 'user1')
        tc.submit()
        tc.find("The subject noperms does not have any permissions\.")

        # Target uses reserved all upper-case form
        tc.formvalue('copyperm', 'cp_subject', 'noperms')
        tc.formvalue('copyperm', 'cp_target', 'USER1')
        tc.submit()
        tc.find("All upper-cased tokens are reserved for permission names\.")
        self._tester.go_to_admin("Permissions")

        # Subject users reserved all upper-case form
        tc.formvalue('copyperm', 'cp_subject', 'USER1')
        tc.formvalue('copyperm', 'cp_target', 'noperms')
        tc.submit()
        tc.find("All upper-cased tokens are reserved for permission names\.")
        self._tester.go_to_admin("Permissions")

        # Target already possess one of the permissions
        anon_perms = perm_sys.store.get_user_permissions('anonymous')
        for perm in anon_perms:
            tc.notfind(checkbox_value('user2', perm))
        grant_permission('user2', anon_perms[0])

        tc.formvalue('copyperm', 'cp_subject', 'anonymous')
        tc.formvalue('copyperm', 'cp_target', 'user2')
        tc.submit()

        tc.notfind("The subject <em>user2</em> has been granted the "
                   "permission %s\." % anon_perms[0])
        for perm in anon_perms[1:]:
            tc.find("The subject user2 has been granted the permission %s\."
                    % perm)
            tc.find(checkbox_value('user2', perm))

        # Subject has a permission that is no longer defined
        try:
            env.db_transaction("INSERT INTO permission VALUES (%s,%s)",
                               ('anonymous', 'NOTDEFINED_PERMISSION'))
        except env.db_exc.IntegrityError:
            pass
        env.config.touch()  # invalidate permission cache
        tc.reload()
        tc.find(checkbox_value('anonymous', 'NOTDEFINED_PERMISSION'))
        perm_sys = PermissionSystem(env)
        anon_perms = perm_sys.store.get_user_permissions('anonymous')
        for perm in anon_perms:
            tc.notfind(checkbox_value('user3', perm))

        tc.formvalue('copyperm', 'cp_subject', 'anonymous')
        tc.formvalue('copyperm', 'cp_target', 'user3')
        tc.submit()

        for perm in anon_perms:
            msg = grant_msg % ('user3', perm)
            if perm == 'NOTDEFINED_PERMISSION':
                tc.notfind(msg)
                tc.notfind(checkbox_value('user3', perm))
            else:
                tc.find(msg)
                tc.find(checkbox_value('user3', perm))
        perm_sys.revoke_permission('anonymous', 'NOTDEFINED_PERMISSION')

        # Actor doesn't posses permission
        grant_permission('anonymous', 'PERMISSION_GRANT')
        grant_permission('user3', 'TRAC_ADMIN')
        self._tester.logout()
        self._tester.go_to_admin("Permissions")

        try:
            tc.formvalue('copyperm', 'cp_subject', 'user3')
            tc.formvalue('copyperm', 'cp_target', 'user4')
            tc.submit()

            perm_sys = PermissionSystem(env)
            for perm in [perm[1] for perm in perm_sys.get_all_permissions()
                                 if perm[0] == 'user3'
                                 and perm[1] != 'TRAC_ADMIN']:
                tc.find(grant_msg % ('user4', perm))
            tc.notfind("The permission TRAC_ADMIN was not granted to user4 "
                       "because users cannot grant permissions they don't "
                       "possess.")
        finally:
            self._testenv.revoke_perm('anonymous', 'PERMISSION_GRANT')
            self._tester.login('admin')
Beispiel #18
0
 def _get_groups(self):
     """Get the list of known groups."""
     ps = PermissionSystem(self.env)
     result = list(set(perm[1] for perm in ps.get_all_permissions()
                   if not perm[1].isupper()))
     return result
Beispiel #19
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                   group and group.isupper():
                raise TracError(
                    _('All upper-cased tokens are reserved for '
                      'permission names'))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm.require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_('Unknown action'))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(
                        req,
                        _(
                            'The subject %(subject)s has been '
                            'granted the permission %(action)s.',
                            subject=subject,
                            action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            'The permission %(action)s was already '
                            'granted to %(subject)s.',
                            action=action,
                            subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm.require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions:  # plugin disabled?
                        self.env.log.warn("Adding %s to group %s: " \
                            "Permission %s unavailable, skipping perm check." \
                            % (subject, group, action))
                    else:
                        req.perm.require(action)
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(
                        req,
                        _(
                            'The subject %(subject)s has been added '
                            'to the group %(group)s.',
                            subject=subject,
                            group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            'The subject %(subject)s was already '
                            'added to the group %(group)s.',
                            subject=subject,
                            group=group))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm.require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = sel if isinstance(sel, list) else [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req,
                           _('The selected permissions have been '
                             'revoked.'))
                req.redirect(req.href.admin(cat, page))

        perms = [perm for perm in all_permissions if perm[1].isupper()]
        groups = [perm for perm in all_permissions if not perm[1].isupper()]

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': perms,
            'groups': groups,
            'unicode_to_base64': unicode_to_base64
        }
Beispiel #20
0
    def runTest(self):
        """Tests for the Copy Permissions functionality
        added in http://trac.edgewall.org/ticket/11099."""
        checkbox_value = lambda s, p: '%s:%s' % (unicode_to_base64(s),
                                                 unicode_to_base64(p))
        grant_msg = "The subject %s has been granted the permission %s\."

        def grant_permission(subject, action):
            tc.formvalue('addperm', 'gp_subject', subject)
            tc.formvalue('addperm', 'action', action)
            tc.submit()
            tc.find(grant_msg % (subject, action))
            tc.find(checkbox_value(subject, action))

        env = self._testenv.get_trac_environment()

        # Copy permissions from subject to target
        self._tester.go_to_admin('Permissions')
        perm_sys = PermissionSystem(env)
        anon_perms = perm_sys.store.get_user_permissions('anonymous')
        for perm in anon_perms:
            tc.find(checkbox_value('anonymous', perm))
            tc.notfind(checkbox_value('user1', perm))
        tc.formvalue('copyperm', 'cp_subject', 'anonymous')
        tc.formvalue('copyperm', 'cp_target', 'user1')
        tc.submit()
        for perm in anon_perms:
            tc.find("The subject user1 has been granted the permission %s\." %
                    perm)
            tc.find(checkbox_value('user1', perm))

        # Subject doesn't have any permissions
        tc.notfind(checkbox_value('noperms', ''))
        tc.formvalue('copyperm', 'cp_subject', 'noperms')
        tc.formvalue('copyperm', 'cp_target', 'user1')
        tc.submit()
        tc.find("The subject noperms does not have any permissions\.")

        # Subject belongs to group but doesn't directly have any permissions
        grant_permission('group1', 'TICKET_VIEW')
        tc.formvalue('addsubj', 'sg_subject', 'noperms')
        tc.formvalue('addsubj', 'sg_group', 'group1')
        tc.submit()
        tc.find("The subject noperms has been added to the group group1\.")

        tc.formvalue('copyperm', 'cp_subject', 'noperms')
        tc.formvalue('copyperm', 'cp_target', 'user1')
        tc.submit()
        tc.find("The subject noperms does not have any permissions\.")

        # Target uses reserved all upper-case form
        tc.formvalue('copyperm', 'cp_subject', 'noperms')
        tc.formvalue('copyperm', 'cp_target', 'USER1')
        tc.submit()
        tc.find("All upper-cased tokens are reserved for permission names\.")
        self._tester.go_to_admin("Permissions")

        # Subject users reserved all upper-case form
        tc.formvalue('copyperm', 'cp_subject', 'USER1')
        tc.formvalue('copyperm', 'cp_target', 'noperms')
        tc.submit()
        tc.find("All upper-cased tokens are reserved for permission names\.")
        self._tester.go_to_admin("Permissions")

        # Target already possess one of the permissions
        anon_perms = perm_sys.store.get_user_permissions('anonymous')
        for perm in anon_perms:
            tc.notfind(checkbox_value('user2', perm))
        grant_permission('user2', anon_perms[0])

        tc.formvalue('copyperm', 'cp_subject', 'anonymous')
        tc.formvalue('copyperm', 'cp_target', 'user2')
        tc.submit()

        tc.notfind("The subject <em>user2</em> has been granted the "
                   "permission %s\." % anon_perms[0])
        for perm in anon_perms[1:]:
            tc.find("The subject user2 has been granted the permission %s\." %
                    perm)
            tc.find(checkbox_value('user2', perm))

        # Subject has a permission that is no longer defined
        try:
            env.db_transaction("INSERT INTO permission VALUES (%s,%s)",
                               ('anonymous', 'NOTDEFINED_PERMISSION'))
        except env.db_exc.IntegrityError:
            pass
        env.config.touch()  # invalidate permission cache
        tc.reload()
        tc.find(checkbox_value('anonymous', 'NOTDEFINED_PERMISSION'))
        perm_sys = PermissionSystem(env)
        anon_perms = perm_sys.store.get_user_permissions('anonymous')
        for perm in anon_perms:
            tc.notfind(checkbox_value('user3', perm))

        tc.formvalue('copyperm', 'cp_subject', 'anonymous')
        tc.formvalue('copyperm', 'cp_target', 'user3')
        tc.submit()

        for perm in anon_perms:
            msg = grant_msg % ('user3', perm)
            if perm == 'NOTDEFINED_PERMISSION':
                tc.notfind(msg)
                tc.notfind(checkbox_value('user3', perm))
            else:
                tc.find(msg)
                tc.find(checkbox_value('user3', perm))
        perm_sys.revoke_permission('anonymous', 'NOTDEFINED_PERMISSION')

        # Actor doesn't posses permission
        grant_permission('anonymous', 'PERMISSION_GRANT')
        grant_permission('user3', 'TRAC_ADMIN')
        self._tester.logout()
        self._tester.go_to_admin("Permissions")

        try:
            tc.formvalue('copyperm', 'cp_subject', 'user3')
            tc.formvalue('copyperm', 'cp_target', 'user4')
            tc.submit()

            perm_sys = PermissionSystem(env)
            for perm in [
                    perm[1] for perm in perm_sys.get_all_permissions()
                    if perm[0] == 'user3' and perm[1] != 'TRAC_ADMIN'
            ]:
                tc.find(grant_msg % ('user4', perm))
            tc.notfind("The permission TRAC_ADMIN was not granted to user4 "
                       "because users cannot grant permissions they don't "
                       "possess.")
        finally:
            self._testenv.revoke_perm('anonymous', 'PERMISSION_GRANT')
            self._tester.login('admin')
Beispiel #21
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                   group and group.isupper():
                raise TracError(_('All upper-cased tokens are reserved for '
                                  'permission names'))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm.require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_('Unknown action'))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(req, _('The subject %(subject)s has been '
                                      'granted the permission %(action)s.',
                                      subject=subject, action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _('The permission %(action)s was already '
                                       'granted to %(subject)s.',
                                       action=action, subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm.require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions: # plugin disabled?
                        self.env.log.warn("Adding %s to group %s: " \
                            "Permission %s unavailable, skipping perm check." \
                            % (subject, group, action))
                    else:
                        req.perm.require(action)
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(req, _('The subject %(subject)s has been added '
                                      'to the group %(group)s.',
                                      subject=subject, group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _('The subject %(subject)s was already '
                                       'added to the group %(group)s.',
                                       subject=subject, group=group))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm.require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = isinstance(sel, list) and sel or [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req, _('The selected permissions have been '
                                  'revoked.'))
                req.redirect(req.href.admin(cat, page))

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': all_permissions
        }
Beispiel #22
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            target = req.args.get('target', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                    group and group.isupper() or \
                    target and target.isupper():
                raise TracError(
                    _("All upper-cased tokens are reserved for "
                      "permission names."))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_("Unknown action"))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been "
                            "granted the permission %(action)s.",
                            subject=subject,
                            action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            "The permission %(action)s was already "
                            "granted to %(subject)s.",
                            action=action,
                            subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions:  # plugin disabled?
                        self.env.log.warn(
                            "Adding %s to group %s: "
                            "Permission %s unavailable, skipping perm check.",
                            subject, group, action)
                    else:
                        req.perm.require(
                            action,
                            message=_(
                                "The subject %(subject)s was not added "
                                "to the group %(group)s because the "
                                "group has %(perm)s permission and "
                                "users cannot grant permissions they "
                                "don't possess.",
                                subject=subject,
                                group=group,
                                perm=action))
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(
                        req,
                        _(
                            "The subject %(subject)s has been added "
                            "to the group %(group)s.",
                            subject=subject,
                            group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(
                        req,
                        _(
                            "The subject %(subject)s was already "
                            "added to the group %(group)s.",
                            subject=subject,
                            group=group))

            # Copy permissions to subject
            elif req.args.get('copy') and subject and target:
                req.perm.require('PERMISSION_GRANT')

                subject_permissions = [
                    i[1] for i in all_permissions
                    if i[0] == subject and i[1].isupper()
                ]
                if not subject_permissions:
                    add_warning(
                        req,
                        _(
                            "The subject %(subject)s does not "
                            "have any permissions.",
                            subject=subject))

                for action in subject_permissions:
                    if (target, action) in all_permissions:
                        continue
                    if not action in all_actions:  # plugin disabled?
                        self.env.log.warn(
                            "Skipped granting %s to %s: "
                            "permission unavailable.", action, target)
                    else:
                        if action not in req.perm:
                            add_warning(
                                req,
                                _(
                                    "The permission %(action)s was "
                                    "not granted to %(subject)s "
                                    "because users cannot grant "
                                    "permissions they don't possess.",
                                    action=action,
                                    subject=subject))
                            continue
                        perm.grant_permission(target, action)
                        add_notice(
                            req,
                            _(
                                "The subject %(subject)s has "
                                "been granted the permission "
                                "%(action)s.",
                                subject=target,
                                action=action))
                req.redirect(req.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm('admin', 'general/perm').require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = sel if isinstance(sel, list) else [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req,
                           _("The selected permissions have been "
                             "revoked."))
                req.redirect(req.href.admin(cat, page))

        perms = [perm for perm in all_permissions if perm[1].isupper()]
        groups = [perm for perm in all_permissions if not perm[1].isupper()]

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': perms,
            'groups': groups,
            'unicode_to_base64': unicode_to_base64
        }
Beispiel #23
0
    def render_admin_panel(self, req, cat, page, path_info):
        perm = PermissionSystem(self.env)
        all_permissions = perm.get_all_permissions()
        all_actions = perm.get_actions()

        if req.method == 'POST':
            subject = req.args.get('subject', '').strip()
            target = req.args.get('target', '').strip()
            action = req.args.get('action')
            group = req.args.get('group', '').strip()

            if subject and subject.isupper() or \
                    group and group.isupper() or \
                    target and target.isupper():
                raise TracError(_("All upper-cased tokens are reserved for "
                                  "permission names."))

            # Grant permission to subject
            if req.args.get('add') and subject and action:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                if action not in all_actions:
                    raise TracError(_("Unknown action"))
                req.perm.require(action)
                if (subject, action) not in all_permissions:
                    perm.grant_permission(subject, action)
                    add_notice(req, _("The subject %(subject)s has been "
                                      "granted the permission %(action)s.",
                                      subject=subject, action=action))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _("The permission %(action)s was already "
                                       "granted to %(subject)s.",
                                       action=action, subject=subject))

            # Add subject to group
            elif req.args.get('add') and subject and group:
                req.perm('admin', 'general/perm').require('PERMISSION_GRANT')
                for action in perm.get_user_permissions(group):
                    if not action in all_actions: # plugin disabled?
                        self.env.log.warn("Adding %s to group %s: "
                            "Permission %s unavailable, skipping perm check.",
                            subject, group, action)
                    else:
                        req.perm.require(action,
                            message=_("The subject %(subject)s was not added "
                                      "to the group %(group)s because the "
                                      "group has %(perm)s permission and "
                                      "users cannot grant permissions they "
                                      "don't possess.", subject=subject,
                                      group=group, perm=action))
                if (subject, group) not in all_permissions:
                    perm.grant_permission(subject, group)
                    add_notice(req, _("The subject %(subject)s has been added "
                                      "to the group %(group)s.",
                                      subject=subject, group=group))
                    req.redirect(req.href.admin(cat, page))
                else:
                    add_warning(req, _("The subject %(subject)s was already "
                                       "added to the group %(group)s.",
                                       subject=subject, group=group))

            # Copy permissions to subject
            elif req.args.get('copy') and subject and target:
                req.perm.require('PERMISSION_GRANT')

                subject_permissions = [i[1] for i in all_permissions
                                            if i[0] == subject and
                                               i[1].isupper()]
                if not subject_permissions:
                    add_warning(req,_("The subject %(subject)s does not "
                                      "have any permissions.",
                                      subject=subject))

                for action in subject_permissions:
                    if (target, action) in all_permissions:
                        continue
                    if not action in all_actions: # plugin disabled?
                        self.env.log.warn("Skipped granting %s to %s: "
                                          "permission unavailable.",
                                          action, target)
                    else:
                        if action not in req.perm:
                            add_warning(req,
                                        _("The permission %(action)s was "
                                          "not granted to %(subject)s "
                                          "because users cannot grant "
                                          "permissions they don't possess.",
                                          action=action, subject=subject))
                            continue
                        perm.grant_permission(target, action)
                        add_notice(req, _("The subject %(subject)s has "
                                          "been granted the permission "
                                          "%(action)s.",
                                          subject=target, action=action))
                req.redirect(req.href.admin(cat, page))

            # Remove permissions action
            elif req.args.get('remove') and req.args.get('sel'):
                req.perm('admin', 'general/perm').require('PERMISSION_REVOKE')
                sel = req.args.get('sel')
                sel = sel if isinstance(sel, list) else [sel]
                for key in sel:
                    subject, action = key.split(':', 1)
                    subject = unicode_from_base64(subject)
                    action = unicode_from_base64(action)
                    if (subject, action) in perm.get_all_permissions():
                        perm.revoke_permission(subject, action)
                add_notice(req, _("The selected permissions have been "
                                  "revoked."))
                req.redirect(req.href.admin(cat, page))

        return 'admin_perms.html', {
            'actions': all_actions,
            'perms': perm.get_users_dict(),
            'groups': perm.get_groups_dict(),
            'unicode_to_base64': unicode_to_base64
        }