コード例 #1
0
ファイル: views.py プロジェクト: apluslms/shepherd
def manage_create_group_perm(group_id, **kwargs):
    """Manage createGroupPerms UI
    """
    if 'group' in kwargs:
        group = kwargs['group']
    else:
        group = db.session.query(Group).filter_by(id=group_id).one_or_none()

    # Check whether the group has the permissions to create subgroups
    if PermType.subgroups not in [perm.type for perm in group.permissions]:
        flash('Permission Denied')
        return redirect(request.referrer)

    # The existing parent groups
    parents = db.session.query(Group). \
        join(CreateGroupPerm.target_group). \
        filter(CreateGroupPerm.group_id == group_id).all()
    parents_slug = [group_slugify(g.name, g.parent) for g in parents]

    # All the possbile parent groups are those groups the current user is a member of and their children
    possible_parents = db.session.query(Group). \
        join(Group.members). \
        filter(User.id == current_user.id).all()
    possible_parents_slug = [
        group_slugify(g.name, g.parent) for g in possible_parents
    ]

    return render_template('groups/groupPerm_manage.html',
                           group_id=group_id,
                           parents=zip(parents, parents_slug),
                           possible_parents=zip(possible_parents,
                                                possible_parents_slug))
コード例 #2
0
ファイル: views.py プロジェクト: apluslms/shepherd
def create_course_group():
    """Create a group for a course
    """
    group_id = request.args.get('group_id')

    form = GroupForm(request.form)
    if request.method == 'POST' and form.validate():
        # Check whether the group name is not empty
        if form.name.data == '':
            flash('The group name can not be empty!')
            raise Exception('The group name could not be empty')
        group_name = slugify(form.name.data, separator='_')

        # Check whether the group already exists
        parent_group = Group.query.filter_by(id=group_id).one_or_none()
        if group_name in [g.name for g in parent_group.children]:
            raise Exception('The group already exists.')

        new_group = new_group_to_db(group_name, parent_group, form)
        try:
            db.session.commit()
            flash('The new group is added,',
                  'and you are set as the admin of the new group')
        except:
            raise Exception('Could not create the group')

        return jsonify(group_id=new_group.id,
                       group_slug=group_slugify(new_group.name,
                                                new_group.parent))
    else:
        raise Exception("Error occur")
コード例 #3
0
ファイル: views.py プロジェクト: apluslms/shepherd
def add_owner_list(course_key, instance_key, **kwargs):
    """Get all the possible owner groups could be added for a course
    """
    course_instance = (db.session.query(CourseInstance).join(
        CourseInstance.owners).filter(
            CourseInstance.course_key == course_key,
            CourseInstance.instance_key == instance_key).filter(
                Group.members.any(User.id == current_user.id)).one_or_none())
    if not course_instance:
        error_message = dumps(
            {'message': 'The course instance does not exist under the user'})
        abort(Response(error_message, 501))

    owner_groups = course_instance.owners
    groups = [g for g in current_user.groups if g not in owner_groups]

    group_array = []

    for group in groups:
        groupObj = {
            'id': group.id,
            'name': group_slugify(group.name, group.parent)
        }
        group_array.append(groupObj)

    return jsonify({'owner_options': group_array})
コード例 #4
0
ファイル: views.py プロジェクト: apluslms/shepherd
def list_my_groups():
    """Listing the groups which the current user is a member of
    """
    title = "My Groups"
    groups = Group.query.join(
        Group.members).filter(User.id == current_user.id).all()
    group_slugs = [group_slugify(g.name, g.parent) for g in groups]
    return render_template('groups/my_groups.html',
                           title=title,
                           user=current_user,
                           groups=zip(groups, group_slugs),
                           PermType=PermType)
コード例 #5
0
ファイル: views.py プロジェクト: apluslms/shepherd
def list_subgroups(group_id):
    """Listing all the subgroups of a group
    """
    group = db.session.query(Group).filter_by(id=group_id).one_or_none()
    if group is None:
        flash('There is no such group')
        return redirect(url_for('groups.list_my_groups'))

    # roots = Group.query.filter_by(parent_id=group.id).all()
    roots = group.children
    title = 'Group: ' + group_slugify(group.name, group.parent)
    return render_template('groups/group_list.html',
                           title=title,
                           user=current_user,
                           roots=roots,
                           node=group)
