def user_roles(request, user_id):
    nova = get_nova_admin_connection()
    userroles = nova.get_user_roles(user_id)
    try:
        modeluser = auth_models.User.objects.get(username=user_id)
    except auth_models.User.DoesNotExist:
        modeluser = None

    if request.method == 'POST':
        form = forms.GlobalRolesForm(request.POST)
        if form.is_valid():
            username = user_id

            # hacky work around to interface correctly with multiple select form
            remove_global_roles(username)

            roleform = request.POST.getlist("role")
            for role in roleform:
                nova.add_user_role(username, str(role))

            return redirect('admin_user_roles', user_id)
    else:
        roles = [str(role.role) for role in userroles]
        form = forms.GlobalRolesForm({
            'username': modeluser and modeluser.id or None,
            'role': roles,
        })

    return render_to_response('admin/django_nova/project/global_edit_user.html', {
        'form' : form,
        'user' : modeluser,
    }, context_instance = template.RequestContext(request))
def projects_list(request):
    nova = get_nova_admin_connection()
    projects = nova.get_projects()

    return render_to_response('admin/django_nova/project/project_list.html', {
        'projects' : projects
    }, context_instance = template.RequestContext(request))
 def get_zip(self):
     """
     Returns a buffer of a zip file containing signed credentials
     for the project's Nova user.
     """
     nova = get_nova_admin_connection()
     return nova.get_zip(self.username, self.projectname)
def edit_user(request, project_id, username):
    nova = get_nova_admin_connection()
    project = get_project_or_404(request, project_id)
    user = nova.get_user(username)
    userroles = nova.get_user_roles(username, project_id)

    if project.projectManagerId != request.user.username:
        return redirect('login')

    if request.method == 'POST':
        form = nova_forms.ProjectUserForm(project, user, request.POST)
        if form.is_valid():
            form.save()

            return redirect('nova_project_manage',  project_id)
    else:
        roles = [str(role.role) for role in userroles]
        form = nova_forms.ProjectUserForm(project,
                                          user,
                                          {'role': roles,
                                           'user': user})

    return render_to_response('django_nova/projects/edit_user.html', {
        'form' : form,
        'project': project,
        'user' : user,
    }, context_instance = template.RequestContext(request))
def project_view(request, project_name):
    nova = get_nova_admin_connection()
    project = nova.get_project(project_name)
    users = nova.get_project_members(project_name)

    try:
        manager = auth_models.User.objects.get(username=project.projectManagerId)
    except auth_models.User.DoesNotExist:
        manager = None

    if request.method == 'POST':
        form = forms.ProjectForm(request.POST)
        if form.is_valid():
            try:
                nova.modify_project(form.cleaned_data["projectname"],
                                    form.cleaned_data["manager"],
                                    form.cleaned_data["description"])
                messages.success(request,
                                 'Successfully modified the project %s.' %
                                 project_name)
            except boto.exception.EC2ResponseError, e:
                messages.error(request,
                               'Unable modify the project %s: %s - %s' %
                               (project_name, e.code, e.error_message))


            return redirect('admin_project', request.POST["projectname"])
def set_project_roles(projectname, username, roles):
    nova = get_nova_admin_connection()
    # hacky work around to interface correctly with multiple select form
    _remove_roles(projectname, username)

    for role in roles:
        nova.add_user_role(username, str(role), projectname)
 def handle_noargs(self, **options):
     nova = get_nova_admin_connection()
     users = User.objects.all()
     for user in users:
         if not nova.has_user(user.username):
             self.stdout.write("creating user %s... " % user.username)
             nova.create_user(user.username)
             self.stdout.write("ok\n")
 def get_nova_connection(self):
     """
     Returns a boto connection for a user's project.
     """
     nova = get_nova_admin_connection()
     return nova.connection_for(self.username,
                                self.projectname,
                                clc_url=self.region['endpoint'],
                                region=self.region['name'])
def get_instance_type_choices():
    """
    Returns list of instance types from nova admin api
    """
    nova = get_nova_admin_connection()
    instance_types = nova.get_instance_types()
    rv = []
    for t in instance_types:
        rv.append((t.name, "%s (%sMB memory, %s cpu, %sGB space)" % \
                      (t.name, t.memory_mb, t.vcpus, t.disk_gb)))
    return rv
def _remove_roles(project, username):
    nova = get_nova_admin_connection()
    userroles = nova.get_user_roles(username,  project)
    roles = [str(role.role) for role in userroles]

    for role in roles:
        if role == "developer":
            nova.remove_user_role(username, "developer", project)
        if role == "sysadmin":
            nova.remove_user_role(username, "sysadmin", project)
        if role == "netadmin":
            nova.remove_user_role(username, "netadmin", project)
