예제 #1
0
    def validate_project(self, neighborhood, shortname, project_name, user, user_project, private_project):
        '''
        Validate that a project can be registered, before it is
        '''
        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
        nb_max_projects = neighborhood.get_max_projects()
        if nb_max_projects is not None:
            count = M.Project.query.find(dict(
                    neighborhood_id=neighborhood._id,
                    deleted=False,
                    is_nbhd_project=False,
                    )).count()
            if count >= nb_max_projects:
                log.exception('Error registering project %s' % project_name)
                raise forge_exc.ProjectOverlimitError()

        self.rate_limit(user, neighborhood)

        if user_project and shortname.startswith('u/'):
            check_shortname = shortname.replace('u/', '', 1)
        else:
            check_shortname = shortname
        self.shortname_validator.to_python(check_shortname, neighborhood=neighborhood)

        p = M.Project.query.get(shortname=shortname, neighborhood_id=neighborhood._id)
        if p:
            raise forge_exc.ProjectConflict('%s already exists in nbhd %s' % (shortname, neighborhood._id))
예제 #2
0
 def register_neighborhood_project(self, neighborhood, users, allow_register=False):
     from allura import model as M
     shortname='--init--'
     p = neighborhood.neighborhood_project
     if p: raise forge_exc.ProjectConflict()
     name = 'Home Project for %s' % neighborhood.name
     database_uri = M.Project.default_database_uri(shortname)
     p = M.Project(neighborhood_id=neighborhood._id,
                 shortname=shortname,
                 name=name,
                 short_description='',
                 description=('You can edit this description in the admin page'),
                 homepage_title = '# ' + name,
                 database_uri=database_uri,
                 last_updated = datetime.utcnow(),
                 is_nbhd_project=True,
                 is_root=True)
     try:
         p.configure_project(
             users=users,
             is_user_project=False,
             apps=[
                 ('Wiki', 'wiki', 'Wiki'),
                 ('admin', 'admin', 'Admin')])
     except:
         ThreadLocalORMSession.close_all()
         log.exception('Error registering project %s' % p)
         raise
     if allow_register:
         role_auth = M.ProjectRole.authenticated(p)
         security.simple_grant(p.acl, role_auth._id, 'register')
         state(p).soil()
     return p
예제 #3
0
파일: forms.py 프로젝트: xmonader/allura
 def _validate_allowed(self, shortname, neighborhood, state):
     p = M.Project.query.get(
         shortname=shortname, neighborhood_id=neighborhood._id)
     if p:
         raise forge_exc.ProjectConflict(
             'This project name is taken.',
             shortname, state)
예제 #4
0
    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