コード例 #6
0
ファイル: views.py プロジェクト: apluslms/shepherd
def parent_options(group_id):
    """Get all the possible parent groups of subgroups 
    for a group has the create subgroup permission  
    """
    groups = (db.session.query(Group).join(
        CreateGroupPerm.target_group).filter(
            CreateGroupPerm.group_id == group_id).all())

    group_array = []

    for group in groups:
        group_obj = {
            'id': group.id,
            'name': group_slugify(group.name, group.parent)
        }
        group_array.append(group_obj)

    return jsonify({'parent_options': group_array})
コード例 #7
0
ファイル: views.py プロジェクト: apluslms/shepherd
def owner_options():
    """Get all the possible new owner groups for a course 
    """
    old_owner_id = request.args.get('old_owner_id')
    old_owner = Group.query.filter_by(id=old_owner_id).one_or_none()

    if not old_owner:
        abort(404, 'No such a group')

    groups = current_user.groups
    groups.remove(
        old_owner)  # Remove the original owner group from the options

    # OR:
    # group_table =Group.__table__
    # old_owner = db.session.query(group_table).filter(
    #             group_table.c.id==old_owner_id).one_or_none()
    # groups = db.session.query(Group,group_table).\
    #         join(Group.members).\
    #         filter(Group.members.any(User.id==current_user.id)).\
    #         filter(db.or_(group_table.c.tree_id != old_owner.tree_id,
    #                     db.and_(
    #                     group_table.c.tree_id == old_owner.tree_id,
    #                     group_table.c.lft<old_owner.lft,
    #                     group_table.c.rgt>old_owner.rgt))).all()

    group_array = []

    for group in groups:
        # the group could not be the descendant of the original owner group
        if not group.is_descendant_of(old_owner):
            group_obj = {
                'id': group.id,
                'name': group_slugify(group.name, group.parent)
            }
            group_array.append(group_obj)

    return jsonify({'owner_options': group_array})
コード例 #8
0
ファイル: views.py プロジェクト: apluslms/shepherd
def owners_list(course_key, instance_key, **kwargs):
    """Get all the owner groups of a course  
    """
    # groups = (db.session.query(Group)
    #                     .join(CourseInstance.owners)
    #                     .filter(CourseInstance.course_key == course_key,
    #                             CourseInstance.instance_key == instance_key).all())
    perms = (db.session.query(ManageCoursePerm).join(
        ManageCoursePerm.course_instance).filter(
            CourseInstance.course_key == course_key,
            CourseInstance.instance_key == instance_key).all())

    group_array = []

    for perm in perms:
        groupObj = {
            'id': perm.group.id,
            'name': group_slugify(perm.group.name, perm.group.parent),
            'owner_type': perm.type.name
        }
        group_array.append(groupObj)

    return jsonify({'owner_groups': group_array})
