def create(self, name=None, **kw):
     if M.ProjectRole.by_name(name):
         flash('%s already exists' % name, 'error')
     else:
         M.ProjectRole(project_id=c.project._id, name=name)
     M.AuditLog.log('create group %s', name)
     g.post_event('project_updated')
     redirect('.')
def test_project_role():
    role = M.ProjectRole(project_id=c.project._id, name='test_role')
    c.user.project_role().roles.append(role._id)
    ThreadLocalORMSession.flush_all()
    for pr in g.credentials.user_roles(c.user._id,
                                       project_id=c.project.root_project._id):
        assert pr.display()
        pr.special
        assert pr.user in (c.user, None, M.User.anonymous())
Exemple #3
0
 def test_is_spam(self, spam_checker):
     spam_checker.check.return_value = True
     c.user = M.User.query.get(username="******")
     role = M.ProjectRole(project_id=c.project._id, name='TestRole')
     M.ProjectRole.by_user(c.user, upsert=True).roles.append(role._id)
     ThreadLocalORMSession.flush_all()
     t = M.Thread()
     p = M.Post(thread=t)
     assert_in('TestRole', [r.name for r in c.project.named_roles])
     assert_false(t.is_spam(p))
def test_project_role():
    role = M.ProjectRole(project_id=c.project._id, name='test_role')
    c.user.project_role().roles.append(role._id)
    ThreadLocalORMSession.flush_all()
    roles = g.credentials.user_roles(
        c.user._id, project_id=c.project.root_project._id)
    roles_ids = [role['_id'] for role in roles]
    roles = M.ProjectRole.query.find({'_id': {'$in': roles_ids}})
    for pr in roles:
        assert pr.display()
        pr.special
        assert pr.user in (c.user, None, M.User.anonymous())
Exemple #5
0
def test_user_projects_unnamed():
    """
    Confirm that spurious ProjectRoles associating a user with
    a project to which they do not belong to any named group
    don't cause the user to count as a member of the project.
    """
    sub1 = M.Project.query.get(shortname='test/sub1')
    M.ProjectRole(user_id=c.user._id, project_id=sub1._id)
    ThreadLocalORMSession.flush_all()
    project_names = [p.shortname for p in c.user.my_projects()]
    assert_not_in('test/sub1', project_names)
    assert_in('test', project_names)
def project_role(project, name):
    role = M.ProjectRole.query.get(project_id=project._id, name=name)
    if role is None:
        role = M.ProjectRole(project_id=project._id, name=name)
    return role
Exemple #7
0
'''Merge all the OldProjectRole collections in various project databases into a
central ProjectRole collection.
'''
import logging

from pylons import c

from ming.orm import session, state
from allura import model as M

log = logging.getLogger(__name__)

seen_databases = set()
projects = M.Project.query.find().all()