def delete_project(request, project_name):
    nova = get_nova_admin_connection()

    if request.method == 'POST':
        nova.delete_project(project_name)
        return redirect('admin_projects')

    project = nova.get_project(project_name)

    return render_to_response('admin/django_nova/project/delete_project.html', {
        'project' : project,
    }, context_instance = template.RequestContext(request))
def user_post_save(sender, instance, created, *args, **kwargs):
    """
    Creates a Nova User when a new Django User is created.
    """

    # NOTE(devcamcar): If running unit tests, don't use a real endpoint.
    if settings.NOVA_DEFAULT_ENDPOINT == 'none':
        return

    if created:
        nova = get_nova_admin_connection()
        if not nova.has_user(instance.username):
            nova.create_user(instance.username)
def users_list(request):
    nova = get_nova_admin_connection()
    users = nova.get_users()

    for user in users:
        # NOTE(devcamcar): Temporarily disabled for performance reasons.
        #roles = [str(role.role) for role in nova.get_user_roles(user.username)]
        roles = []
        user.roles = ", ".join(roles)

    return render_to_response('admin/django_nova/project/user_list.html', {
        'users' : users
    }, context_instance = template.RequestContext(request))
def delete_project_user(request, project_name, project_user):
    nova = get_nova_admin_connection()

    if request.method == 'POST':
        nova.remove_project_member(project_user, project_name)
        return redirect('admin_project', project_name)

    project = nova.get_project(project_name)
    user = nova.get_user(project_user)

    return render_to_response('admin/django_nova/project/delete_project_user.html', {
        'user' : user,
        'project' : project,
    }, context_instance = template.RequestContext(request))
def get_all_regions():
    """
    Returns a list of all regions.
    """
    regions = cache.get("regions")

    if not regions:
        nova = get_nova_admin_connection()
        conn = nova.connection_for(settings.NOVA_ADMIN_USER, settings.NOVA_PROJECT)
        results = conn.get_all_regions()
        regions = [{"name": r.name, "endpoint": r.endpoint} for r in results]
        cache.set("regions", regions, 60 * 60 * 24)

    return regions
def get_projects(user):
    """
    Returns a list of projects for a user.
    """
    # key = 'projects.%s' % user
    # projects = cache.get(key)

    # if not projects:
    #    nova = get_nova_admin_connection()
    #    projects = nova.get_projects(user=user)
    #    cache.set(key, projects, 30)

    # return projects
    nova = get_nova_admin_connection()
    return nova.get_projects(user=user)
def remove_global_roles(username):
    nova = get_nova_admin_connection()
    userroles = nova.get_user_roles(username)
    roles = [str(role.role) for role in userroles]

    for role in roles:
        if role == "developer":
            nova.remove_user_role(username, "developer")
        if role == "sysadmin":
            nova.remove_user_role(username, "sysadmin")
        if role == "netadmin":
            nova.remove_user_role(username, "netadmin")
        if role == "cloudadmin":
            nova.remove_user_role(username, "cloudadmin")
        if role == "itsec":
            nova.remove_user_role(username, "itsec")
def project_start_vpn(request, project_id):
    nova = get_nova_admin_connection()
    project = nova.get_project(project_id)

    if project == None:
        raise http.Http404()

    try:
        nova.start_vpn(project_id)
        messages.success(request,
                         'Successfully started VPN for project %s.' %
                         project_id)
    except boto.exception.EC2ResponseError, e:
        messages.error(request,
                       'Unable to start VPN for the project %s: %s - %s' %
                       (project_id, e.code, e.error_message))
def get_project_or_404(request, project_id):
    """
    Returns a project or 404s if it doesn't exist.
    """

    # Ensure that a connection is never attempted for a user that is unauthenticated.
    if not request.user.is_authenticated:
        raise PermissionDenied("User not authenticated")

    nova = get_nova_admin_connection()
    project = nova.get_project(project_id)
    region = get_current_region(request)

    if not project:
        raise Http404("Project %s does not exist." % project_id)

    return manager.ProjectManager(request.user, project, region)
def add_project(request):
    nova = get_nova_admin_connection()

    if request.method == 'POST':
        form = forms.ProjectForm(request.POST)
        if form.is_valid():
            manager = form.cleaned_data["manager"]
            nova.create_project(form.cleaned_data["projectname"],
                                manager.username,
                                form.cleaned_data["description"])
            return redirect('admin_project', request.POST["projectname"])
    else:
        form = forms.ProjectForm()

    return render_to_response('admin/django_nova/project/add_project.html', {
        'form' : form,
    }, context_instance = template.RequestContext(request))