コード例 #9
0
ファイル: views.py プロジェクト: apluslms/shepherd
def edit_group(group_id, **kwargs):
    if 'group' in kwargs:
        group = kwargs['group']
    else:
        group = db.session.query(Group).filter_by(id=group_id).one_or_none()

    group_slug = group_slugify(group.name, group.parent)
    permissions = [perm.type.name for perm in group.permissions]
    form = GroupForm(request.form)
    form.name.label = "New group name"
    form.parent_path.label = "New parent path"
    form.permissions.label = 'Update permission'

    if request.method == 'POST' and form.validate():
        # Edit the group name
        if request.form['edit'] == 'name':
            new_name = slugify(form.name.data, separator='_')

            # Check whether the name is unchanged
            if new_name == group.name:
                flash('No changes to make for the group')
                return redirect(url_for('.edit_group', group_id=group.id))

            # Check whether there has been a group with the same name
            q = db.session.query(Group).filter_by(
                name=new_name, parent_id=group.parent_id).one_or_none()
            if q:
                flash(
                    'A group with the same name has been under the same parent'
                )
                return redirect(url_for('.edit_group', group_id=group.id))

            group.name = new_name

        # Edit the group parent
        elif request.form['edit'] == 'parent path':

            new_parent = query_end_group(form.parent_path.data)

            if new_parent.id == group.parent_id:
                flash('No changes to make for the group')
            else:
                if parent_group_check(group.name, new_parent):
                    group.parent_id = new_parent.id

        # Edit the permissions
        elif request.form['edit'] == 'permissions':

            perm_origin = [perm.type.name for perm in group.permissions]
            perm_new = form.permissions.data

            # Manage Group.permissions field
            for name, perm_type in PermType.__members__.items():
                # The new pemission is added
                if (name not in perm_origin) and (name in perm_new):
                    perm = db.session.query(GroupPermission).filter(
                        GroupPermission.type == perm_type).first()
                    if not perm:
                        perm = GroupPermission(type=perm_type)
                    group.permissions.append(perm)

                # The original permission is removed
                if (name in perm_origin) and (name not in perm_new):
                    perm = db.session.query(GroupPermission).filter(
                        GroupPermission.type == perm_type).first()
                    group.permissions.remove(perm)

            # Set the 'self-administrator' permission
            # If it is the root, it is always self_admin
            if 'self_admin' in perm_new or group.parent is None:
                group.self_admin = True
            else:
                group.self_admin = False

            # Manage CreateCoursePerm
            # Add new CreateCoursePermission if the 'courses' permission is added
            if ('courses' not in perm_origin) and ('courses' in perm_new):
                course_prefix = form.course_prefix.data.upper()
                course_pattern = course_prefix + '-[A-Za-z][0-9][0-9][0-9][0-9]'
                course_perm = CreateCoursePerm(group=group,
                                               pattern=course_pattern)
                db.session.add(course_perm)

            # Delete the CreateCoursePermission if the 'courses' permission is removed
            if ('courses' in perm_origin) and ('courses' not in perm_new):
                create_course_perm = db.session.query(CreateGroupPerm).filter(
                    CreateGroupPerm.group_id == group.id).one_or_none()
                if create_course_perm:
                    db.session.delete(create_course_perm)

                    # Update the course prefix
        elif request.form['edit'] == 'course prefix':
            if 'courses' in permissions:
                course_prefix = form.course_prefix.data.upper()
                course_pattern = course_prefix + '-[A-Za-z][0-9][0-9][0-9][0-9]'

                create_course_perm = db.session.query(CreateCoursePerm).filter(
                    CreateCoursePerm.group_id == group.id).one_or_none()
                if create_course_perm:
                    create_course_perm.pattern = course_pattern
                else:
                    create_course_perm = CreateCoursePerm(
                        group=group, pattern=course_pattern)
                    db.session.add(create_course_perm)
            else:
                flash('Permission Denied')

        try:
            db.session.commit()
            flash('The group is edited successfully')
            return redirect(url_for('.list_my_groups'))
        except:
            flash('The group edit failed')

    return render_template('groups/group_edit.html',
                           group_id=group_id,
                           form=form,
                           group_slug=group_slug,
                           permissions=permissions)