for p in projects:
    if p.database_uri in seen_databases:
        continue
    seen_databases.add(p.database_uri)
    log.info('Moving project roles in database %s to main DB', p.database_uri)
    c.project = p
    for opr in M.OldProjectRole.query.find():
        pr = M.ProjectRole(**state(opr).document)
    session(opr).clear()
    session(pr).flush()
    session(pr).clear()
    def _create_project(self, neighborhood, shortname, project_name, user, user_project, private_project, apps):
        '''
        Actually create the project, no validation.  This should not be called directly
        under normal circumstances.
        '''
        from allura import model as M

        project_template = neighborhood.get_project_template()
        p = M.Project(neighborhood_id=neighborhood._id,
                    shortname=shortname,
                    name=project_name,
                    short_description='',
                    description=('You can edit this description in the admin page'),
                    homepage_title=shortname,
                    database_uri=M.Project.default_database_uri(shortname),
                    last_updated = datetime.utcnow(),
                    is_nbhd_project=False,
                    is_root=True)
        p.configure_project(
            users=[user],
            is_user_project=user_project,
            is_private_project=private_project or project_template.get('private', False),
            apps=apps or [] if 'tools' in project_template else None)

        # Setup defaults from neighborhood project template if applicable
        offset = p.next_mount_point(include_hidden=True)
        if 'groups' in project_template:
            for obj in project_template['groups']:
                name = obj.get('name')
                permissions = set(obj.get('permissions', [])) & \
                              set(p.permissions)
                usernames = obj.get('usernames', [])
                # Must provide a group name
                if not name: continue
                # If the group already exists, we'll add users to it,
                # but we won't change permissions on the group
                group = M.ProjectRole.by_name(name, project=p)
                if not group:
                    # If creating a new group, *must* specify permissions
                    if not permissions: continue
                    group = M.ProjectRole(project_id=p._id, name=name)
                    p.acl += [M.ACE.allow(group._id, perm)
                            for perm in permissions]
                for username in usernames:
                    guser = M.User.by_username(username)
                    if not (guser and guser._id): continue
                    pr = guser.project_role(project=p)
                    if group._id not in pr.roles:
                        pr.roles.append(group._id)
        if 'tools' in project_template:
            for i, tool in enumerate(project_template['tools'].keys()):
                tool_config = project_template['tools'][tool]
                tool_options = tool_config.get('options', {})
                for k, v in tool_options.iteritems():
                    if isinstance(v, basestring):
                        tool_options[k] = \
                                string.Template(v).safe_substitute(
                                    p.__dict__.get('root_project', {}))
                if p.app_instance(tool) is None:
                    app = p.install_app(tool,
                        mount_label=tool_config['label'],
                        mount_point=tool_config['mount_point'],
                        ordinal=i + offset,
                    **tool_options)
                    if tool == 'wiki':
                        from forgewiki import model as WM
                        text = tool_config.get('home_text',
                            '[[members limit=20]]\n[[download_button]]')
                        WM.Page.query.get(app_config_id=app.config._id).text = text

        if 'tool_order' in project_template:
            for i, tool in enumerate(project_template['tool_order']):
                p.app_config(tool).options.ordinal = i
        if 'labels' in project_template:
            p.labels = project_template['labels']
        if 'trove_cats' in project_template:
            for trove_type in project_template['trove_cats'].keys():
                troves = getattr(p, 'trove_%s' % trove_type)
                for trove_id in project_template['trove_cats'][trove_type]:
                    troves.append(M.TroveCategory.query.get(trove_cat_id=trove_id)._id)
        if 'icon' in project_template:
            icon_file = StringIO(urlopen(project_template['icon']['url']).read())
            M.ProjectFile.save_image(
                project_template['icon']['filename'], icon_file,
                square=True, thumbnail_size=(48, 48),
                thumbnail_meta=dict(project_id=p._id, category='icon'))

        if user_project:
            # Allow for special user-only tools
            p._extra_tool_status = ['user']
            # add user project informative text to home
            from forgewiki import model as WM
            home_app = p.app_instance('wiki')
            home_page = WM.Page.query.get(app_config_id=home_app.config._id)
            home_page.text = ("This is the personal project of %s."
            " This project is created automatically during user registration"
            " as an easy place to store personal data that doesn't need its own"
            " project such as cloned repositories.") % user.display_name

        # clear the RoleCache for the user so this project will
        # be picked up by user.my_projects()
        g.credentials.clear_user(user._id, None)  # unnamed roles for this user
        g.credentials.clear_user(user._id, p._id)  # named roles for this project + user
        with h.push_config(c, project=p, user=user):
            ThreadLocalORMSession.flush_all()
            # have to add user to context, since this may occur inside auth code
            # for user-project reg, and c.user isn't set yet
            g.post_event('project_created')
        return p
    def register_project(self, neighborhood, shortname, project_name, user, user_project, private_project, apps=None):
        '''Register a new project in the neighborhood.  The given user will
        become the project's superuser.
        '''
        from allura import model as M

        # Check for private project rights
        if neighborhood.features['private_projects'] == False and private_project:
            raise ValueError("You can't create private projects for %s neighborhood" % neighborhood.name)

        # Check for project limit creation
        pq = M.Project.query.find(dict(
                neighborhood_id=neighborhood._id,
                deleted=False,
                is_nbhd_project=False,
                ))
        count = pq.count()
        nb_max_projects = neighborhood.get_max_projects()

        if nb_max_projects is not None and count >= nb_max_projects:
            log.exception('Error registering project %s' % project_name)
            raise forge_exc.ProjectOverlimitError()

        if not h.re_path_portion.match(shortname.replace('/', '')):
            raise ValueError('Invalid project shortname: %s' % shortname)
        try:
            p = M.Project.query.get(shortname=shortname, neighborhood_id=neighborhood._id)
            if p:
                raise forge_exc.ProjectConflict()
            project_template = neighborhood.get_project_template()
            p = M.Project(neighborhood_id=neighborhood._id,
                        shortname=shortname,
                        name=project_name,
                        short_description='',
                        description=('You can edit this description in the admin page'),
                        homepage_title=shortname,
                        database_uri=M.Project.default_database_uri(shortname),
                        last_updated = datetime.utcnow(),
                        is_nbhd_project=False,
                        is_root=True)
            p.configure_project(
                users=[user],
                is_user_project=user_project,
                is_private_project=private_project or project_template.get('private', False),
                apps=apps or [] if 'tools' in project_template else None)

            # Setup defaults from neighborhood project template if applicable
            offset = p.next_mount_point(include_hidden=True)
            if 'groups' in project_template:
                for obj in project_template['groups']:
                    name = obj.get('name')
                    permissions = set(obj.get('permissions', [])) & \
                                  set(p.permissions)
                    usernames = obj.get('usernames', [])
                    # Must provide a group name
                    if not name: continue
                    # If the group already exists, we'll add users to it,
                    # but we won't change permissions on the group
                    group = M.ProjectRole.by_name(name, project=p)
                    if not group:
                        # If creating a new group, *must* specify permissions
                        if not permissions: continue
                        group = M.ProjectRole(project_id=p._id, name=name)
                        p.acl += [M.ACE.allow(group._id, perm)
                                for perm in permissions]
                    for username in usernames:
                        user = M.User.by_username(username)
                        if not (user and user._id): continue
                        pr = user.project_role(project=p)
                        if group._id not in pr.roles:
                            pr.roles.append(group._id)
            if 'tools' in project_template:
                for i, tool in enumerate(project_template['tools'].keys()):
                    tool_config = project_template['tools'][tool]
                    tool_options = tool_config.get('options', {})
                    for k, v in tool_options.iteritems():
                        if isinstance(v, basestring):
                            tool_options[k] = \
                                    string.Template(v).safe_substitute(
                                        p.__dict__.get('root_project', {}))
                    app = p.install_app(tool,
                        mount_label=tool_config['label'],
                        mount_point=tool_config['mount_point'],
                        ordinal=i + offset,
                        **tool_options)
                    if tool == 'wiki':
                        from forgewiki import model as WM
                        text = tool_config.get('home_text',
                            '[[project_admins]]\n[[download_button]]')
                        WM.Page.query.get(app_config_id=app.config._id).text = text

            if 'tool_order' in project_template:
                for i, tool in enumerate(project_template['tool_order']):
                    p.app_config(tool).options.ordinal = i
            if 'labels' in project_template:
                p.labels = project_template['labels']
            if 'trove_cats' in project_template:
                for trove_type in project_template['trove_cats'].keys():
                    troves = getattr(p, 'trove_%s' % trove_type)
                    for trove_id in project_template['trove_cats'][trove_type]:
                        troves.append(M.TroveCategory.query.get(trove_cat_id=trove_id)._id)
            if 'icon' in project_template:
                icon_file = StringIO(urlopen(project_template['icon']['url']).read())
                M.ProjectFile.save_image(
                    project_template['icon']['filename'], icon_file,
                    square=True, thumbnail_size=(48, 48),
                    thumbnail_meta=dict(project_id=p._id, category='icon'))
        except forge_exc.ProjectConflict:
            raise
        except:
            ThreadLocalORMSession.close_all()
            log.exception('Error registering project %s' % p)
            raise
        with h.push_config(c, project=p, user=user):
            ThreadLocalORMSession.flush_all()
            # have to add user to context, since this may occur inside auth code
            # for user-project reg, and c.user isn't set yet
            g.post_event('project_created')
        return p