def determine_login(request, message=None, template_name=None, redirect_url=None, redirect_viewname=None): if "next" in request.GET: next = request.GET['next'] elif not redirect_url: if redirect_viewname != None: next = reverse(redirect_viewname) else: next = settings.RESOURCE_REDIRECT_URL else: next = redirect_url if not template_name: institution = authentication_tools.get_institution(request) institutional_idp = IdentityProvider.objects.filter(institution__iexact=str(institution)) if not institutional_idp: log.debug("No institution") return HttpResponse("There is no Identity Provider specified for your institution") else: authentication_type = institutional_idp[0].type template_name = 'idpauth/' + str(authentication_type) + '.html' if authentication_type == 'local': return HttpResponseRedirect(reverse("local_login_url", kwargs={ 'template_name' : template_name, 'redirect_url' : next, })) return render_to_response(template_name, {'next': next, 'message' : message, }, context_instance=RequestContext(request))
def local_login(request, template_name=None, redirect_url=None, redirect_viewname=None): message = None if "next" in request.REQUEST: next = request.REQUEST['next'] elif not redirect_url: if redirect_viewname != None: next = reverse(redirect_viewname) else: next = settings.RESOURCE_REDIRECT_URL else: next = redirect_url if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) log.debug("Auhentication") if user is not None: login(request, user) log.debug("Login") institution = authentication_tools.get_institution(request) authentication_tools.add_session_username(request, username) return HttpResponseRedirect(next) else: message = "Invalid username or password" form = AuthenticationForm() else: form = AuthenticationForm() return render_to_response(template_name, { 'form' : form, 'next' : next, 'message' : message, }, context_instance=RequestContext(request))
def log_user_off(self, username): try: output = self.node.ssh_run_command(["pkill", "-KILL", "-u", str(username)]) log.debug("Logged %s off" % username) return output except HostNotConnectableError: return False
def setUp(self): self.app1 = Application.objects.create(name="TestApp1", image_id="1234", max_concurrent_instances=3, users_per_small=4, cluster_headroom=5, icon_url="http://nopath", ssh_key='key.fake') self.app2 = Application.objects.create(name="TestApp2", image_id="12345", max_concurrent_instances=3, users_per_small=4, cluster_headroom=5, icon_url="http://nopath", ssh_key='key.fake') self.inst1 = Instance.objects.create(instanceId='10', application=self.app1, priority=0, state=5) self.inst1.shutdownDateTime=datetime(2010,5,13,18,00) self.inst1.startUpDateTime=datetime(2010,5,13,12,00) self.inst1.save() self.inst2 = Instance.objects.create(instanceId='11', application=self.app1, priority=0, state=2) self.inst2.shutdownDateTime=datetime(2010,5,14,8,00) self.inst2.startUpDateTime=datetime(2010,5,14,8,00) self.inst2.save() self.inst3 = Instance.objects.create(instanceId='12', application=self.app2, priority=0, state=5) self.inst3.shutdownDateTime=datetime(2010,5,12,18,00) self.inst3.startUpDateTime=datetime(2010,5,11,8,00) self.inst3.save() app = Application.objects.all() tmp_list = list(app) log.debug("TMP 2 : " + str(tmp_list[0])) log.debug("TMP 1 : " + str(tmp_list[1])) log.debug(tmp_list[0].image_id) tmp_list[0].image_id = '4321' tmp_list[0].save() log.debug(tmp_list[0].image_id) app_tmp = Application.objects.all() log.debug(app_tmp)
def test_get_all_user_wait_times(self): self.failUnlessEqual( user_experience_tools.get_all_user_wait_times(self.app1), [120, 360]) log.debug( "***TEST*** user Wait Times: " + str(user_experience_tools.get_all_user_wait_times(self.app1)))
def upgrade_app(self, appname, to): """Upgrades the given app to the given version.""" if "/" in appname or "\\" in appname: raise ValueError("Bad app name") self._check_appname(appname) log.info("Upgrading {0} to version {1}".format( appname, to)) apppath = os.path.join(self.projectdir, appname) apptype = opus.lib.builder.sources.introspect_source(apppath) log.debug("apppath is %s", apppath) log.debug("apptype is %s", apptype) opus.lib.builder.sources.upgrade_functions[apptype](apppath, to) # If there isn't a media link and there should be, add one if os.path.exists(os.path.join(self.projectdir, appname, "media")) \ and not os.path.exists(os.path.join(self.projectdir, "media",appname)): os.symlink(os.path.join("..",appname,"media"), os.path.join(self.projectdir, "media",appname)) self._touch_wsgi()
def add_session_username(request, username): clean_username = username.split('++') if len(clean_username) == 1: clean_username = clean_username[0] else: clean_username = clean_username[1] log.debug("Clean username for session is " + str(clean_username)) request.session['username'] = clean_username
def add_local_identifier(sender, instance, created, **kwargs): if created: user = instance.username.split('++') if settings.SEND_EMAIL_ON_USER_CREATION: log.debug("sending email") send_mail(settings.EMAIL_SUBJECT, settings.EMAIL_MESSAGE + " " + user[0], settings.FROM_EMAIL_ADDRESS, [settings.EMAIL_TO], fail_silently=False) log.debug("Email sent")
def test_get_user_application_arrival_times(self): self.failUnlessEqual( self.ue1.access_date.ctime(), user_experience_tools.get_user_application_arrival_times( self.app1)[0].ctime()) log.debug( user_experience_tools.get_user_application_arrival_times( self.app1))
def test_get_user_applications_on_date(self): self.failUnlessEqual( user_experience_tools.get_user_applications_in_date_range( self.user1, datetime(2010, 5, 14, 00), datetime(2010, 5, 14, 23, 59)), [self.app1, self.app2]) log.debug("***TEST*** User Applications on Date: " + str( user_experience_tools.get_user_applications_in_date_range( self.user1, datetime(2010, 5, 14, 00), datetime(2010, 5, 14, 23, 59))))
def shibboleth_login(request): try: username = request.META['REMOTE_USER'] user_tools.login(request, username, "T", "null") return HttpResponse("Remote user set to: " + remote_user) except KeyError, e: log.debug(e) return HttpResponse("Remote user not set.")
def test_get_total_instance_hours(self): app = Application.objects.all() log.debug("***TEST*** APP CHANGE : " + app[0].image_id) instances = Instance.objects.all() self.failUnlessEqual( cost_tools.get_total_instance_hours(instances, datetime(2010, 5, 10, 8, 00), datetime(2010, 5, 14, 22, 00)), 54)
def set_attributes(auth_request): requested_attributes = OPENID_AX if requested_attributes: log.debug("AX true") ax_request = oidax.FetchRequest() for i in requested_attributes: ax_request.add(oidax.AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(ax_request) return auth_request
def add_user(self, username, password): try: output = self.node.ssh_run_command(["adduser", username]) output = self.change_user_password(username, password) log.debug('THE PASSWORD WAS SET') log.debug("Added %s" % username) return True, "" except HostNotConnectableError: return False, ""
def test_procesS_user_connections(self): user_experience_tools.process_user_connections(self.app_node) us_exp1 = UserExperience.objects.filter(user=self.user3).filter(connection_opened__isnull=False) self.failIfEqual(us_exp1[0].connection_opened, None) log.debug("****TEST**** connection opened = " + str(us_exp1[0].connection_opened)) self.app_node.sessions.remove(self.session) user_experience_tools.process_user_connections(self.app_node) us_exp2 = UserExperience.objects.filter(user=self.user3).filter(connection_closed__isnull=False) self.failIfEqual(us_exp2[0].connection_closed, None) log.debug("****TEST**** connection closed = " + str(us_exp2[0].connection_closed))
def set_attributes(auth_request): requested_attributes = OPENID_AX if requested_attributes: log.debug("AX true") ax_request = oidax.FetchRequest() for i in requested_attributes: ax_request.add( oidax.AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(ax_request) return auth_request
def test_get_instance_hours_in_date_range(self): app = Application.objects.all() log.debug("***TEST*** APP CHANGE : " + app[0].image_id) self.failUnlessEqual( cost_tools.get_instance_hours_in_date_range( datetime(2010, 5, 14, 1, 00), datetime(2010, 5, 14, 14, 00)), 6) self.failUnlessEqual( cost_tools.get_instance_hours_in_date_range( datetime(2010, 5, 12, 1, 00), datetime(2010, 5, 14, 14, 00)), 12)
def test_procesS_user_connections(self): user_experience_tools.process_user_connections(self.app_node) us_exp1 = UserExperience.objects.filter(user=self.user3).filter( connection_opened__isnull=False) self.failIfEqual(us_exp1[0].connection_opened, None) log.debug("****TEST**** connection opened = " + str(us_exp1[0].connection_opened)) self.app_node.sessions.remove(self.session) user_experience_tools.process_user_connections(self.app_node) us_exp2 = UserExperience.objects.filter(user=self.user3).filter( connection_closed__isnull=False) self.failIfEqual(us_exp2[0].connection_closed, None) log.debug("****TEST**** connection closed = " + str(us_exp2[0].connection_closed))
def start_node(self): """ Starts a new node on the cluster. This function first tries to reuse a 'shutting-down' node first. If no 'shutting-down' nodes are available to reuse, start a new one. """ # Consider if we can re-use a node about to be shutdown, or if we should create a new one if self.shutting_down: new_node = self.shutting_down[0] new_node.state = 2 new_node.priority = self.find_next_priority() else: new_instance_id = driver_tools.create_instance(self.app.image_id) new_priority = self.find_next_priority() log.debug('New instance created with id %s and priority %s' % (new_instance_id,new_priority)) new_node = Instance(instanceId=new_instance_id,application=self.app,priority=new_priority) new_node.save()
def begin_openid(session, trust_root, openid_url, resource_redirect_url, redirect_to=None): if not redirect_to: redirect_to = trust_root + '/idpauth/openid_login_complete/' + '?next=' + resource_redirect_url else: redirect_to = trust_root + '/' + redirect_to + '?next=' + resource_redirect_url log.debug(redirect_to) consumer = Consumer(session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: return None auth_request = set_attributes(auth_request) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return redirect_url
def get_ldap_roles(server, username, password): timeout = 0 result_set = [] try: ldap_session = ldap.open(server.url) ldap_session.protocol_version = ldap.VERSION3 if server.ssl_option == True: ldap_session.start_tls_s() ldap_session.set_option(ldap.OPT_X_TLS_DEMAND, True) else: ldap_session.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) user_dn = "uid=" + username if server.distinguished_name: search_string = server.distinguished_name + ',' + server.bind_base else: search_string = server.bind_base authentication_string = user_dn + "," + search_string log.debug(authentication_string) ldap_session.simple_bind_s(authentication_string, password) if server.group_retrieval_string != '': result_id = ldap_session.search( search_string, ldap.SCOPE_SUBTREE, user_dn, [str(server.group_retrieval_string)]) while 1: result_type, result_data = ldap_session.result( result_id, timeout) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) #log.debug(result_set) roles = result_set[0][0][1][str(server.group_retrieval_string)] #log.debug("LDAP Roles = " + str(roles)) return roles else: return {} except ldap.LDAPError, e: log.debug("LDAP Error: " + str(e)) return None
def setUp(self): self.app1 = Application.objects.create(name="TestApp1", image_id="1234", max_concurrent_instances=3, users_per_small=4, cluster_headroom=5, icon_url="http://nopath", ssh_key='key.fake') self.app2 = Application.objects.create(name="TestApp2", image_id="12345", max_concurrent_instances=3, users_per_small=4, cluster_headroom=5, icon_url="http://nopath", ssh_key='key.fake') self.inst1 = Instance.objects.create(instanceId='10', application=self.app1, priority=0, state=5) self.inst1.shutdownDateTime = datetime(2010, 5, 13, 18, 00) self.inst1.startUpDateTime = datetime(2010, 5, 13, 12, 00) self.inst1.save() self.inst2 = Instance.objects.create(instanceId='11', application=self.app1, priority=0, state=2) self.inst2.shutdownDateTime = datetime(2010, 5, 14, 8, 00) self.inst2.startUpDateTime = datetime(2010, 5, 14, 8, 00) self.inst2.save() self.inst3 = Instance.objects.create(instanceId='12', application=self.app2, priority=0, state=5) self.inst3.shutdownDateTime = datetime(2010, 5, 12, 18, 00) self.inst3.startUpDateTime = datetime(2010, 5, 11, 8, 00) self.inst3.save() app = Application.objects.all() tmp_list = list(app) log.debug("TMP 2 : " + str(tmp_list[0])) log.debug("TMP 1 : " + str(tmp_list[1])) log.debug(tmp_list[0].image_id) tmp_list[0].image_id = '4321' tmp_list[0].save() log.debug(tmp_list[0].image_id) app_tmp = Application.objects.all() log.debug(app_tmp)
def openid_login(request, redirect_to=None): openid_url = request.POST['openid_url'] resource_redirect_url = request.POST['next'] log.debug(resource_redirect_url) institution = authentication_tools.get_institution(request) session = request.session trust_root = authentication_tools.get_url_host(request) if not redirect_to: redirect_url = openid_tools.begin_openid(session, trust_root, openid_url, resource_redirect_url) else: log.debug(redirect_to) redirect_url = openid_tools.begin_openid(session, trust_root, openid_url, resource_redirect_url, redirect_to) if not redirect_url: return HttpResponse('The OpenID was invalid') else: return HttpResponseRedirect(redirect_url)
def get_ldap_roles(server, username, password): timeout = 0 result_set = [] try: ldap_session = ldap.open(server.url) ldap_session.protocol_version = ldap.VERSION3 if server.ssl_option == True: ldap_session.start_tls_s() ldap_session.set_option(ldap.OPT_X_TLS_DEMAND, True) else: ldap_session.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) user_dn = "uid=" + username if server.distinguished_name: search_string = server.distinguished_name + ',' + server.bind_base else: search_string = server.bind_base authentication_string = user_dn + "," + search_string log.debug(authentication_string) ldap_session.simple_bind_s(authentication_string, password) if server.group_retrieval_string != '': result_id = ldap_session.search(search_string,ldap.SCOPE_SUBTREE,user_dn,[str(server.group_retrieval_string)]) while 1: result_type, result_data = ldap_session.result(result_id, timeout) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) #log.debug(result_set) roles = result_set[0][0][1][str(server.group_retrieval_string)] #log.debug("LDAP Roles = " + str(roles)) return roles else: return {} except ldap.LDAPError, e: log.debug("LDAP Error: " + str(e)) return None
def terminate_instances(instances): """Turns off the list of instances given. instances should be an iterable of vdi.models.Instance objects, for example, a django queryset. The number of instances that were successfully terminated is returned. """ num = 0 for instance in instances: prov_instance = driver.instance(instance.instanceId) if prov_instance.stop(): dbitem = Instance.objects.filter(instanceId=instance.instanceId)[0] log.debug('The node has been deleted. I will now move %s into a deleted state' % dbitem.instanceId) dbitem.state = 5 dbitem.save() num += 1 else: log.warning('Could not shut down instance "%s"' % instance.instanceId) return num
def user_registration(request, template_name=None, redirect_url=None): if "next" in request.REQUEST: next = request.REQUEST['next'] log.debug("Setting next " + next) elif not redirect_url: next = settings.RESOURCE_REDIRECT_URL else: next = redirect_url if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() log.debug("Redirecting to: " + next) return HttpResponseRedirect(next) else: form = UserCreationForm() return render_to_response(template_name, { 'form' : form, 'next' : next, }, context_instance=RequestContext(request))
def show_cost(request): log.debug('cost = ') log.debug('weekday = %s' % datetime.now().weekday()) log.debug(datetime.now().isocalendar()) yesterday_midnight = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) day = cost_tools.get_instance_hours_in_date_range(yesterday_midnight, datetime.now()) month_midnight = datetime.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0) month = cost_tools.get_instance_hours_in_date_range( month_midnight, datetime.now()) year_midnight = datetime.today().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) week_midnight = year_midnight + timedelta( weeks=datetime.today().isocalendar()[1]) week = cost_tools.get_instance_hours_in_date_range(week_midnight, datetime.now()) return render_to_response('vdi/cost_display.html', { 'day': day, 'week': week, 'month': month }, context_instance=RequestContext(request))
def user_cleanup(self, timeout): """ Checks idle time for all sessions on the node. If any session is disconnected then the user is logged off. If the idle time exceeds the timeout parameter, the user is logged off. Timeout is in MINUTES. """ log.debug(self.sessions) for session in self.sessions: log.debug("Reported idletime: " + session["idletime"]) if session["state"] == "Disc": self.log_user_off(session["sessionid"]) elif (session["idletime"] == ".") or (session["idletime"] == "none"): continue else: days = session["idletime"].split("+") if len(days) > 1: idletime = 24 * 60 * int(days[0]) for i, digit in enumerate(days[1].split(":")): if i == 0: idletime += 60 * int(digit) else: idletime += int(digit) else: idletime = 0 hoursandmins = days[0].split(":") if len(hoursandmins) > 1: idletime += 60 * int(hoursandmins[0]) idletime += int(hoursandmins[1]) else: idletime += int(hoursandmins[0]) log.debug("Calculated idle time: " + str(idletime)) if idletime > timeout: self.log_user_off(session["sessionid"])
def add_user(self, username, password): try: output = self.node.ssh_run_command(["NET", "USER", username, password, "/ADD"]) if output.find("The command completed successfully.") > -1: log.debug("User %s has been created" % username) elif output.find("The account already exists.") > -1: log.debug("User %s already exists, going to try to set the password" % username) output = self.change_user_password(username, password) if output.find("The command completed successfully.") > -1: log.debug("THE PASSWORD WAS RESET") else: error_string = ( "An unknown error occured while trying to set the password for user %s on machine %s. The error from the machine was %s" % (username, self.ip, output) ) log.error(error_string) return False, error_string else: error_string = ( "An unknown error occured while trying to create user %s on machine %s. The error from the machine was %s" % (username, self.ip, output) ) log.error(error_string) return False, error_string return True, "" except HostNotConnectableError: return False, ""
def user_cleanup(self, timeout): """ Checks idle time for all sessions on the node. If any session is disconnected then the user is logged off. If the idle time exceeds the timeout parameter, the user is logged off. Timeout is in MINUTES. """ log.debug(self.sessions) for session in self.sessions: log.debug("Reported idletime: " + session["idletime"]) if 's' in session["idletime"]: seconds = session["idletime"].split('s')[0] idletime = float(seconds) / 60 elif 'm' in session["idletime"]: idletime = session["idletime"].split('m')[0].split(':') minutes = idletime[1] hours = idletime[0] idletime = int(hours) * 60 + int(minutes) elif 'days'in session["idletime"]: days = session["idletime"].split('days')[0] idletime = float(days) * 24 * 60 else: idletime = session["idletime"].split(':') minutes = idletime[0] seconds = idletime[1] idletime = int(minutes) + (int(seconds) / 60) log.debug("Calculated idle time: "+str(idletime)) if(idletime > timeout): self.log_user_off(session["username"])
def determine_login(request, message=None, template_name=None, redirect_url=None, redirect_viewname=None): if "next" in request.GET: next = request.GET['next'] elif not redirect_url: if redirect_viewname != None: next = reverse(redirect_viewname) else: next = settings.RESOURCE_REDIRECT_URL else: next = redirect_url if not template_name: institution = authentication_tools.get_institution(request) institutional_idp = IdentityProvider.objects.filter( institution__iexact=str(institution)) if not institutional_idp: log.debug("No institution") return HttpResponse( "There is no Identity Provider specified for your institution") else: authentication_type = institutional_idp[0].type template_name = 'idpauth/' + str(authentication_type) + '.html' if authentication_type == 'local': return HttpResponseRedirect( reverse("local_login_url", kwargs={ 'template_name': template_name, 'redirect_url': next, })) return render_to_response(template_name, { 'next': next, 'message': message, }, context_instance=RequestContext(request))
def local_login(request, template_name=None, redirect_url=None, redirect_viewname=None): message = None if "next" in request.REQUEST: next = request.REQUEST['next'] elif not redirect_url: if redirect_viewname != None: next = reverse(redirect_viewname) else: next = settings.RESOURCE_REDIRECT_URL else: next = redirect_url if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) log.debug("Auhentication") if user is not None: login(request, user) log.debug("Login") institution = authentication_tools.get_institution(request) authentication_tools.add_session_username(request, username) return HttpResponseRedirect(next) else: message = "Invalid username or password" form = AuthenticationForm() else: form = AuthenticationForm() return render_to_response(template_name, { 'form': form, 'next': next, 'message': message, }, context_instance=RequestContext(request))
def user_registration(request, template_name=None, redirect_url=None): if "next" in request.REQUEST: next = request.REQUEST['next'] log.debug("Setting next " + next) elif not redirect_url: next = settings.RESOURCE_REDIRECT_URL else: next = redirect_url if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() log.debug("Redirecting to: " + next) return HttpResponseRedirect(next) else: form = UserCreationForm() return render_to_response(template_name, { 'form': form, 'next': next, }, context_instance=RequestContext(request))
def create_application_permission(sender, instance, **kwargs): try: app = sender.objects.get(pk=instance.id) perm = Permission.objects.get(codename='use_%s' % app.name) if not instance.name == app.name: log.debug("Application being saved - name: " + str(app.name)) perm.name = 'Use %s' % instance.name perm.codename = 'use_%s' % instance.name perm.save() except ObjectDoesNotExist: log.debug("No permission") log.debug('Use %s' % instance.name) log.debug('vdi.use_%s' % instance.name) ct = ContentType.objects.get(model='application', app_label='vdi') perm = Permission.objects.create(name='Use %s' % instance.name, content_type = ct, codename='use_%s' % instance.name)
def terminate_instances(instances): """Turns off the list of instances given. instances should be an iterable of vdi.models.Instance objects, for example, a django queryset. The number of instances that were successfully terminated is returned. """ num = 0 for instance in instances: prov_instance = driver.instance(instance.instanceId) if prov_instance.stop(): dbitem = Instance.objects.filter(instanceId=instance.instanceId)[0] log.debug( 'The node has been deleted. I will now move %s into a deleted state' % dbitem.instanceId) dbitem.state = 5 dbitem.save() num += 1 else: log.warning('Could not shut down instance "%s"' % instance.instanceId) return num
def get_os_type(ip, ssh_key): node = NodeUtil(ip, ssh_key) log.debug("Checking OS Type") output = node.ssh_run_command(["uname"]) if "Linux" in output: log.debug("Found a Linux machine") return "linux" else: log.debug("Found a Windows machine") return "windows" return "None"
def openid_login_complete(request): institution = authentication_tools.get_institution(request) resource_redirect_url = request.GET['next'] session = request.session host = authentication_tools.get_url_host(request) nonce = request.GET['janrain_nonce'] if not "" == settings.OPENID_COMPLETE_URL: url = openid_tools.get_return_url(host, nonce, settings.OPENID_COMPLETE_URL) else: url = openid_tools.get_return_url(host, nonce) query_dict = dict([(k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()]) status, username = openid_tools.complete_openid(session, query_dict, url) if status == "SUCCESS": username = username user = authenticate(username=username) if user is not None: log.debug("Logging user in") login(request, user) authentication_tools.add_session_username(request, username.split('@')[0]) log.debug("Redirecting to " + resource_redirect_url) return HttpResponseRedirect(resource_redirect_url) else: log.debug("No user found") return HttpResponseRedirect(settings.LOGIN_URL) elif status == "CANCEL": message = "OpenID login failed due to a cancelled request. This can be due to failure to release email address which is required by the service." return render_to_response('idpauth/openid.html', { 'message': message, 'next': resource_redirect_url, }, context_instance=RequestContext(request)) elif status == "FAILURE": return render_to_response('idpauth/openid.html', { 'message': username, 'next': resource_redirect_url, }, context_instance=RequestContext(request)) else: message = "An error was encountered" return render_to_response('idpauth/openid.html', { 'message': message, 'next': resource_redirect_url, }, context_instance=RequestContext(request))
def ldap_login(request): username = request.POST['username'] password = request.POST['password'] resource_redirect_url = request.POST['next'] institution = authentication_tools.get_institution(request) identityprovider = IdentityProviderLDAP.objects.filter( institution__iexact=str(institution)) if identityprovider: server = identityprovider[0] roles = ldap_tools.get_ldap_roles(server, username, password) username = institution + "++" + username user = authenticate(username=username) roles = str(roles).strip('[').strip(']') try: user_profile = user.get_profile() user_profile.ldap_roles = roles user_profile.save() except ObjectDoesNotExist: user_profile = UserProfile(user=user, ldap_roles=roles) user_profile.save() if user is not None: if roles == None: log.debug("Roles were none, redirecting to login") return HttpResponseRedirect(settings.LOGIN_URL) else: log.debug("Logging user in") login(request, user) authentication_tools.add_session_username(request, username) log.debug("Redirecting to " + resource_redirect_url) return HttpResponseRedirect(resource_redirect_url) else: log.debug("No user found") return HttpResponseRedirect(settings.LOGIN_URL) else: message = 'There were errors retrieving the identity provider' return render_to_response('idpauth/ldap.html', { 'next': resource_redirect_url, 'message': message }, context_instance=RequestContext(request))
def ldap_login(request): username = request.POST['username'] password = request.POST['password'] resource_redirect_url = request.POST['next'] institution = authentication_tools.get_institution(request) identityprovider = IdentityProviderLDAP.objects.filter(institution__iexact=str(institution)) if identityprovider: server = identityprovider[0] roles = ldap_tools.get_ldap_roles(server, username, password) username = institution + "++" + username user = authenticate(username=username) roles = str(roles).strip('[').strip(']') try: user_profile = user.get_profile() user_profile.ldap_roles = roles user_profile.save() except ObjectDoesNotExist: user_profile = UserProfile(user=user, ldap_roles=roles) user_profile.save() if user is not None: if roles == None: log.debug("Roles were none, redirecting to login") return HttpResponseRedirect(settings.LOGIN_URL) else: log.debug("Logging user in") login(request, user) authentication_tools.add_session_username(request, username) log.debug("Redirecting to " + resource_redirect_url) return HttpResponseRedirect(resource_redirect_url) else: log.debug("No user found") return HttpResponseRedirect(settings.LOGIN_URL) else: message = 'There were errors retrieving the identity provider' return render_to_response('idpauth/ldap.html', {'next' : resource_redirect_url, 'message' : message}, context_instance=RequestContext(request))
def show_cost(request): log.debug('cost = ') log.debug('weekday = %s' % datetime.now().weekday()) log.debug(datetime.now().isocalendar()) yesterday_midnight = datetime.today().replace(hour=0,minute=0,second=0,microsecond=0) day = cost_tools.get_instance_hours_in_date_range(yesterday_midnight,datetime.now()) month_midnight = datetime.today().replace(day=1,hour=0,minute=0,second=0,microsecond=0) month = cost_tools.get_instance_hours_in_date_range(month_midnight,datetime.now()) year_midnight = datetime.today().replace(month=1,day=1,hour=0,minute=0,second=0,microsecond=0) week_midnight = year_midnight +timedelta(weeks=datetime.today().isocalendar()[1]) week = cost_tools.get_instance_hours_in_date_range(week_midnight,datetime.now()) return render_to_response('vdi/cost_display.html', {'day' : day, 'week' : week, 'month' : month}, context_instance=RequestContext(request))
def openid_login_complete(request): institution = authentication_tools.get_institution(request) resource_redirect_url = request.GET['next'] session = request.session host = authentication_tools.get_url_host(request) nonce = request.GET['janrain_nonce'] if not "" == settings.OPENID_COMPLETE_URL: url = openid_tools.get_return_url(host, nonce, settings.OPENID_COMPLETE_URL) else: url = openid_tools.get_return_url(host, nonce) query_dict = dict([ (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()]) status, username = openid_tools.complete_openid(session, query_dict, url) if status == "SUCCESS": username = username user = authenticate(username=username) if user is not None: log.debug("Logging user in") login(request, user) authentication_tools.add_session_username(request, username.split('@')[0]) log.debug("Redirecting to " + resource_redirect_url) return HttpResponseRedirect(resource_redirect_url) else: log.debug("No user found") return HttpResponseRedirect(settings.LOGIN_URL) elif status == "CANCEL": message = "OpenID login failed due to a cancelled request. This can be due to failure to release email address which is required by the service." return render_to_response('idpauth/openid.html', {'message' : message, 'next' : resource_redirect_url,}, context_instance=RequestContext(request)) elif status == "FAILURE": return render_to_response('idpauth/openid.html', {'message' : username, 'next' : resource_redirect_url,}, context_instance=RequestContext(request)) else: message = "An error was encountered" return render_to_response('idpauth/openid.html', {'message' : message, 'next' : resource_redirect_url, }, context_instance=RequestContext(request))
def authenticate(self, username=None, password=None): if not username: return None else: if password == None: log.debug("Non-local authen") user, created = User.objects.get_or_create(username=username) return user else: log.debug("local authen") try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: log.debug("User not found in database") return None
def process_user_connections(app_node): from opus.lib import log log = log.get_logger('vdi') user_experience = UserExperience.objects.exclude(connection_closed__isnull=False) for user_exp in user_experience: for session in app_node.sessions: if user_exp.user.username.split('++')[1].split('@')[0] == session['username']: if user_exp.connection_opened == None: log.debug("Setting the connection_opened parameter") user_exp.connection_opened = datetime.today() user_exp.save() log.debug("Connection opened after setting is: " + str(user_exp.connection_opened)) user_experience = user_experience.exclude(user=user_exp.user) user_experience = user_experience.exclude(connection_opened__isnull=True) for user_exp in user_experience: user_exp.connection_closed = datetime.today() user_exp.save() log.debug("Connection closed was set to: " + str(user_exp.connection_closed))
def process_user_connections(app_node): from opus.lib import log log = log.get_logger('vdi') user_experience = UserExperience.objects.exclude( connection_closed__isnull=False) for user_exp in user_experience: for session in app_node.sessions: if user_exp.user.username.split('++')[1].split( '@')[0] == session['username']: if user_exp.connection_opened == None: log.debug("Setting the connection_opened parameter") user_exp.connection_opened = datetime.today() user_exp.save() log.debug("Connection opened after setting is: " + str(user_exp.connection_opened)) user_experience = user_experience.exclude(user=user_exp.user) user_experience = user_experience.exclude(connection_opened__isnull=True) for user_exp in user_experience: user_exp.connection_closed = datetime.today() user_exp.save() log.debug("Connection closed was set to: " + str(user_exp.connection_closed))
def test_get_application_service_times(self): self.failUnlessEqual( user_experience_tools.get_application_service_times(self.app1), [2700, 6300]) log.debug("***TEST*** Service Times: " + str( user_experience_tools.get_application_service_times(self.app1)))
def test_get_user_application_arrival_times(self): self.failUnlessEqual(self.ue1.access_date.ctime(), user_experience_tools.get_user_application_arrival_times(self.app1)[0].ctime()) log.debug(user_experience_tools.get_user_application_arrival_times(self.app1))
def test_get_application_service_times(self): self.failUnlessEqual(user_experience_tools.get_application_service_times(self.app1), [2700, 6300]) log.debug("***TEST*** Service Times: " + str(user_experience_tools.get_application_service_times(self.app1)))
def test_get_user_applications_on_date(self): self.failUnlessEqual(user_experience_tools.get_user_applications_in_date_range(self.user1, datetime(2010,5,14,00), datetime(2010,5,14,23,59)), [self.app1, self.app2]) log.debug("***TEST*** User Applications on Date: " + str(user_experience_tools.get_user_applications_in_date_range(self.user1, datetime(2010,5,14,00), datetime(2010,5,14,23,59))))
def connect(request, app_pk=None, conn_type=None): # Check that the user has permissions to access this app = Application.objects.filter(pk=app_pk)[0] if not request.user.has_perm('vdi.use_%s' % app.name): return HttpResponseRedirect(settings.LOGIN_URL) # Get an AppCluster instance cluster = AppCluster(app_pk) if conn_type == None: # A conn_type was not explicitly requested, so let's decide which one to have the user use if request.META["HTTP_USER_AGENT"].find('MSIE') == -1: # User is not running IE, give them the default connection type conn_type = settings.DEFAULT_CONNECTION_PROTOCOL else: # User is running IE, give them the rdpweb connection type conn_type = 'rdpweb' if request.method == 'GET': user_experience = UserExperience.objects.create(user=request.user, application=app) user_experience.access_date = datetime.today() user_experience.save() try: # Determine which host this user should use host = cluster.select_host() except NoHostException: # Start a new instance immedietly and redirect the user back to this page after 20 seconds # Only boot a new node if there are none currently booting up if len(cluster.booting) == 0: cluster.start_node() return render_to_response( 'vdi/app_not_ready.html', { 'app': cluster.app, 'reload_s': settings.USER_WAITING_PAGE_RELOAD_TIME, 'reload_ms': settings.USER_WAITING_PAGE_RELOAD_TIME * 1000 }) # Random Password Generation string chars = string.ascii_letters + string.digits password = ''.join(choice(chars) for x in range(6)) log.debug("THE PASSWORD IS: %s" % password) # Get IP of user # Implement firewall manipulation of instance log.debug('Found user ip of %s' % request.META["REMOTE_ADDR"]) # Grab the proper osutils object osutil_obj = osutils.get_os_object( host.ip, settings.OPUS_SECURE_UPLOADS + str(cluster.app.ssh_key)) if osutil_obj: status, error_string = osutil_obj.add_user(request.user.username, password) if status == False: return HttpResponse(error_string) else: return HttpResponse('Your server was not reachable') if osutil_obj.__class__.__name__ == 'Linux': conn_type = 'nx' elif osutil_obj.__class__.__name__ == 'Windows': # For windows only, ddd the created user to the Remote Desktop Users group status = osutil_obj.enable_rdp_for_user(request.user.username) if status == False: HttpResponse(error_string) else: log.debug("Added user %s to the 'Remote Desktop Users' group" % request.user.username) # This is a hack for NC WISE only, and should be handled through a more general mechanism # TODO refactor this to be more secure rdesktopPid = Popen([ "rdesktop", "-u", request.user.username, "-p", password, "-s", cluster.app.path, host.ip ], env={ "DISPLAY": ":1" }).pid # Wait for rdesktop to logon sleep(3) if conn_type == 'rdp': user_experience.file_presented = datetime.today() user_experience.save() return render_to_response('vdi/connect.html', { 'username': request.user.username, 'password': password, 'app': cluster.app, 'ip': host.ip }, context_instance=RequestContext(request)) ''' This code is commented out because it really compliments nxproxy. Originally nxproxy and vdi were developed together but nxproxy has not been touched in a while. I'm leaving this here for now because it is was hard to write, and it would be easy to refactor (probably into the nxproxy module) if anyone felt the need to do so. NOTE: There is a vestige of this code in the vdi URLconf elif conn_type == 'nxweb': return _nxweb(host.ip,user.username,password,cluster.app) elif conn_type == 'nx': # TODO -- This url should not be hard coded session_url = 'https://opus-dev.cnl.ncsu.edu:9001/nxproxy/conn_builder?' + urlencode({'dest' : host.ip, 'dest_user' : user.username, 'dest_pass' : password, 'app_path' : cluster.app.path}) return HttpResponseRedirect(session_url) ''' elif conn_type == 'rdpweb': tsweb_url = '/media/vdi/TSWeb/' user_experience.file_presented = datetime.today() user_experience.save() return render_to_response( 'vdi/rdpweb.html', { 'tsweb_url': tsweb_url, 'app': cluster.app, 'ip': host.ip, 'username': request.user.username, 'password': password }) elif conn_type == 'nx': user_experience.file_presented = datetime.today() user_experience.save() return render_to_response('vdi/connect.html', { 'username': request.user.username, 'password': password, 'app': cluster.app, 'ip': host.ip }, context_instance=RequestContext(request)) elif request.method == 'POST': # Handle POST request types if conn_type == 'rdp': return _create_rdp_conn_file(request.POST["ip"], request.user.username, request.POST["password"], cluster.app) elif conn_type == 'nx': return connection_tools.nx_conn_builder(request.POST["ip"], request.user.username, request.POST["password"], cluster.app) '''
search_string = server.bind_base authentication_string = user_dn + "," + search_string log.debug(authentication_string) ldap_session.simple_bind_s(authentication_string, password) if server.group_retrieval_string != '': result_id = ldap_session.search( search_string, ldap.SCOPE_SUBTREE, user_dn, [str(server.group_retrieval_string)]) while 1: result_type, result_data = ldap_session.result( result_id, timeout) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) #log.debug(result_set) roles = result_set[0][0][1][str(server.group_retrieval_string)] #log.debug("LDAP Roles = " + str(roles)) return roles else: return {} except ldap.LDAPError, e: log.debug("LDAP Error: " + str(e)) return None finally: log.debug("Unbinding") ldap_session.unbind()