コード例 #10
0
ファイル: views.py プロジェクト: apluslms/shepherd
def add_course(**kwargs):
    if 'identity_groups' in kwargs:
        identity_groups = kwargs['identity_groups']
    else:
        identity_groups = Group.query.filter(
            Group.members.any(id=current_user.id),
            Group.permissions.any(type=PermType.courses)).all()
    owner_groups = Group.query.filter(
        Group.members.any(id=current_user.id)).all()
    form = CourseForm(request.form)
    form.identity.choices += [(g.id, group_slugify(g.name, g.parent))
                              for g in identity_groups]
    form.owner_group.choices = [(g.id, group_slugify(g.name, g.parent))
                                for g in owner_groups]
    group_form = GroupForm(request.form)
    group_form.permissions.choices = [
        v for v in PERMISSION_LIST if v != ('courses', 'create courses')
    ]

    if request.method == 'POST' and form.validate():
        course_perm = CreateCoursePerm.query.filter_by(
            group_id=form.identity.data).one_or_none()
        if not course_perm:
            flash('Please choose a valid identity')
            return redirect(url_for('.add_course'))

        if not course_perm.pattern_match(form.course_key.data.upper()):
            flash('The course key does not match the naming rule ')
            return redirect(url_for('.add_course'))
        exists = CourseInstance.query.filter(
            CourseInstance.course_key == form.course_key.data.upper(),
            CourseInstance.instance_key == form.instance_key.data).first()
        if exists:
            flash('Course key %s and instance key %s already exists.' %
                  (form.course_key.data.upper(), form.instance_key.data))
        else:
            repository = GitRepository.query.filter_by(
                origin=form.origin.data).first()
            if repository is None:
                new_repository = GitRepository(origin=form.origin.data)
                new_repository.save()
                # Start generating key pair for this repository.
                generate_deploy_key.apply_async(
                    args=[DevelopmentConfig.REPO_KEYS_PATH, form.origin.data])
            new_course = CourseInstance(
                course_key=form.course_key.data.upper(),
                instance_key=form.instance_key.data,
                branch=form.branch.data,
                origin=form.origin.data,
                secret_token=None
                if form.secret_token.data == '' else form.secret_token.data,
                config_filename=None
                if form.config_filename.data == '' else form.secret_token.data,
                name=form.name.data)
            owner_group = Group.query.filter(
                Group.id == form.owner_group.data).one_or_none()
            new_course.owners.append(owner_group)
            course_admin_perm = ManageCoursePerm(course_instance=new_course,
                                                 group=owner_group,
                                                 type=CourseOwnerType.admin)
            db.session.add(new_course)
            db.session.commit()
            db.session.add(course_admin_perm)
            db.session.commit()
            flash('New course added.')
        return redirect('/courses/')
    return render_template('courses/course_create.html',
                           form=form,
                           group_form=group_form)
コード例 #11
0
ファイル: views.py プロジェクト: apluslms/shepherd
def edit_course(course_key, instance_key, **kwargs):
    # Get course from db
    course = CourseInstance.query.filter_by(course_key=course_key,
                                            instance_key=instance_key)
    origin_prev = course.first().origin
    form = CourseForm(request.form, obj=course.first())
    # Get the options of identity groups
    identity_groups = Group.query.filter(
        Group.members.any(id=current_user.id),
        Group.permissions.any(type=PermType.courses)).all()
    form.identity.choices += [(g.id, group_slugify(g.name, g.parent))
                              for g in identity_groups]
    # The label is changes according to whether user is edit a course or creating a course,
    # When editing a course, it should be changed to follows, or it will be "First instance origin"
    if request.method == 'POST' and form.validate():
        # Check whether the course key match the naming rule
        course_perm = CreateCoursePerm.query.filter_by(
            group_id=form.identity.data).one_or_none()
        if not course_perm:
            flash('Please choose a valid identity group')
            return redirect(
                url_for('.edit_course',
                        course_key=course_key,
                        instance_key=instance_key))
        if not course_perm.pattern_match(form.course_key.data.upper()):
            flash('The course key does not match the naming rule: {}'.format(
                course_perm.pattern))
            return redirect(url_for('.edit_course', course_key=course_key))
        origin_new = form.origin.data
        course.update(
            dict(
                course_key=form.course_key.data.upper(),
                instance_key=form.instance_key.data,
                branch=form.instance_key.data,
                # origin=origin_new,
                secret_token=None
                if form.secret_token.data == '' else form.secret_token.data,
                config_filename=None
                if form.config_filename.data == '' else form.secret_token.data,
                name=form.name.data))
        flash('Course edited.')
        db.session.commit()
        logger.info('Course edited')
        # Check if has change on origin
        if origin_new != origin_prev:
            # Create new, is this new repo is not in db yet.
            if GitRepository.query.filter_by(
                    origin=origin_new).one_or_none() is None:
                logger.info(
                    'This new repository is not exists in database,add it to database'
                )
                new_repo = GitRepository(origin=origin_new)
                new_repo.save()
                course.update(dict(origin=origin_new))
                generate_deploy_key.apply_async(
                    args=[DevelopmentConfig.REPO_KEYS_PATH, origin_new])
            # Delete old, if old repo becomes an orphan repository.
            if CourseInstance.query.filter_by(
                    origin=origin_prev).one_or_none() is None:
                logger.info(
                    'This edit makes the repository %s becomes an orphan repository, cleaning this repository.'
                    % origin_prev)
                clean_unused_repo.delay(origin_prev)
        return redirect('/courses/')
    return render_template('courses/course_edit.html', form=form)