def get_user_image_permissions(username, project_name):
    """
    Returns true if user is a sysadmin and can modify image attributes.
    """
    nova = get_nova_admin_connection()
    user_has_modify_permissions = False

    # checks global roles, if user is a sysadmin they can modify image attribtues.
    if not user_has_modify_permissions:
        for role in nova.get_user_roles(username):
            if role.role == "sysadmin":
                user_has_modify_permissions = True

    # checks project roles, if user is a sysadmin they can modify image attribtues.
    if not user_has_modify_permissions:
        for role in nova.get_user_roles(username, project_name):
            if role.role == "sysadmin":
                user_has_modify_permissions = True

    return user_has_modify_permissions
def manage(request, project_id):
    project = get_project_or_404(request, project_id)

    if project.projectManagerId != request.user.username:
        return redirect('login')

    nova = get_nova_admin_connection()
    members = nova.get_project_members(project_id)

    for member in members:
        project_role = [str(role.role) for role in nova.get_user_roles(member.memberId, project_id)]
        global_role = [str(role.role) for role in nova.get_user_roles(member.memberId, project=False)]

        member.project_roles = ", ".join(project_role)
        member.global_roles = ", ".join(global_role)


    return render_to_response('django_nova/projects/manage.html', {
        'project': project,
        'members': members,
    }, context_instance = template.RequestContext(request))
def add_project_user(request, project_name):
    nova = get_nova_admin_connection()

    if request.method == 'POST':
        form = forms.AddProjectUserForm(request.POST, project=project_name)
        if form.is_valid():
            username = form.cleaned_data["username"].username
            nova.add_project_member(username, project_name,)

            roleform = request.POST.getlist("role")
            for role in roleform:
                nova.add_user_role(username, str(role), project_name)

            return redirect('admin_project', project_name)
    else:
        form = forms.AddProjectUserForm(project=project_name)

    project = nova.get_project(project_name)

    return render_to_response('admin/django_nova/project/add_project_user.html', {
        'form' : form,
        'project' : project,
    }, context_instance = template.RequestContext(request))
def project_user(request, project_name, project_user):
    nova = get_nova_admin_connection()
    project = nova.get_project(project_name)
    userroles = nova.get_user_roles(project_user, project_name)

    try:
        modeluser = auth_models.User.objects.get(username = project_user)
    except auth_models.User.DoesNotExist:
        modeluser = None

    if request.method == 'POST':
        form = forms.ProjectUserForm(project, request.user, request.POST)
        if form.is_valid():
            username = project_user

            # hacky work around to interface correctly with multiple select form
            remove_project_roles(username, project_name)

            roleform = request.POST.getlist("role")
            for role in roleform:
                nova.add_user_role(username, str(role), project_name)

            return redirect('admin_project', project_name)
    else:
        roles = [str(role.role) for role in userroles]
        form = forms.ProjectUserForm(project,
                                     request.user,
                                     {'role': roles,
                                      'user': modeluser})


    return render_to_response('admin/django_nova/project/project_user.html', {
        'form' : form,
        'project' : project,
        'user': modeluser,
    }, context_instance = template.RequestContext(request))
def project_sendcredentials(request, project_id):
    nova = get_nova_admin_connection()
    project = nova.get_project(project_id)

    users = [user.memberId for user in nova.get_project_members(project_id)]
    form = forms.SendCredentialsForm(query_list=users)

    if project == None:
        raise http.Http404()

    if request.method == 'POST':
        if len(request.POST.getlist('users')) < 1:
            msg = "Please select a user to send credentials to."

            return render_to_response('admin/django_nova/project/send_credentials.html', {
                'project' : project,
                'form' : form,
                'users' : users,
                'error': msg,
            }, context_instance = template.RequestContext(request))
        else:
            for username in request.POST.getlist('users'):
                models.CredentialsAuthorization.authorize(username, project_id)
            msg = "Credentials were successfully sent."
            return render_to_response('admin/django_nova/project/send_credentials.html', {
                'project' : project,
                'form' : form,
                'users' : users,
                'success': msg,
            }, context_instance = template.RequestContext(request))

    return render_to_response('admin/django_nova/project/send_credentials.html', {
        'project' : project,
        'form' : form,
        'users' : users,
    }, context_instance = template.RequestContext(request))
 def get_zip(self):
     nova = get_nova_admin_connection()
     self.delete()
     return nova.get_zip(self.username, self.project)
def get_members(project):
    nova = get_nova_admin_connection()
    members = nova.get_project_members(project)
    return [str(user.memberId) for user in members]
def get_roles(project_roles=True):
    nova = get_nova_admin_connection()
    roles = nova.get_roles(project_roles=project_roles)
    return [(role.role, role.role) for role in roles]