def remove_member(request, proj_id, user_id): """ Kick a member out by stripping his roles """ project = get_object_or_404(Project, id=proj_id) member = get_object_or_404(User, id=user_id) if request.method == "POST": #<UT> if settings.ENABLE_CBAS: authz_user = UserProfile.get_or_create_profile(request.user) user_to_remove = UserProfile.get_or_create_profile(member) remove_member_from_project(project.urn, user_to_remove.urn, authz_user.urn, authz_user.certificate) member = Permittee.objects.get_as_permittee(member) # Remove the roles for role in ProjectRole.objects.filter(project=project): role.remove_from_permittee(member) # Remove other permissions PermissionOwnership.objects.delete_all_for_target(project, member) #Remove can_use_aggregate if user is not member of any other project using the aggregates of this project for projectAgg in project._get_aggregates(): aggNotUsedAnymoreByMember=1 for p in Project.objects.exclude(id=project.id): if projectAgg in p._get_aggregates() and unicode(member) in p.members.values_list("username", flat=True): aggNotUsedAnymoreByMember=0 break; if aggNotUsedAnymoreByMember and not has_permission(member, projectAgg, "can_use_aggregate"): projectAgg.remove_from_user(member,"/") try: #Sync LDAP project.save() except: logger.warning("User '%s' may have not been deleted from project '%s'. It could be a bug within LDAP." % (member.object.username, project.name)) return HttpResponseRedirect( reverse("project_detail", args=[proj_id])) return simple.direct_to_template( request, template=TEMPLATE_PATH+"/remove_member.html", extra_context={ "project": project, "member": member, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Remove Member %s" % member.username, request.path), ), }, )
def user_cert_manage(request, user_id): """Allow the user to download/regenerate/upload a GCF certificate. @param request: the request object @param user_id: the id of the user whose certificate we are managing. """ user = get_object_or_404(User, pk=user_id) user_profile = UserProfile.get_or_create_profile(request.user) user_cert = user_profile.certificate private_ssh_key_exists = len(user_profile.private_ssh_key) > 0 public_ssh_key_exists = len(user_profile.public_ssh_key) > 0 must_have_permission(request.user, user, "can_change_user_cert") cert_fname = get_user_cert_fname(user) if not os.access(cert_fname, os.F_OK): cert = None else: cert = read_cert_from_string(user_cert) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/user_cert_manage.html", extra_context={ "curr_user": user, "cert": cert, "private_ssh_key_exists": private_ssh_key_exists, "public_ssh_key_exists": public_ssh_key_exists }, )
def user_cert_manage(request, user_id): """Allow the user to download/regenerate/upload a GCF certificate. @param request: the request object @param user_id: the id of the user whose certificate we are managing. """ user = get_object_or_404(User, pk=user_id) user_profile = UserProfile.get_or_create_profile(request.user) user_cert = user_profile.certificate private_ssh_key_exists = len(user_profile.private_ssh_key) > 0 public_ssh_key_exists = len(user_profile.public_ssh_key) > 0 must_have_permission(request.user, user, "can_change_user_cert") cert_fname = get_user_cert_fname(user) if not os.access(cert_fname, os.F_OK): cert = None else: cert = read_cert_from_string(user_cert) return simple.direct_to_template( request, template= TEMPLATE_PATH + "/user_cert_manage.html", extra_context={ "curr_user": user, "cert": cert, "private_ssh_key_exists" : private_ssh_key_exists, "public_ssh_key_exists": public_ssh_key_exists }, )
def create(request, proj_id): '''Create a slice''' project = get_object_or_404(Project, id=proj_id) must_have_permission(request.user, project, "can_create_slices") #<UT> user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn user_cert = user_profile.certificate def pre_save(instance, created): instance.project = project instance.owner = request.user #Generate UUID: fixes caching problem on model default value instance.uuid = uuid.uuid4() #<UT> instance.urn = 'n/a' #import pdb; pdb.set_trace() if settings.ENABLE_CBAS: slice_urn = create_slice(owner_urn=user_urn, owner_certificate=user_cert, slice_name=instance.name, slice_desc=instance.description, slice_project_urn=str(project.urn)) if slice_urn: instance.urn = slice_urn instance.save() instance.reserved = False #use to give the can_delete_slices over the slice to the creator and the owners of the project def post_save(instance, created): give_permission_to("can_delete_slices", instance, instance.owner, giver=None, can_delegate=False) # for projectOwner in instance.project._get_owners(): # give_permission_to("can_delete_slices", instance, projectOwner, giver=None, can_delegate=False) return generic_crud( request, None, Slice, TEMPLATE_PATH + "/create_update.html", redirect=lambda instance: reverse("slice_detail", args=[instance.id]), form_class=SliceCrudForm, extra_context={ "project": project, "title": "Create slice", "cancel_url": reverse("project_detail", args=[proj_id]), }, pre_save=pre_save, post_save=post_save, success_msg=lambda instance: "Successfully created slice %s." % instance.name, )
def create(request): """ Create a new project """ user_profile = UserProfile.get_or_create_profile(request.user) cert = user_profile.certificate creds = user_profile.credentials user_urn = user_profile.urn def post_save(instance, created): # Create default roles in the project #Generate UUID: fixes caching problem on model default value instance.uuid = uuid.uuid4() #<UT> instance.urn = "n/a" #import pdb; pdb.set_trace() if settings.ENABLE_CBAS: project_urn = create_project(certificate=cert, credentials=creds, project_name=instance.name, project_desc=instance.description, user_urn=user_urn) if project_urn: instance.urn = project_urn create_project_roles(instance, request.user) instance.save() #if settings.LDAP_STORE_PROJECTS: # instance.sync_netgroup_ldap() def redirect(instance): return reverse("project_detail", args=[instance.id]) try: return generic_crud( request, None, model=Project, form_class=ProjectCreateForm, template=TEMPLATE_PATH+"/create_update.html", post_save=post_save, redirect=redirect, template_object_name="project", extra_context={ "breadcrumbs": ( ("Home", reverse("home")), ("Create Project", request.path), ), }, success_msg = lambda instance: "Successfully created project %s." % instance.name, ) except Exception as e: if isinstance(e,ldap.LDAPError): DatedMessage.objects.post_message_to_user( "Project has been created but only locally since LDAP is not reachable. You will not be able to add users to the project until connection is restored.", request.user, msg_type=DatedMessage.TYPE_ERROR) else: DatedMessage.objects.post_message_to_user( "Project may have been created, but some problem ocurred: %s" % str(e), request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse("home"))
def detail(request, slice_id): '''Show information about the slice''' slice = get_object_or_404(Slice, id=slice_id) must_have_permission(request.user, slice.project, "can_view_project") resource_list = [rsc.as_leaf_class() for rsc in slice.resource_set.all()] user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn user_cert = user_profile.certificate #creds = get_slice_credentials(slice.project.urn, slice.urn, user_urn, user_cert) #print_debug_message(str(creds)) template_list_computation = [] template_list_network = [] template_list_aggregate = [] for plugin in PLUGIN_LOADER.plugin_settings: try: plugin_dict = PLUGIN_LOADER.plugin_settings.get(plugin) # Get templates according to the plugin category ('computation' or 'network') # instead of directly using "TEMPLATE_RESOURCES" settings if plugin_dict.get("general").get("resource_type") == "computation": template_list_computation.append(plugin_dict.get("paths").get("template_resources")) elif plugin_dict.get("general").get("resource_type") == "network": template_list_network.append(plugin_dict.get("paths").get("template_resources")) elif plugin_dict.get("general").get("resource_type") == "aggregate": template_list_aggregate.append(plugin_dict.get("paths").get("template_resources")) except Exception as e: print "[WARNING] Could not obtain template to add resources to slides in plugin '%s'. Details: %s" % (str(plugin), str(e)) plugin_context = TOPOLOGY_GENERATOR.load_ui_data(slice) # if not plugin_context['d3_nodes'] or not plugin_context['d3_links']: # template_list_computation = [] # template_list_network = [] extra_context={ "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % slice.project.name, reverse("project_detail", args=[slice.project.id])), ("Slice %s" % slice.name, reverse("slice_detail", args=[slice_id])), ), "resource_list": resource_list, "plugin_template_list_aggregate": template_list_aggregate, "plugin_template_list_network": template_list_network, "plugin_template_list_computation": template_list_computation, "plugins_path": PLUGIN_LOADER.plugins_path, } return list_detail.object_detail( request, Slice.objects.all(), object_id=slice_id, template_name=TEMPLATE_PATH+"/detail.html", template_object_name="slice", extra_context=dict(extra_context.items()+plugin_context.items()) )
def user_cert_generate(request, user_id): """Create a new user certificate after confirmation. @param request: the request object @param user_id: the id of the user whose certificate we are generating. """ user = get_object_or_404(User, pk=user_id) must_have_permission(request.user, user, "can_change_user_cert") user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn if request.method == "POST": #create_x509_cert(urn, cert_fname, key_fname) retValues = regenerate_member_creds(user_urn) if retValues: cert, cert_key, creds = retValues[0:] user_profile.certificate = cert user_profile.certificate_key = cert_key user_profile.credentials = creds user_profile.save() DatedMessage.objects.post_message_to_user( "Certificate for user %s successfully created." % user.username, user=request.user, msg_type=DatedMessage.TYPE_SUCCESS) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/user_new_keys_download.html", extra_context={ "curr_user": user, }, ) else: DatedMessage.objects.post_message_to_user( "Certificate for user %s could not be created." % user.username, user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect( reverse(user_cert_manage, args=[user.id])) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/user_cert_generate.html", extra_context={ "curr_user": user, }, )
def create(request, proj_id): '''Create a slice''' project = get_object_or_404(Project, id=proj_id) must_have_permission(request.user, project, "can_create_slices") #<UT> user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn user_cert = user_profile.certificate def pre_save(instance, created): instance.project = project instance.owner = request.user #Generate UUID: fixes caching problem on model default value instance.uuid = uuid.uuid4() #<UT> instance.urn = 'n/a' #import pdb; pdb.set_trace() if settings.ENABLE_CBAS: slice_urn = create_slice(owner_urn=user_urn, owner_certificate=user_cert, slice_name=instance.name, slice_desc=instance.description, slice_project_urn=str(project.urn)) if slice_urn: instance.urn = slice_urn instance.save() instance.reserved = False #use to give the can_delete_slices over the slice to the creator and the owners of the project def post_save(instance, created): give_permission_to("can_delete_slices", instance, instance.owner, giver=None, can_delegate=False) # for projectOwner in instance.project._get_owners(): # give_permission_to("can_delete_slices", instance, projectOwner, giver=None, can_delegate=False) return generic_crud( request, None, Slice, TEMPLATE_PATH+"/create_update.html", redirect=lambda instance:reverse("slice_detail", args=[instance.id]), form_class=SliceCrudForm, extra_context={ "project": project, "title": "Create slice", "cancel_url": reverse("project_detail", args=[proj_id]), }, pre_save=pre_save, post_save=post_save, success_msg = lambda instance: "Successfully created slice %s." % instance.name, )
def create(request, proj_id): '''Create a slice''' project = get_object_or_404(Project, id=proj_id) must_have_permission(request.user, project, "can_create_slices") #<UT> from expedient.clearinghouse.users.models import UserProfile user_credentials = UserProfile.get_or_create_profile(request.user).credentials def pre_save(instance, created): instance.project = project instance.owner = request.user #Generate UUID: fixes caching problem on model default value instance.uuid = uuid.uuid4() #<UT> instance.credentials = 'n/a' if ENABLE_CBAS: code, values, output = create_slice(slice_name=instance.name, slice_desc=instance.description, user_credentials=[{'SFA': user_credentials}]) if code == 0 and 'SLICE_CREDENTIAL' in values: instance.credentials = values.SLICE_CREDENTIAL #import pdb; pdb.set_trace() instance.save() instance.reserved = False #use to give the can_delete_slices over the slice to the creator and the owners of the project def post_save(instance, created): give_permission_to("can_delete_slices", instance, instance.owner, giver=None, can_delegate=False) # for projectOwner in instance.project._get_owners(): # give_permission_to("can_delete_slices", instance, projectOwner, giver=None, can_delegate=False) return generic_crud( request, None, Slice, TEMPLATE_PATH+"/create_update.html", redirect=lambda instance:reverse("slice_detail", args=[instance.id]), form_class=SliceCrudForm, extra_context={ "project": project, "title": "Create slice", "cancel_url": reverse("project_detail", args=[proj_id]), }, pre_save=pre_save, post_save=post_save, success_msg = lambda instance: "Successfully created slice %s." % instance.name, )
def create(request, proj_id): '''Create a slice''' project = get_object_or_404(Project, id=proj_id) must_have_permission(request.user, project, "can_create_slices") #<UT> from expedient.clearinghouse.users.models import UserProfile user_credentials = UserProfile.get_or_create_profile(request.user).credentials def pre_save(instance, created): instance.project = project instance.owner = request.user #Generate UUID: fixes caching problem on model default value instance.uuid = uuid.uuid4() #<UT> #print "--------------------" code, values, output = create_slice(slice_name=instance.name, slice_desc=instance.description, user_credentials=user_credentials) if code == 0 and 'SLICE_CREDENTIAL' in values: instance.credentials = values.SLICE_CREDENTIAL import pdb; pdb.set_trace() instance.save() instance.reserved = False #use to give the can_delete_slices over the slice to the creator and the owners of the project def post_save(instance, created): give_permission_to("can_delete_slices", instance, instance.owner, giver=None, can_delegate=False) # for projectOwner in instance.project._get_owners(): # give_permission_to("can_delete_slices", instance, projectOwner, giver=None, can_delegate=False) return generic_crud( request, None, Slice, TEMPLATE_PATH+"/create_update.html", redirect=lambda instance:reverse("slice_detail", args=[instance.id]), form_class=SliceCrudForm, extra_context={ "project": project, "title": "Create slice", "cancel_url": reverse("project_detail", args=[proj_id]), }, pre_save=pre_save, post_save=post_save, success_msg = lambda instance: "Successfully created slice %s." % instance.name, )
def user_cert_generate(request, user_id): """Create a new user certificate after confirmation. @param request: the request object @param user_id: the id of the user whose certificate we are generating. """ user = get_object_or_404(User, pk=user_id) must_have_permission(request.user, user, "can_change_user_cert") user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn if request.method == "POST": #create_x509_cert(urn, cert_fname, key_fname) retValues = regenerate_member_creds(user_urn) if retValues: cert, cert_key, creds = retValues[0:] user_profile.certificate = cert user_profile.certificate_key = cert_key user_profile.credentials = creds user_profile.save() DatedMessage.objects.post_message_to_user( "Certificate for user %s successfully created." % user.username, user=request.user, msg_type=DatedMessage.TYPE_SUCCESS) return simple.direct_to_template( request, template= TEMPLATE_PATH + "/user_new_keys_download.html", extra_context={ "curr_user": user, }, ) else: DatedMessage.objects.post_message_to_user( "Certificate for user %s could not be created." % user.username, user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse(user_cert_manage, args=[user.id])) return simple.direct_to_template( request, template= TEMPLATE_PATH + "/user_cert_generate.html", extra_context={ "curr_user": user, }, )
def home(request): isSuperUser = False if (has_permission(request.user, User, "can_manage_users")): isSuperUser = True if request.session.get("visited") == None: showFirstTimeTooltips = True request.session["visited"] = True else: showFirstTimeTooltips = False #<UT> if settings.ENABLE_CBAS: try: user_profile = UserProfile.get_or_create_profile(request.user) user_details = { "FIRST_NAME": user_profile.user.first_name, "LAST_NAME": user_profile.user.last_name, "EMAIL": user_profile.user.email } # if not (user_profile.urn and user_profile.certificate and # user_profile.certificate_key and user_profile.credentials): urn, cert, creds, ssh_key_pair = get_member_info( str(request.user), user_details) user_profile.urn = urn user_profile.certificate = cert user_profile.credentials = creds if ssh_key_pair: user_profile.public_ssh_key = ssh_key_pair[0] user_profile.private_ssh_key = ssh_key_pair[1] user_profile.save() except socket_error as serr: # Error 111: connection refused if serr.errno == errno.ECONNREFUSED: DatedMessage.objects.post_message_to_user( "Warning: the clearinghouse is enabled, but its server is not running. You or the administrator should start it", request.user, msg_type=DatedMessage.TYPE_WARNING) return direct_to_template(request, template="expedient/clearinghouse/index.html", extra_context={ "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": (("Home", reverse("home")), ), })
def home(request): isSuperUser = False if(has_permission(request.user, User, "can_manage_users")): isSuperUser = True if request.session.get("visited") == None: showFirstTimeTooltips = True request.session["visited"] = True else: showFirstTimeTooltips = False #<UT> if settings.ENABLE_CBAS: try: user_profile = UserProfile.get_or_create_profile(request.user) user_details = {"FIRST_NAME": user_profile.user.first_name, "LAST_NAME": user_profile.user.last_name, "EMAIL": user_profile.user.email} # if not (user_profile.urn and user_profile.certificate and # user_profile.certificate_key and user_profile.credentials): urn, cert, creds, ssh_key_pair = get_member_info(str(request.user), user_details) user_profile.urn = urn user_profile.certificate = cert user_profile.credentials = creds if ssh_key_pair: # Keys are returned only for new registration user_profile.public_ssh_key = ssh_key_pair[0] user_profile.private_ssh_key = ssh_key_pair[1] user_profile.save() except socket_error as serr: # Error 111: connection refused if serr.errno == errno.ECONNREFUSED: DatedMessage.objects.post_message_to_user( "Warning: the clearinghouse is enabled, but its server is not running. You or the administrator should start it", request.user, msg_type=DatedMessage.TYPE_WARNING) return direct_to_template( request, template="expedient/clearinghouse/index.html", extra_context={ "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": ( ("Home", reverse("home")), ), } )
def user_cert_download(request, user_id): """Download a GCF certificate.""" user = get_object_or_404(User, pk=user_id) try: # must_have_permission(request.user, user, "can_download_certs") user_profile = UserProfile.get_or_create_profile(request.user) user_cert = user_profile.certificate response = HttpResponse(user_cert, mimetype='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s-cert.pem' % user.username return response except: DatedMessage.objects.post_message_to_user( "Could not retrieve certificate for user '%s'" % str(user.username), user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect( reverse("gcf_cert_manage", args=[user_id]) )
def save(self, user): """Update the SSH keys @param user: the user to update SSH keys for. @type user: C{django.contrib.auth.models.User} """ user_profile = UserProfile.get_or_create_profile(user) cert = user_profile.certificate creds = user_profile.credentials ret_value = update_ssh_key(user_profile.urn, self.key_str, cert, creds) if not ret_value == 0: raise forms.ValidationError( "Could not update SSH key." " Please check if C-BAS is reachable" ) else: user_profile.private_ssh_key = '' user_profile.public_ssh_key = self.key_str user_profile.save()
def user_public_ssh_key_download(request, user_id): """Download a public SSH key.""" user = get_object_or_404(User, pk=user_id) try: user_profile = UserProfile.get_or_create_profile(request.user) user_pub_ssh_key = user_profile.public_ssh_key # must_have_permission(request.user, user, "can_download_certs") response = HttpResponse(user_pub_ssh_key, mimetype='application/force-download') response[ 'Content-Disposition'] = 'attachment; filename=%s-ssh-key.pub' % user.username return response except: DatedMessage.objects.post_message_to_user( "Could not retrieve ssh key for user '%s'" % str(user.username), user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse("gcf_cert_manage", args=[user_id]))
def user_private_ssh_key_download(request, user_id): """Download a public SSH key.""" user = get_object_or_404(User, pk=user_id) try: user_profile = UserProfile.get_or_create_profile(request.user) user_priv_ssh_key = user_profile.private_ssh_key user_profile.private_ssh_key = '' user_profile.save() # must_have_permission(request.user, user, "can_download_certs") response = HttpResponse(user_priv_ssh_key, mimetype='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s-ssh-key' % user.username return response except: DatedMessage.objects.post_message_to_user( "Could not retrieve ssh key for user '%s'" % str(user.username), user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect( reverse("gcf_cert_manage", args=[user_id]) )
def user_ssh_keys_generate(request, user_id): """Create a new user certificate after confirmation. @param request: the request object @param user_id: the id of the user whose certificate we are generating. """ user = get_object_or_404(User, pk=user_id) must_have_permission(request.user, user, "can_change_user_cert") user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn user_cert = user_profile.certificate user_creds = user_profile.credentials pub_key, priv_key = regenerate_ssh_keys(user_urn, str(request.user), user_cert, user_creds) if pub_key and priv_key: user_profile.public_ssh_key = pub_key user_profile.private_ssh_key = priv_key user_profile.save() DatedMessage.objects.post_message_to_user( "SSH key pair for user %s successfully created." % user.username, user=request.user, msg_type=DatedMessage.TYPE_SUCCESS) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/user_new_ssh_key_download.html", extra_context={ "curr_user": user, }, ) else: DatedMessage.objects.post_message_to_user( "Could not update ssh keys for user '%s'" % str(user.username), user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse("gcf_cert_manage", args=[user_id]))
def user_ssh_keys_generate(request, user_id): """Create a new user certificate after confirmation. @param request: the request object @param user_id: the id of the user whose certificate we are generating. """ user = get_object_or_404(User, pk=user_id) must_have_permission(request.user, user, "can_change_user_cert") user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn user_cert = user_profile.certificate user_creds = user_profile.credentials pub_key, priv_key = regenerate_ssh_keys(user_urn, str(request.user), user_cert, user_creds) if pub_key and priv_key: user_profile.public_ssh_key = pub_key user_profile.private_ssh_key = priv_key user_profile.save() DatedMessage.objects.post_message_to_user( "SSH key pair for user %s successfully created." % user.username, user=request.user, msg_type=DatedMessage.TYPE_SUCCESS) return simple.direct_to_template( request, template= TEMPLATE_PATH + "/user_new_ssh_key_download.html", extra_context={ "curr_user": user, }, ) else: DatedMessage.objects.post_message_to_user( "Could not update ssh keys for user '%s'" % str(user.username), user=request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect( reverse("gcf_cert_manage", args=[user_id]) )
def CreateSliver(slice_urn, rspec, user): (project_name, project_desc, slice_name, slice_desc, slice_expiry, controller_url, firstname, lastname, affiliation, email, password, slivers) = rspec_mod.parse_slice(rspec) logger.debug("Parsed Rspec") slice_expiry = datetime.fromtimestamp(slice_expiry) give_permission_to("can_create_project", Project, user) user.first_name = firstname user.last_name = lastname user.email = email profile = UserProfile.get_or_create_profile(user) profile.affiliation = affiliation user.save() profile.save() # Check if the slice exists try: slice = get_slice(slice_urn) # update the slice info slice.description = slice_desc slice.name = slice_name slice.expiration_date = slice_expiry slice.save() # update the project info slice.project.name = project_name slice.project.description = project_desc slice.project.save() project = slice.project except Slice.DoesNotExist: # Check if the project exists try: project = Project.objects.get(name=project_name) # update the project info logger.debug("Updating project") project.description = project_desc project.save() except Project.DoesNotExist: # create the project logger.debug("Creating project") project = Project.objects.create( name=project_name, description=project_desc, ) create_project_roles(project, user) # create the slice logger.debug("Creating slice") try: slice = Slice.objects.create( name=slice_name, description=slice_desc, project=project, owner=user, expiration_date=slice_expiry, ) except IntegrityError: raise DuplicateSliceNameException(slice_name) logger.debug("Creating/updating slice info") # create openflow slice info for the slice create_or_update( OpenFlowSliceInfo, filter_attrs={"slice": slice}, new_attrs={ "controller_url": controller_url, "password": password, }, ) logger.debug("creating gapislice") # store a pointer to this slice using the slice_urn create_or_update( GENISliceInfo, filter_attrs={ "slice": slice, }, new_attrs={ "slice_urn": slice_urn, }, ) logger.debug("adding resources") sliver_ids = [] # delete all flowspace in the slice FlowSpaceRule.objects.filter(slivers__slice=slice).delete() # add the new flowspace for fs_dict, iface_qs in slivers: # give the user, project, slice permission to use the aggregate aggregate_ids = list(iface_qs.values_list("aggregate", flat=True)) for agg_id in aggregate_ids: aggregate = Aggregate.objects.get(id=agg_id).as_leaf_class() give_permission_to("can_use_aggregate", aggregate, user) give_permission_to("can_use_aggregate", aggregate, project) give_permission_to("can_use_aggregate", aggregate, slice) # Create flowspace logger.debug("Creating flowspace %s" % fs_dict) fs = FlowSpaceRule.objects.create(**fs_dict) # make sure all the selected interfaces are added for iface in iface_qs: sliver, _ = OpenFlowInterfaceSliver.objects.get_or_create( slice=slice, resource=iface) sliver_ids.append(sliver.id) fs.slivers.add(sliver) logger.debug("Deleting old resources") # Delete all removed interfaces OpenFlowInterfaceSliver.objects.exclude(id__in=sliver_ids).delete() logger.debug("Starting the slice %s %s" % (slice, slice.name)) # make the reservation tl = threadlocals.get_thread_locals() tl["project"] = project tl["slice"] = slice slice.start(user) logger.debug("Done creating sliver") return rspec_mod.create_resv_rspec(user, slice)
def add_member(request, proj_id): """ Add a member to the project """ project = get_object_or_404(Project, id=proj_id) if request.method == "POST": form = AddMemberForm(project=project, giver=request.user, data=request.POST) if form.is_valid(): user = User.objects.get(id=request.POST['user']) #<UT> if settings.ENABLE_CBAS: user_to_add = UserProfile.get_or_create_profile(user) op_user = UserProfile.get_or_create_profile(request.user) add_member_to_project( project_urn=project.urn, to_add_user_urn=user_to_add.urn, to_add_user_certificate=user_to_add.certificate, authz_user_urn=op_user.urn, authz_user_certificate=op_user.certificate) form.save() try: #Sync LDAP project.save() except: logger.warning( "User '%s' may have not been added to project '%s'. It could be a bug within LDAP." % (user.username, project.name)) DatedMessage.objects.post_message_to_user( "User '%s' may not own the requested permissions. It could be a bug within LDAP." % user.username, request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect( reverse("project_detail", args=[proj_id])) #Send mail notification to the user roles = ', '.join( repr(role.encode('ascii')) for role in ProjectRole.objects.filter( id__in=request.POST.getlist('roles')).values_list( 'name', flat=True)) #XXX: Not sure about this... maybe give_permission_to... for aggregate in project._get_aggregates(): if not has_permission(user, aggregate, "can_use_aggregate"): aggregate.add_to_user(user, "/") try: # Get project detail URL to send via e-mail from expedient.clearinghouse.project import urls project_detail_url = reverse("project_detail", args=[project.id]) or "/" # No "https://" check should be needed if settings are OK site_domain_url = "https://" + Site.objects.get_current( ).domain + project_detail_url send_mail( settings.EMAIL_SUBJECT_PREFIX + "Project %s membership notification" % (project.name), "You have been added to project '%s' as a user with the following roles: %s.\nYou may start experimenting now by going to %s\n\n" % (project.name, roles, site_domain_url), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str( e) return HttpResponseRedirect( reverse("project_detail", args=[proj_id])) else: form = AddMemberForm(project=project, giver=request.user) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/add_member.html", extra_context={ "form": form, "project": project, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Add Member", request.path), ), }, )
def detail(request, slice_id): '''Show information about the slice''' slice = get_object_or_404(Slice, id=slice_id) must_have_permission(request.user, slice.project, "can_view_project") resource_list = [rsc.as_leaf_class() for rsc in slice.resource_set.all()] user_profile = UserProfile.get_or_create_profile(request.user) user_urn = user_profile.urn user_cert = user_profile.certificate #creds = get_slice_credentials(slice.project.urn, slice.urn, user_urn, user_cert) #print_debug_message(str(creds)) template_list_computation = [] template_list_network = [] for plugin in PLUGIN_LOADER.plugin_settings: try: plugin_dict = PLUGIN_LOADER.plugin_settings.get(plugin) # Get templates according to the plugin category ('computation' or 'network') # instead of directly using "TEMPLATE_RESOURCES" settings if plugin_dict.get("general").get( "resource_type") == "computation": template_list_computation.append( plugin_dict.get("paths").get("template_resources")) elif plugin_dict.get("general").get("resource_type") == "network": template_list_network.append( plugin_dict.get("paths").get("template_resources")) except Exception as e: print "[WARNING] Could not obtain template to add resources to slides in plugin '%s'. Details: %s" % ( str(plugin), str(e)) plugin_context = TOPOLOGY_GENERATOR.load_ui_data(slice) # if not plugin_context['d3_nodes'] or not plugin_context['d3_links']: # template_list_computation = [] # template_list_network = [] extra_context = { "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % slice.project.name, reverse("project_detail", args=[slice.project.id])), ("Slice %s" % slice.name, reverse("slice_detail", args=[slice_id])), ), "resource_list": resource_list, "plugin_template_list_network": template_list_network, "plugin_template_list_computation": template_list_computation, "plugins_path": PLUGIN_LOADER.plugins_path, } return list_detail.object_detail( request, Slice.objects.all(), object_id=slice_id, template_name=TEMPLATE_PATH + "/detail.html", template_object_name="slice", extra_context=dict(extra_context.items() + plugin_context.items()))
def confirm_requests(request): """Confirm the approval of the permission requests.""" approved_req_ids = request.session.setdefault("approved_req_ids", []) delegatable_req_ids = request.session.setdefault("delegatable_req_ids", []) denied_req_ids = request.session.setdefault("denied_req_ids", []) approved_reqs = [] for req_id in approved_req_ids: req = get_object_or_404(PermissionRequest, id=req_id) delegatable = req_id in delegatable_req_ids approved_reqs.append((req, delegatable)) denied_reqs = [] for req_id in denied_req_ids: denied_reqs.append( get_object_or_404(PermissionRequest, id=req_id)) if request.method == "POST": # check if confirmed and then do actions. if request.POST.get("post", "no") == "yes": for req in denied_reqs: req.deny() # DatedMessage.objects.post_message_to_user( # "Request for permission %s for object %s denied." # % (req.requested_permission.permission.name, # req.requested_permission.target), # user=req.requesting_user, # sender=req.permission_owner, # msg_type=DatedMessage.TYPE_WARNING) post_message = "Request for %s denied." % str(req.requested_permission.target).capitalize() if req.requested_permission.permission.name == "can_create_project": # Removes "* Project name: " try: project_name = req.message.split("||")[0].strip()[16:] post_message = "Request for project %s creation denied." % project_name # Notify requesting user try: send_mail( settings.EMAIL_SUBJECT_PREFIX + "Denied project request for '%s'" % (project_name), "Your request for the creation of project '%s' has been denied.\n\n\nYou may want to get in contact with the Island Manager for further details." % project_name, from_email = settings.DEFAULT_FROM_EMAIL, recipient_list = [req.requesting_user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e) except: pass # ------------------------------------------- # It is not about permission granting anymore # ------------------------------------------- # Notify requesting user DatedMessage.objects.post_message_to_user( post_message, user = req.requesting_user, sender = req.permission_owner, msg_type = DatedMessage.TYPE_WARNING) # Notify user with permission (e.g. root) DatedMessage.objects.post_message_to_user( post_message, user = request.user, sender = req.permission_owner, msg_type = DatedMessage.TYPE_WARNING) for req, delegate in approved_reqs: # -------------------------------------------------------- # Do NOT grant permission to create projects in the future # -------------------------------------------------------- # req.allow(can_delegate=delegate) req.deny() # DatedMessage.objects.post_message_to_user( # "Request for permission %s for object %s approved." # % (req.requested_permission.permission.name, # req.requested_permission.target), # user=req.requesting_user, # sender=req.permission_owner, # msg_type=DatedMessage.TYPE_SUCCESS) post_message = "Request for %s approved." % str(req.requested_permission.target).capitalize() permission_user_post = post_message requesting_user_post = post_message email_header = post_message email_body = "%s." % post_message message_type = DatedMessage.TYPE_SUCCESS # --------------------------------------- # Project will be created in a direct way # --------------------------------------- if req.requested_permission.permission.name == "can_create_project": project_name = "" try: project = Project() project.uuid = uuid.uuid4() message = req.message.split("||") # Removes "* Project name: " project.name = message[0].strip()[16:] project_name = project.name # Removes "* Project description: " project.description = message[3].strip()[23:] project.urn = 'n/a' #import pdb; pdb.set_trace() if settings.ENABLE_CBAS: user_profile = UserProfile.get_or_create_profile(req.requesting_user) cert = user_profile.certificate creds = user_profile.credentials project_urn = create_project(certificate=cert, credentials=creds, project_name=project.name, project_desc=project.description) if project_urn: project.urn = project_urn post_message = "Successfully created project %s" % project.name project.save() create_project_roles(project, req.requesting_user) project.save() email_header = "Approved project request for '%s'" % project_name email_body = "Your request for the creation of project '%s' has been approved." % project_name except Exception as e: # Any error when creating a project results into: # 1. Denying the petition # 2. Notifying user in their Expedient # 3. Notifying user via e-mail post_message = "Project '%s' could not be created" % project_name permission_user_post = post_message requesting_user_post = post_message # Handle exception text for user if "duplicate entry" in str(e).lower(): email_body = "There is already a project with name '%s'. Try using a different name" % project_name requesting_user_post += ". Details: project '%s' already exists" % project_name else: email_body = "There might have been a problem when interpreting the information for project '%s'" % str(project_name) requesting_user_post += ". Contact your Island Manager for further details" # Handle exception text for admin if "Details" not in post_message: permission_user_post = "%s. Details: %s" % (post_message, str(e)) message_type = DatedMessage.TYPE_ERROR # Email for requesting user email_header = "Denied project request for '%s'" % project_name email_body = "Your request for the creation of project '%s' has been denied because of the following causes:\n\n%s\n\n\nYou may want to get in contact with the Island Manager for further details." % (project_name, email_body) # Notify requesting user DatedMessage.objects.post_message_to_user( requesting_user_post, user = req.requesting_user, sender = req.permission_owner, msg_type = message_type) try: send_mail( settings.EMAIL_SUBJECT_PREFIX + email_header, email_body, from_email = settings.DEFAULT_FROM_EMAIL, recipient_list = [req.requesting_user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e) # Notify user with permission (e.g. root) DatedMessage.objects.post_message_to_user( permission_user_post, user = request.user, sender = req.permission_owner, msg_type = message_type) # After this post we will be done with all this information del request.session["approved_req_ids"] del request.session["delegatable_req_ids"] del request.session["denied_req_ids"] return HttpResponseRedirect(reverse("home")) else: return direct_to_template( request=request, template=TEMPLATE_PATH+"/confirm_requests.html", extra_context={ "approved_reqs": approved_reqs, "denied_reqs": denied_reqs, } )
def create(request): """ Create a new project """ user_profile = UserProfile.get_or_create_profile(request.user) cert = user_profile.certificate creds = user_profile.credentials user_urn = user_profile.urn def post_save(instance, created): # Create default roles in the project #Generate UUID: fixes caching problem on model default value instance.uuid = uuid.uuid4() #<UT> instance.urn = "n/a" #import pdb; pdb.set_trace() if settings.ENABLE_CBAS: project_urn = create_project(certificate=cert, credentials=creds, project_name=instance.name, project_desc=instance.description, user_urn=user_urn) if project_urn: instance.urn = project_urn create_project_roles(instance, request.user) instance.save() #if settings.LDAP_STORE_PROJECTS: # instance.sync_netgroup_ldap() def redirect(instance): return reverse("project_detail", args=[instance.id]) try: return generic_crud( request, None, model=Project, form_class=ProjectCreateForm, template=TEMPLATE_PATH + "/create_update.html", post_save=post_save, redirect=redirect, template_object_name="project", extra_context={ "breadcrumbs": ( ("Home", reverse("home")), ("Create Project", request.path), ), }, success_msg=lambda instance: "Successfully created project %s." % instance.name, ) except Exception as e: if isinstance(e, ldap.LDAPError): DatedMessage.objects.post_message_to_user( "Project has been created but only locally since LDAP is not reachable. You will not be able to add users to the project until connection is restored.", request.user, msg_type=DatedMessage.TYPE_ERROR) else: DatedMessage.objects.post_message_to_user( "Project may have been created, but some problem ocurred: %s" % str(e), request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse("home"))
def CreateSliver(slice_urn, rspec, user): (project_name, project_desc, slice_name, slice_desc, slice_expiry, controller_url, firstname, lastname, affiliation, email, password, slivers) = rspec_mod.parse_slice(rspec) logger.debug("Parsed Rspec") slice_expiry = datetime.fromtimestamp(slice_expiry) give_permission_to("can_create_project", Project, user) user.first_name = firstname user.last_name = lastname user.email = email profile = UserProfile.get_or_create_profile(user) profile.affiliation = affiliation user.save() profile.save() # Check if the slice exists try: slice = get_slice(slice_urn) # update the slice info slice.description = slice_desc slice.name = slice_name slice.expiration_date = slice_expiry slice.save() # update the project info slice.project.name = project_name slice.project.description = project_desc slice.project.save() project = slice.project except Slice.DoesNotExist: # Check if the project exists try: project = Project.objects.get(name=project_name) # update the project info logger.debug("Updating project") project.description = project_desc project.save() except Project.DoesNotExist: # create the project logger.debug("Creating project") project = Project.objects.create( name=project_name, description=project_desc, ) create_project_roles(project, user) # create the slice logger.debug("Creating slice") try: slice = Slice.objects.create( name=slice_name, description=slice_desc, project=project, owner=user, expiration_date = slice_expiry, ) except IntegrityError: raise DuplicateSliceNameException(slice_name) logger.debug("Creating/updating slice info") # create openflow slice info for the slice create_or_update( OpenFlowSliceInfo, filter_attrs={"slice": slice}, new_attrs={ "controller_url": controller_url, "password": password, }, ) logger.debug("creating gapislice") # store a pointer to this slice using the slice_urn create_or_update( GENISliceInfo, filter_attrs={ "slice": slice, }, new_attrs={ "slice_urn": slice_urn, }, ) logger.debug("adding resources") sliver_ids = [] # delete all flowspace in the slice FlowSpaceRule.objects.filter(slivers__slice=slice).delete() # add the new flowspace for fs_dict, iface_qs in slivers: # give the user, project, slice permission to use the aggregate aggregate_ids = list(iface_qs.values_list("aggregate", flat=True)) for agg_id in aggregate_ids: aggregate = Aggregate.objects.get(id=agg_id).as_leaf_class() give_permission_to("can_use_aggregate", aggregate, user) give_permission_to("can_use_aggregate", aggregate, project) give_permission_to("can_use_aggregate", aggregate, slice) # Create flowspace logger.debug("Creating flowspace %s" % fs_dict) fs = FlowSpaceRule.objects.create(**fs_dict) # make sure all the selected interfaces are added for iface in iface_qs: sliver, _ = OpenFlowInterfaceSliver.objects.get_or_create( slice=slice, resource=iface) sliver_ids.append(sliver.id) fs.slivers.add(sliver) logger.debug("Deleting old resources") # Delete all removed interfaces OpenFlowInterfaceSliver.objects.exclude(id__in=sliver_ids).delete() logger.debug("Starting the slice %s %s" % (slice, slice.name)) # make the reservation tl = threadlocals.get_thread_locals() tl["project"] = project tl["slice"] = slice slice.start(user) logger.debug("Done creating sliver") return rspec_mod.create_resv_rspec(user, slice)
def create_resv_rspec(user, slice, aggregate=None): """Create a reservation rspec from the set of interface slivers. @param user: The user making the reservation. @type user: L{django.contrib.auth.models.User} @param slice: The slice to use in the reservation. @type slice: L{expedient.clearinghouse.slice.models.Slice} @keyword aggregate: If not None, only get the resv rspec for the specified aggregate. DDefault is None. @type aggregate: None or L{openflow.plugin.models.OpenFlowAggregate} @return: an OpenFlow reservation RSpec for the wanted slivers. @rtype: C{str} """ root = et.Element(RESV_RSPEC_TAG, { "type": "openflow", VERSION: CURRENT_RESV_VERSION }) # add the user info et.SubElement( root, USER_TAG, { FIRSTNAME: user.first_name, LASTNAME: user.last_name, AFFILIATION: UserProfile.get_or_create_profile(user).affiliation, EMAIL: user.email, PASSWORD: slice.openflowsliceinfo.password, }) # add the project info et.SubElement(root, PROJECT_TAG, { NAME: slice.project.name, DESCRIPTION: slice.project.description, }) # add the slice info et.SubElement( root, SLICE_TAG, { NAME: slice.name, DESCRIPTION: slice.description, EXPIRY: "%s" % long(time.mktime(slice.expiration_date.timetuple())), CONTROLLER: slice.openflowsliceinfo.controller_url, }) flowspace_qs = FlowSpaceRule.objects.filter( slivers__slice=slice).distinct() if aggregate: flowspace_qs = flowspace_qs.filter( slivers__resource__aggregate__id=aggregate.id).distinct() # add the flowspace for fs in flowspace_qs: fs_elem = et.SubElement(root, FLOWSPACE_TAG) for sliver in fs.slivers.all(): iface = sliver.resource.as_leaf_class() et.SubElement( fs_elem, PORT_TAG, {URN: _port_to_urn(iface.switch.datapath_id, iface.port_num)}) for tag in DL_SRC_TAG, DL_DST_TAG,\ DL_TYPE_TAG, VLAN_ID_TAG, NW_SRC_TAG, NW_DST_TAG, NW_PROTO_TAG,\ TP_SRC_TAG, TP_DST_TAG: f = getattr(fs, "%s_start" % tag) t = getattr(fs, "%s_end" % tag) d = {} if f is not None and f != "": d["from"] = str(f) if t is not None and t != "": d["to"] = str(t) if d: et.SubElement( fs_elem, tag, d, ) return et.tostring(root)
def confirm_requests(request): """Confirm the approval of the permission requests.""" approved_req_ids = request.session.setdefault("approved_req_ids", []) delegatable_req_ids = request.session.setdefault("delegatable_req_ids", []) denied_req_ids = request.session.setdefault("denied_req_ids", []) approved_reqs = [] for req_id in approved_req_ids: req = get_object_or_404(PermissionRequest, id=req_id) delegatable = req_id in delegatable_req_ids approved_reqs.append((req, delegatable)) denied_reqs = [] for req_id in denied_req_ids: denied_reqs.append(get_object_or_404(PermissionRequest, id=req_id)) if request.method == "POST": # check if confirmed and then do actions. if request.POST.get("post", "no") == "yes": for req in denied_reqs: req.deny() # DatedMessage.objects.post_message_to_user( # "Request for permission %s for object %s denied." # % (req.requested_permission.permission.name, # req.requested_permission.target), # user=req.requesting_user, # sender=req.permission_owner, # msg_type=DatedMessage.TYPE_WARNING) post_message = "Request for %s denied." % str( req.requested_permission.target).capitalize() if req.requested_permission.permission.name == "can_create_project": # Removes "* Project name: " try: project_name = req.message.split("||")[0].strip()[16:] post_message = "Request for project %s creation denied." % project_name # Notify requesting user try: send_mail( settings.EMAIL_SUBJECT_PREFIX + "Denied project request for '%s'" % (project_name), "Your request for the creation of project '%s' has been denied.\n\n\nYou may want to get in contact with the Island Manager for further details." % project_name, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[req.requesting_user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str( e) except: pass # ------------------------------------------- # It is not about permission granting anymore # ------------------------------------------- # Notify requesting user DatedMessage.objects.post_message_to_user( post_message, user=req.requesting_user, sender=req.permission_owner, msg_type=DatedMessage.TYPE_WARNING) # Notify user with permission (e.g. root) DatedMessage.objects.post_message_to_user( post_message, user=request.user, sender=req.permission_owner, msg_type=DatedMessage.TYPE_WARNING) for req, delegate in approved_reqs: # -------------------------------------------------------- # Do NOT grant permission to create projects in the future # -------------------------------------------------------- # req.allow(can_delegate=delegate) req.deny() # DatedMessage.objects.post_message_to_user( # "Request for permission %s for object %s approved." # % (req.requested_permission.permission.name, # req.requested_permission.target), # user=req.requesting_user, # sender=req.permission_owner, # msg_type=DatedMessage.TYPE_SUCCESS) post_message = "Request for %s approved." % str( req.requested_permission.target).capitalize() permission_user_post = post_message requesting_user_post = post_message email_header = post_message email_body = "%s." % post_message message_type = DatedMessage.TYPE_SUCCESS # --------------------------------------- # Project will be created in a direct way # --------------------------------------- if req.requested_permission.permission.name == "can_create_project": project_name = "" try: project = Project() project.uuid = uuid.uuid4() message = req.message.split("||") # Removes "* Project name: " project.name = message[0].strip()[16:] project_name = project.name # Removes "* Project description: " project.description = message[3].strip()[23:] project.urn = 'n/a' #import pdb; pdb.set_trace() if settings.ENABLE_CBAS: user_profile = UserProfile.get_or_create_profile( req.requesting_user) cert = user_profile.certificate creds = user_profile.credentials project_urn = create_project( certificate=cert, credentials=creds, project_name=project.name, project_desc=project.description, user_urn=user_profile.urn) if project_urn: project.urn = project_urn post_message = "Successfully created project %s" % project.name project.save() create_project_roles(project, req.requesting_user) project.save() email_header = "Approved project request for '%s'" % project_name email_body = "Your request for the creation of project '%s' has been approved." % project_name except Exception as e: # Any error when creating a project results into: # 1. Denying the petition # 2. Notifying user in their Expedient # 3. Notifying user via e-mail post_message = "Project '%s' could not be created" % project_name permission_user_post = post_message requesting_user_post = post_message # Handle exception text for user if "duplicate entry" in str(e).lower(): email_body = "There is already a project with name '%s'. Try using a different name" % project_name requesting_user_post += ". Details: project '%s' already exists" % project_name else: email_body = "There might have been a problem when interpreting the information for project '%s'" % str( project_name) requesting_user_post += ". Contact your Island Manager for further details" # Handle exception text for admin if "Details" not in post_message: permission_user_post = "%s. Details: %s" % ( post_message, str(e)) message_type = DatedMessage.TYPE_ERROR # Email for requesting user email_header = "Denied project request for '%s'" % project_name email_body = "Your request for the creation of project '%s' has been denied because of the following causes:\n\n%s\n\n\nYou may want to get in contact with the Island Manager for further details." % ( project_name, email_body) # Notify requesting user DatedMessage.objects.post_message_to_user( requesting_user_post, user=req.requesting_user, sender=req.permission_owner, msg_type=message_type) try: send_mail( settings.EMAIL_SUBJECT_PREFIX + email_header, email_body, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[req.requesting_user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str( e) # Notify user with permission (e.g. root) DatedMessage.objects.post_message_to_user( permission_user_post, user=request.user, sender=req.permission_owner, msg_type=message_type) # After this post we will be done with all this information del request.session["approved_req_ids"] del request.session["delegatable_req_ids"] del request.session["denied_req_ids"] return HttpResponseRedirect(reverse("home")) else: return direct_to_template(request=request, template=TEMPLATE_PATH + "/confirm_requests.html", extra_context={ "approved_reqs": approved_reqs, "denied_reqs": denied_reqs, })
def add_member(request, proj_id): """ Add a member to the project """ project = get_object_or_404(Project, id=proj_id) if request.method == "POST": form = AddMemberForm(project=project, giver=request.user, data=request.POST) if form.is_valid(): user = User.objects.get(id = request.POST['user'] ) #<UT> if settings.ENABLE_CBAS: user_to_add = UserProfile.get_or_create_profile(user) op_user = UserProfile.get_or_create_profile(request.user) add_member_to_project(project_urn=project.urn, to_add_user_urn=user_to_add.urn, to_add_user_certificate=user_to_add.certificate, authz_user_urn=op_user.urn, authz_user_certificate=op_user.certificate) form.save() try: #Sync LDAP project.save() except: logger.warning("User '%s' may have not been added to project '%s'. It could be a bug within LDAP." % (user.username, project.name)) DatedMessage.objects.post_message_to_user( "User '%s' may not own the requested permissions. It could be a bug within LDAP." % user.username, request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse("project_detail", args=[proj_id])) #Send mail notification to the user roles = ', '.join(repr(role.encode('ascii')) for role in ProjectRole.objects.filter( id__in = request.POST.getlist('roles')).values_list('name', flat=True)) #XXX: Not sure about this... maybe give_permission_to... for aggregate in project._get_aggregates(): if not has_permission(user, aggregate, "can_use_aggregate"): aggregate.add_to_user(user,"/") try: # Get project detail URL to send via e-mail from expedient.clearinghouse.project import urls project_detail_url = reverse("project_detail", args=[project.id]) or "/" # No "https://" check should be needed if settings are OK site_domain_url = "https://" + Site.objects.get_current().domain + project_detail_url send_mail( settings.EMAIL_SUBJECT_PREFIX + "Project %s membership notification" % (project.name), "You have been added to project '%s' as a user with the following roles: %s.\nYou may start experimenting now by going to %s\n\n" % (project.name, roles, site_domain_url), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e) return HttpResponseRedirect(reverse("project_detail", args=[proj_id])) else: form = AddMemberForm(project=project, giver=request.user) return simple.direct_to_template( request, template=TEMPLATE_PATH+"/add_member.html", extra_context={ "form": form, "project": project, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Add Member", request.path), ), }, )
def create_resv_rspec(user, slice, aggregate=None): """Create a reservation rspec from the set of interface slivers. @param user: The user making the reservation. @type user: L{django.contrib.auth.models.User} @param slice: The slice to use in the reservation. @type slice: L{expedient.clearinghouse.slice.models.Slice} @keyword aggregate: If not None, only get the resv rspec for the specified aggregate. DDefault is None. @type aggregate: None or L{openflow.plugin.models.OpenFlowAggregate} @return: an OpenFlow reservation RSpec for the wanted slivers. @rtype: C{str} """ root = et.Element( RESV_RSPEC_TAG, {"type": "openflow", VERSION: CURRENT_RESV_VERSION}) # add the user info et.SubElement( root, USER_TAG, { FIRSTNAME: user.first_name, LASTNAME: user.last_name, AFFILIATION: UserProfile.get_or_create_profile(user).affiliation, EMAIL: user.email, PASSWORD: slice.openflowsliceinfo.password, } ) # add the project info et.SubElement( root, PROJECT_TAG, { NAME: slice.project.name, DESCRIPTION: slice.project.description, } ) # add the slice info et.SubElement( root, SLICE_TAG, { NAME: slice.name, DESCRIPTION: slice.description, EXPIRY: "%s" % long(time.mktime(slice.expiration_date.timetuple())), CONTROLLER: slice.openflowsliceinfo.controller_url, } ) flowspace_qs = FlowSpaceRule.objects.filter( slivers__slice=slice).distinct() if aggregate: flowspace_qs = flowspace_qs.filter( slivers__resource__aggregate__id=aggregate.id).distinct() # add the flowspace for fs in flowspace_qs: fs_elem = et.SubElement(root, FLOWSPACE_TAG) for sliver in fs.slivers.all(): iface = sliver.resource.as_leaf_class() et.SubElement( fs_elem, PORT_TAG, { URN: _port_to_urn(iface.switch.datapath_id, iface.port_num) } ) for tag in DL_SRC_TAG, DL_DST_TAG,\ DL_TYPE_TAG, VLAN_ID_TAG, NW_SRC_TAG, NW_DST_TAG, NW_PROTO_TAG,\ TP_SRC_TAG, TP_DST_TAG: f = getattr(fs, "%s_start" % tag) t = getattr(fs, "%s_end" % tag) d = {} if f is not None and f != "": d["from"] = str(f) if t is not None and t != "": d["to"] = str(t) if d: et.SubElement( fs_elem, tag, d, ) return et.tostring(root)
def remove_member(request, proj_id, user_id): """ Kick a member out by stripping his roles """ project = get_object_or_404(Project, id=proj_id) member = get_object_or_404(User, id=user_id) if request.method == "POST": #<UT> if settings.ENABLE_CBAS: authz_user = UserProfile.get_or_create_profile(request.user) user_to_remove = UserProfile.get_or_create_profile(member) remove_member_from_project(project.urn, user_to_remove.urn, authz_user.urn, authz_user.certificate) member = Permittee.objects.get_as_permittee(member) # Remove the roles for role in ProjectRole.objects.filter(project=project): role.remove_from_permittee(member) # Remove other permissions PermissionOwnership.objects.delete_all_for_target(project, member) #Remove can_use_aggregate if user is not member of any other project using the aggregates of this project for projectAgg in project._get_aggregates(): aggNotUsedAnymoreByMember = 1 for p in Project.objects.exclude(id=project.id): if projectAgg in p._get_aggregates() and unicode( member) in p.members.values_list("username", flat=True): aggNotUsedAnymoreByMember = 0 break if aggNotUsedAnymoreByMember and not has_permission( member, projectAgg, "can_use_aggregate"): projectAgg.remove_from_user(member, "/") try: #Sync LDAP project.save() except: logger.warning( "User '%s' may have not been deleted from project '%s'. It could be a bug within LDAP." % (member.object.username, project.name)) return HttpResponseRedirect(reverse("project_detail", args=[proj_id])) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/remove_member.html", extra_context={ "project": project, "member": member, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Remove Member %s" % member.username, request.path), ), }, )