From: Pedro, Carlos and Rezende Date: Fri, 3 Oct 2014 19:51:36 +0000 (-0300) Subject: Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into fibre X-Git-Url: http://git.onelab.eu/?p=myslice.git;a=commitdiff_plain;h=6a3f5d4949171451d5df2df5d0f96e9eb396f29c Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into fibre Conflicts: manifoldapi/manifoldproxy.py manifoldapi/static/js/manifold.js myslice/urls.py portal/actions.py portal/emailactivationview.py portal/homeview.py portal/managementtabrequests.py portal/registrationview.py portal/sliceresourceview.py portal/templates/email_activation.html portal/templates/management-tab-requests.html portal/templates/registration_view.html portal/templates/slice-resource-view.html --- 6a3f5d4949171451d5df2df5d0f96e9eb396f29c diff --cc manifoldapi/static/js/manifold.js index 30cb75e3,74fb5d9d..31d4b000 --- a/manifoldapi/static/js/manifold.js +++ b/manifoldapi/static/js/manifold.js @@@ -344,15 -344,22 +344,23 @@@ function QueryStore() default_set = (default_set === undefined) ? STATE_SET_OUT : default_set; var self = this; - var query_ext = this.find_analyzed_query_ext(query_uuid); - var record_key = manifold.metadata.get_key(query_ext.query.object); + var key, object, query_ext, record_key; + + query_ext = this.find_analyzed_query_ext(query_uuid); + object = query_ext.query.object; + if (object.indexOf(':') != -1) { + object = object.split(':')[1]; + } + record_key = manifold.metadata.get_key(object); + // ["start_time", "resource", "end_time"] + // ["urn"] + $.each(records, function(i, record) { //var key = manifold.metadata.get_key(query_ext.query.object); - // ["start_time", "resource", "end_time"] - // ["urn"] + var record_key_value = manifold.record_get_value(record, record_key); + query_ext.records.put(record_key_value, record); if (!(query_ext.state.get(record_key_value))) diff --cc myslice/urls.py index b318cb00,91511b7d..7b8dea1e --- a/myslice/urls.py +++ b/myslice/urls.py @@@ -17,9 -17,14 +17,16 @@@ import portal.dashboardvie import portal.homeview import portal.newsview +import plugins.cafe.edelberto + + from portal.about import AboutView from portal.registrationview import RegistrationView + from portal.accountview import AccountView, account_process + from portal.institution import InstitutionView + + from portal.supportview import SupportView + from portal.contactview import ContactView + from portal.termsview import TermsView home_view=portal.homeview.HomeView.as_view() diff --cc portal/actions.py index 285b4400,da5fe56f..dd1e8537 --- a/portal/actions.py +++ b/portal/actions.py @@@ -10,11 -12,10 +12,13 @@@ from django.core.mail import from myslice.theme import ThemeView +# LS Client - By Bruno Soares (UFG) +from lsapiclient import LaboraSchedulerClient + theme = ThemeView() + import activity.slice + # Thierry: moving this right into the code so # most people can use myslice without having to install sfa # XXX tmp sfa dependency, should be moved to SFA gateway @@@ -564,200 -749,96 +764,252 @@@ def sfa_create_user(wsgi_request, reque 'user_enabled' : True } - query = Query.create('user').set(sfa_user_params).select('user_hrn') - results = execute_query(wsgi_request, query) ++ ## Conflict ++ #query = Query.create('user').set(sfa_user_params).select('user_hrn') ++ #results = execute_query(wsgi_request, query) ++ + if namespace is not None: + query = Query.create('%s:user' % namespace).set(sfa_user_params).select('user_hrn') + else: + query = Query.create('user').set(sfa_user_params).select('user_hrn') + + if as_admin: + results = execute_admin_query(wsgi_request, query) + else: + results = execute_query(wsgi_request, query) if not results: raise Exception, "Could not create %s. Already exists ?" % sfa_user_params['user_hrn'] else: - try: - theme.template_name = 'user_request_validated.txt' - text_content = render_to_string(theme.template, request) - theme.template_name = 'user_request_validated.html' - html_content = render_to_string(theme.template, request) - - theme.template_name = 'email_default_sender.txt' - sender = render_to_string(theme.template, request) - sender = sender.replace('\n', '') + subject = 'User validated' + msg = 'A manager of your institution has validated your account. You have now full user access to the portal.' + send_mail(subject, msg, 'support@fibre.org.br',[request['email']], fail_silently=False) + return results +def ls_create_user(wsgi_request, request, user_detail): + organization = request['username'].split('@')[1] + lsClient = LaboraSchedulerClient( organization ) - subject = 'User validated' + orgGIDNumber = lsClient.get_testbed_info()['gidnumber'] + userHomeDirectory = "/home/" + organization + "/" + request['username'].split('@')[0] + userHomeDirectory = userHomeDirectory.encode('utf-8') + + userData = { + 'username' : request['username'], + 'email' : request['email'].encode('utf-8'), + 'password' : request['password'].encode('utf-8'), + 'name' : str( request['first_name'].encode('latin1') ) + ' ' + str( request['last_name'].encode('latin1') ), + 'gidnumber' : orgGIDNumber, + 'homedirectory' : userHomeDirectory, + 'created_by' : "myslice" + } + + # Add user in the island. + addUser = lsClient.add_user( userData ) + + # User successfully created, upload user public key. + if addUser: + ls_update_public_key( wsgi_request, request, lsClient, addUser ) + + return addUser - msg = EmailMultiAlternatives(subject, text_content, sender, [request['email']]) - msg.attach_alternative(html_content, "text/html") - msg.send() - except Exception, e: - print "Failed to send email, please check the mail templates and the SMTP configuration of your server" +def ls_validate_user(wsgi_request, request): + organization = request['username'].split('@')[1] + lsClient = LaboraSchedulerClient( organization ) + + userId = lsClient.get_user_id_by_username( { 'username': str( request['username'] ) } ) + + validate = False + if userId: + userData = { + 'user_id' : userId, + 'new_user_data' : { 'enable': 'TRUE' } + } + + validate = lsClient.update_user( userData ) + + return validate and addUserPublicKey - return results +def ls_update_public_key( wsgi_request, request, lsClient, userId ): + userPbKey = { + 'user_id' : userId, + 'public_key' : request['public_key'] + } + + addUserPublicKey = lsClient.add_user_public_key( userPbKey ) + + return addUserPublicKey - def create_user(wsgi_request, request): + def iotlab_create_user (wsgi_request, request, namespace = None, as_admin=False): + + import requests + import time + from requests.auth import HTTPBasicAuth + URL_REST = 'https://devgrenoble.senslab.info/rest/admin/users' + LOGIN_ADMIN = "auge" + PASSWORD_ADMIN = "k,mfg1+Q" + + auth = HTTPBasicAuth(LOGIN_ADMIN,PASSWORD_ADMIN) + headers = {'content-type': 'application/json'} + + for user in PendingUser.objects.raw('SELECT * FROM portal_pendinguser WHERE email = %s', [request['email']]): + password= user.password + + + iotlab_user_params = { + "type" : "SA", + "login" : request['email'], + "password" : password, + "firstName" : request['first_name'], + "lastName" : request['last_name'], + "email" : request['email'], + "structure" : request['authority_hrn'], + "city" : "N/A", + "country" : "N/A", + "sshPublicKey" : [request['public_key']], + "motivations" : "SFA federation", + } + + iotlab_user_params1 = json.dumps(iotlab_user_params) + r=requests.post(url=URL_REST, data=iotlab_user_params1, headers=headers, auth=auth) + print 'Create iotlab user : ', r.status_code, r.text + return r.text + + def create_user(wsgi_request, request, namespace = None, as_admin = False): # XXX This has to be stored centrally USER_STATUS_ENABLED = 2 # NOTE : if we were to create a user directly (just like we create slices, # we would have to perform the steps in create_pending_user too + + # Edelberto - I put this more below + # Add the user to the SFA registry + #sfa_create_user(wsgi_request, request) + # Update Manifold user status + manifold_update_user(wsgi_request, request['username'], {'status': USER_STATUS_ENABLED}) + + # Add reference accounts for platforms + manifold_add_reference_user_accounts(wsgi_request, request) + ++ # Conflict ++ # sfa_create_user(wsgi_request, request) # Add the user to the SFA registry - sfa_create_user(wsgi_request, request) + sfa_create_user(wsgi_request, request, namespace, as_admin) + + # Validate the user using the LS API ( By Bruno - UFG ): + try: + ls_validate_user( wsgi_request, request ) + except Exception, e: + "Error to validate the user in Labora Scheduler." + +def create_user_in_ldap(wsgi_request, request, user_detail): + """ + """ + + # saves the user to django auth_user table [needed for password reset] + user = User.objects.create_user(request['username'], request['email'], request['password']) + + # Creating a manifold user + user_id = manifold_add_user(wsgi_request, request) + + # Creating a Manifold account on the MySlice platform + # Note the JSON representation of public and private keys already includes quotes + account_config = { + 'user_hrn' : request['user_hrn'], + 'user_public_key' : request['public_key'], + } + if request['private_key']: + account_config['user_private_key'] = request['private_key'] + + user_id = user_detail['user_id'] + 1 # the user_id for the newly created user in local:user + + # XXX TODO: Require a myslice platform + # ALERT: this will disapear with ROUTERV2 of Manifold + # We have to consider the case where several registries can be used + # Removed hardcoded platform = 5 + # This platform == 'myslice' is a TMP FIX !! + try: + reg_platform_query = Query().get('local:platform') \ + .filter_by('platform', '==', 'myslice') \ + .select('platform_id') + reg_platform = execute_admin_query(wsgi_request, reg_platform_query) + reg_platform_id = reg_platform[0]['platform_id'] + account_params = { + 'platform_id' : reg_platform_id, # XXX ALERT !! + 'user_id' : user_id, + 'auth_type' : request['auth_type'], + 'config' : json.dumps(account_config), + } + manifold_add_account(wsgi_request, account_params) + except Exception, e: + print "Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email']) + + # XXX This has to be stored centrally + USER_STATUS_ENABLED = 2 # Update Manifold user status - manifold_update_user(wsgi_request, request['email'], {'status': USER_STATUS_ENABLED}) + manifold_update_user(wsgi_request, request['username'], {'status': USER_STATUS_ENABLED}) # Add reference accounts for platforms manifold_add_reference_user_accounts(wsgi_request, request) + + organization = request['username'].split('@')[1] + lsClient = LaboraSchedulerClient( organization ) + + userId = lsClient.get_user_id_by_username( { 'username': str( request['username'] ) } ) + + ls_up_pkey = ls_update_public_key( wsgi_request, request, lsClient, userId ) + + if ls_up_pkey: + print "OK PKEY" + + from sfa.util.xrn import Xrn + + auth_pi = request.get('pi', None) + auth_pi = list([auth_pi]) if auth_pi else list() + + # We create a user request with Manifold terminology + sfa_user_params = { + 'user_hrn' : request['user_hrn'], + 'user_email' : request['email'], + 'user_urn' : Xrn(request['user_hrn'], request['type']).get_urn(), + 'user_type' : request['type'], + 'keys' : request['public_key'], + 'user_first_name' : request['first_name'], + 'user_last_name' : request['last_name'], + 'pi_authorities' : auth_pi, + 'user_enabled' : True + } + + print request['user_hrn'] + print request['email'] + print request['first_name'] + print request['last_name'] + print request['type'] + print request['public_key'] + + query = Query.create('user').set(sfa_user_params).select('user_hrn') + + print query + + results = execute_admin_query(wsgi_request, query) + + print results + + if not results: + raise Exception, "Could not create %s. Already exists ?" % sfa_user_params['user_hrn'] + else: + subject = 'User validated' + msg = 'A manager of your institution has validated your account. You have now full user access to the portal.' + send_mail(subject, msg, 'support@fibre.org.br',[request['email']], fail_silently=False) + return results + # Add the user to iotlab portal if theme is set to onelab + if theme.theme == 'onelab': + iotlab_create_user (wsgi_request, request) + def create_pending_user(wsgi_request, request, user_detail): """ """ diff --cc portal/emailactivationview.py index e1a6a4be,533cccfa..3dc388be --- a/portal/emailactivationview.py +++ b/portal/emailactivationview.py @@@ -2,7 -2,7 +2,7 @@@ from unfold.loginrequire # from manifold.core.query import Query from manifoldapi.manifoldapi import execute_query, execute_admin_query - from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, authority_get_pi_emails, authority_get_pis -from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, authority_get_pi_emails, make_request_user, create_user ++from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, authority_get_pi_emails, make_request_user, create_user, authority_get_pis # from unfold.page import Page from ui.topmenu import topmenu_items_live, the_user @@@ -11,10 -11,10 +11,10 @@@ from django.htt from django.contrib import messages from django.contrib.auth.decorators import login_required from myslice.theme import ThemeView - from portal.models import PendingUser + from portal.models import PendingUser, PendingAuthority from django.core.mail import EmailMultiAlternatives, send_mail from django.contrib.sites.models import Site - +from django.contrib.auth.models import User # import json, os, re, itertools @@@ -35,60 -50,58 +50,97 @@@ class ActivateEmailView(FreeAccessView #print "%s = %s" % (key, value) if key == "hash_code": hash_code=value - - if PendingUser.objects.filter(email_hash__iexact = hash_code): - #get_user = PendingUser.objects.filter(email_hash__iexact = hash_code) - #get_user.status= 'True' - #get_user.save() - #for user in PendingUser.objects.all(): - # first_name = user.first_name - # last_name = user.last_name - # authority_hrn = user.authority_hrn - # public_key = user.public_key - # email = user.email - # user_hrn = user.user_hrn - PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True') + if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'): activation = 'success' + # sending email after activation success + try: + request = PendingUser.objects.filter(email_hash= hash_code) - split_authority_hrn = request[0].authority_hrn.split('.')[0] - pis = authority_get_pis(request, split_authority_hrn) - pi_emails = [] - for x in pis: - for e in x['pi_users']: - u = e.split('.')[1] - y = User.Objects.get(username = u) - if y.username.count("@") != 0: - if y.username.split("@")[1] == request[0].user_hrn.split("@")[1]: - pi_emails += [y.email] - subject = 'User email activated' - msg = 'The user %s has validated his/her email. Now you can validate his/her account' % (request[0].login) - send_mail(subject, msg, 'support@fibre.org.br', pi_emails, fail_silently = False) - except: - print "error sending the email!" - #try: - # Send an email: the recipients are the PI of the authority - # If No PI is defined for this Authority, send to a default email (different for each theme) - # recipients = authority_get_pi_emails(wsgi_request, authority_hrn) - # theme.template_name = 'user_request_email.html' - # html_content = render_to_string(theme.template, request) - # theme.template_name = 'user_request_email.txt' - # text_content = render_to_string(theme.template, request) - # theme.template_name = 'user_request_email_subject.txt' - # subject = render_to_string(theme.template, request) - # subject = subject.replace('\n', '') - # theme.template_name = 'email_default_sender.txt' - # sender = render_to_string(theme.template, request) - # sender = sender.replace('\n', '') - # msg = EmailMultiAlternatives(subject, text_content, sender, recipients) - # msg.attach_alternative(html_content, "text/html") - # msg.send() - # except Exception, e: - # print "Failed to send email, please check the mail templates and the SMTP configuration of your server" - # import traceback - # traceback.print_exc() ++ split_authority_hrn = request[0].authority_hrn.split('.')[0] ++ pis = authority_get_pis(request, split_authority_hrn) ++ pi_emails = [] ++ for x in pis: ++ for e in x['pi_users']: ++ u = e.split('.')[1] ++ y = User.Objects.get(username = u) ++ if y.username.count("@") != 0: ++ if y.username.split("@")[1] == request[0].user_hrn.split("@")[1]: ++ pi_emails += [y.email] ++ subject = 'User email activated' ++ msg = 'The user %s has validated his/her email. Now you can validate his/her account' % (request[0].login) ++ send_mail(subject, msg, 'support@fibre.org.br', pi_emails, fail_silently = False) ++ except: ++ print "error sending the email!" ++ #try: ++ # Send an email: the recipients are the PI of the authority ++ # If No PI is defined for this Authority, send to a default email (different for each theme) ++ # recipients = authority_get_pi_emails(wsgi_request, authority_hrn) ++ # theme.template_name = 'user_request_email.html' ++ # html_content = render_to_string(theme.template, request) ++ # theme.template_name = 'user_request_email.txt' ++ # text_content = render_to_string(theme.template, request) ++ # theme.template_name = 'user_request_email_subject.txt' ++ # subject = render_to_string(theme.template, request) ++ # subject = subject.replace('\n', '') ++ # theme.template_name = 'email_default_sender.txt' ++ # sender = render_to_string(theme.template, request) ++ # sender = sender.replace('\n', '') ++ # msg = EmailMultiAlternatives(subject, text_content, sender, recipients) ++ # msg.attach_alternative(html_content, "text/html") ++ # msg.send() ++ # except Exception, e: ++ # print "Failed to send email, please check the mail templates and the SMTP configuration of your server" ++ # import traceback ++ # traceback.print_exc() + + # AUTO VALIDATION of PLE enabled users (only for OneLab Portal) + if self.theme == "onelab": + # Auto-Validation of pending user, which is enabled in a trusted SFA Registry (example: PLE) + # We could check in the Registry based on email, but it takes too long + # as we currently need to do a Resolve on each user_hrn of the Registry in order to get its email + # TODO in SFA XXX We need a Resolve based on email + # TODO maybe we can use MyPLC API for PLE + pending_users = PendingUser.objects.filter(email_hash__iexact = hash_code) + # by default user is not in PLE + ple_user_enabled = False + + if pending_users: + pending_user = pending_users[0] + + # Auto Validation + if self.is_ple_enabled(pending_user): + pending_user_request = make_request_user(pending_user) + # Create user in SFA and Update in Manifold + create_user(self.request, pending_user_request, namespace = 'myslice', as_admin = True) + # Delete pending user + PendingUser.objects.filter(email_hash__iexact = hash_code).delete() + + # template user auto validated + activation = 'validated' + + # sending email after activation success + #try: + # # Send an email: the recipient is the user + # recipients = pending_user_eamil + # theme.template_name = 'user_request_email.html' + # html_content = render_to_string(theme.template, request) + # theme.template_name = 'user_request_email.txt' + # text_content = render_to_string(theme.template, request) + # theme.template_name = 'user_request_email_subject.txt' + # subject = render_to_string(theme.template, request) + # subject = subject.replace('\n', '') + # theme.template_name = 'email_default_sender.txt' + # sender = render_to_string(theme.template, request) + # sender = sender.replace('\n', '') + # msg = EmailMultiAlternatives(subject, text_content, sender, recipients) + # msg.attach_alternative(html_content, "text/html") + # msg.send() + #except Exception, e: + # print "Failed to send email, please check the mail templates and the SMTP configuration of your server" + # import traceback + # traceback.print_exc() + + PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True') else: activation = 'failed' diff --cc portal/homeview.py index 3fc0cd85,b0236525..cf3fcbab --- a/portal/homeview.py +++ b/portal/homeview.py @@@ -31,9 -19,8 +32,11 @@@ from myslice.configengine import Config from myslice.theme import ThemeView -import activity.user +# Edelberto LDAP authentication XXX +import ldap + ++#import activity.user + class HomeView (FreeAccessView, ThemeView): template_name = 'home-view.html' @@@ -48,269 -35,85 +51,271 @@@ env['theme'] = self.theme env['section'] = "Dashboard" - username = request.POST.get('username') + username = request.POST.get('username').lower() password = request.POST.get('password') - - # pass request within the token, so manifold session key can be attached to the request session. - token = {'username': username, 'password': password, 'request': request} - - # our authenticate function returns either - # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable - # . a django User in case of success - # . or None if the backend could be reached but the authentication failed - auth_result = authenticate(token=token) - # use one or two columns for the layout - not logged in users will see the login prompt - # high-level errors, like connection refused or the like - if isinstance (auth_result, ManifoldResult): - manifoldresult = auth_result - # let's use ManifoldResult.__repr__ - env['state']="%s"%manifoldresult - - return render_to_response(self.template,env, context_instance=RequestContext(request)) - # user was authenticated at the backend - elif auth_result is not None: - user=auth_result - if user.is_active: - print "LOGGING IN" - login(request, user) - - if request.user.is_authenticated(): - env['person'] = self.request.user - env['username'] = self.request.user - - # log user activity - activity.user.login(self.request) - - ## check user is pi or not - platform_details = {} - account_details = {} - acc_auth_cred = {} - acc_user_cred = {} - platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled') - account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config') - platform_details = execute_query(self.request, platform_query) - account_details = execute_query(self.request, account_query) - for platform_detail in platform_details: - for account_detail in account_details: - if platform_detail['platform_id'] == account_detail['platform_id']: - if 'config' in account_detail and account_detail['config'] is not '': - account_config = json.loads(account_detail['config']) - if 'myslice' in platform_detail['platform']: - acc_auth_cred = account_config.get('delegated_authority_credentials','N/A') - acc_user_cred = account_config.get('delegated_user_credential','N/A') - # assigning values - if acc_auth_cred=={} or acc_auth_cred=='N/A': - pi = "is_not_pi" - else: - pi = "is_pi" - - # check if the user has creds or not - if acc_user_cred == {} or acc_user_cred == 'N/A': - user_cred = 'no_creds' - else: - user_cred = 'has_creds' - - - env['pi'] = pi - env['user_cred'] = user_cred - else: - env['person'] = None - return render_to_response(self.template,env, context_instance=RequestContext(request)) - else: - # log user activity - activity.user.login(self.request, "notactive") - env['state'] = "Your account is not active, please contact the site admin." - env['layout_1_or_2']="layout-unfold2.html" - - return render_to_response(self.template,env, context_instance=RequestContext(request)) - # otherwise + + # LDAP form - If FIBRE, then get the possibilite to authenticate using usernameldap + #if self.theme == 'fibre': + #usernameldap = request.POST.get('usernameldap') + #token = {'usernameldap': usernameldap, 'username': username ,'password': password, 'request': request} + + ################################################## + ########## XXX Edelberto 010914 XXX + ################################################# + ## first you must open a connection to the server + try: + # Connect to NOC + l = ldap.initialize("ldap://10.128.0.50:389") + # Bind/authenticate with a root user to search all objects + l.simple_bind_s("cn=Manager,dc=br,dc=fibre","fibre2013") + + l.protocol_version = ldap.VERSION3 + except ldap.LDAPError, e: + print e + + ## Base directory + baseDN = "dc=fibre" + searchScope = ldap.SCOPE_SUBTREE + ## retrieve all attributes + retrieveAttributes = None + #retrieveAttributes = ['userEnable'] + searchFilter = "uid=" + username + print searchFilter + + in_ldap = 0 + + try: + if username != "admin": + ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes) + result_set = [] + result_type, result_data = l.result(ldap_result_id, 0) + if (result_data == []): + print "User doesnt exist in LDAP" + in_ldap = 0 + else: + if result_type == ldap.RES_SEARCH_ENTRY: + result_set.append(result_data) + else: + result_set.append(result_data) + # TRUE or FALSE for userEnable attribute + userEnable = result_set[0][0][1]['userEnable'][0] + if userEnable == 'TRUE': + in_ldap = 1 + enabled = 1 + print "In LDAP and Enabled" + + dn = result_set[0][0][0] + try: + l.simple_bind_s(dn,password) + pwd = 1 + print "User password OK" + + except: + pwd = 0 + print "User password WRONG" + + if in_ldap and enabled and pwd: + ldap_mail = result_set[0][0][1]['mail'][0] + + user_exists = Query().get('local:user') \ + .select('status') \ + .filter_by('email', '==', username) + results = execute_admin_query(request, user_exists) + print "DEBUG: %s" % user_exists + if results: + print "DEBUG: user exists on MySlice DBs" + else: + print "DEBUG: user NOT exists on MySlice DBs" + + cn = result_set[0][0][1]['cn'][0] + sn = result_set[0][0][1]['sn'][0] + + fname=None + lname=None + + try: + fname = sn.split(' ')[0] + lname = sn.split(' ')[1] + except: + fname = sn + lname = "" + + #authority_hrn = 'fibre' + '.' + username.split('@')[1] + authority_hrn = 'fibre' + print authority_hrn + email = ldap_mail + print ldap_mail + username = username + print username + password = password + print password + # user_hrn = 'fibre' + '.' + username.split('@')[1] + '.' + username + user_hrn = 'fibre' + '.' + username + print user_hrn + + # Based on registrationview + + + # get the domain url + current_site = Site.objects.get_current() + current_site = current_site.domain + print current_site + + post_email = ldap_mail + salt = randint(1,100000) + email_hash = md5(str(salt)+post_email).hexdigest() + print email_hash + + user_request = { + 'first_name' : fname, + 'last_name' : lname, + 'organization' : authority_hrn, + 'authority_hrn' : authority_hrn, + 'email' : ldap_mail, + 'username' : username, + 'password' : password, + 'current_site' : current_site, + 'email_hash' : email_hash, + 'pi' : '', + 'user_hrn' : user_hrn, + 'reasons' : 'already exists in the LDAP', + 'type' : 'user', + 'validation_link': 'https://' + current_site + '/portal/email_activation/'+ email_hash + } + + # Validate input + errors = [] + UserModel = get_user_model() + if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None): + errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.') + if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None): + errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.') + if (re.search(r'^[\w,]+$' , username) == None): + errors.append('Username may contain only letters,numbers and -/_ characters.') + # checking in django_db !! + if PendingUser.objects.filter(email__iexact = user_request['email']): + errors.append('Email is pending for validation. Please provide a new email address.') + if User.objects.filter(username__iexact = user_request['username']): + errors.append('This username is already in use, try another one') + # Does the user exist in Manifold? + user_query = Query().get('local:user').select('user_id','email') + user_details = execute_admin_query(request, user_query) + for user_detail in user_details: + if user_detail['email'] == user_request['email']: + errors.append('Email already registered in Manifold. Please provide a new email address.') + # Does the user exist in sfa? [query is very slow!!] + #user_query = Query().get('user').select('user_hrn','user_email') + # XXX Test based on the user_hrn is quick + #user_query = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn']) + user_query = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_hrn) + user_details_sfa = execute_admin_query(request, user_query) + + #if 'generate' in wsgi_request.POST['question']: + user_request['auth_type'] = 'managed' + + # XXX Common code, dependency ? + from Crypto.PublicKey import RSA + private = RSA.generate(1024) + + # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...' + # Example: public_key = 'ssh-rsa AAAAB3...' + user_request['private_key'] = private.exportKey() + user_request['public_key'] = private.publickey().exportKey(format='OpenSSH') + + # XXX Verify if errors exist - After! + #if not errors: + create_user_in_ldap(request, user_request, user_detail) + #create_pending_user(request, user_request, user_detail) + + #create_user(request, user_request) + + env['state'] = "LDAP associated. Please, login again." + return render_to_response(self.template, env, context_instance=RequestContext(request)) + + + else: + env['state'] = "Access denied. Verify LDAP userEnable and password." + return render_to_response(self.template, env, context_instance=RequestContext(request)) + + else: + in_ldap = 1 + enabled = 0 + print "In LDAP but Disabled" + env['state'] = "Access denied. Verify LDAP userEnable." + return render_to_response(self.template, env, context_instance=RequestContext(request)) + + #print result_set + except ldap.LDAPError, e: + print e + + #else: + if in_ldap and enabled and pwd or username=="admin": + +################################################################################ +### XXX Edelberto LDAP auth end XXX +############################################################################### + # Follow original code + ## pass request within the token, so manifold session key can be attached to the request session. + token = {'username': username, 'password': password, 'request': request} + + # our authenticate function returns either + # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable + # . a django User in case of success + # . or None if the backend could be reached but the authentication failed + auth_result = authenticate(token=token) + # use one or two columns for the layout - not logged in users will see the login prompt + # high-level errors, like connection refused or the like + if isinstance (auth_result, ManifoldResult): + manifoldresult = auth_result + # let's use ManifoldResult.__repr__ + env['state']="%s"%manifoldresult + + return render_to_response(self.template,env, context_instance=RequestContext(request)) + # user was authenticated at the backend + elif auth_result is not None: + user=auth_result + if user.is_active: + print "LOGGING IN" + login(request, user) + + if request.user.is_authenticated(): + env['person'] = self.request.user + env['username'] = self.request.user + + ## check user is pi or not + platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled') + account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config') + + # Edleberto + #cc_auth_cred = {} + + platform_details = execute_query(self.request, platform_query) + account_details = execute_query(self.request, account_query) + for platform_detail in platform_details: + for account_detail in account_details: + if platform_detail['platform_id'] == account_detail['platform_id']: + if 'config' in account_detail and account_detail['config'] is not '': + account_config = json.loads(account_detail['config']) + if 'myslice' in platform_detail['platform']: + acc_auth_cred = account_config.get('delegated_authority_credentials','N/A') + # assigning values + if acc_auth_cred=={} or acc_auth_cred=='N/A': + pi = "is_not_pi" + else: + pi = "is_pi" + env['pi'] = pi + else: + env['person'] = None + return render_to_response(self.template,env, context_instance=RequestContext(request)) + else: + env['state'] = "Your account is not active, please contact the site admin." + env['layout_1_or_2']="layout-unfold2.html" + + return render_to_response(self.template,env, context_instance=RequestContext(request)) + # otherwise else: + # log user activity - activity.user.login(self.request, "error") ++ #activity.user.login(self.request, "error") env['state'] = "Your username and/or password were incorrect." return render_to_response(self.template, env, context_instance=RequestContext(request)) diff --cc portal/managementtabrequests.py index 0f490e94,31cbb0d7..66f9991f --- a/portal/managementtabrequests.py +++ b/portal/managementtabrequests.py @@@ -164,24 -156,10 +164,24 @@@ class ManagementRequestsView (LoginRequ # env['pi'] = "is_pi" # env['theme'] = self.theme # env['section'] = "Requests" - +# auth_hrn = user_authority + '.' + user_username.split("@")[1] + ctx_list = [ctx_my_authorities, ctx_sub_authorities, ctx_delegation_authorities] + for ctx in ctx_list: + if ctx: + for authorities in ctx: + for requests in ctx[authorities]: + try: + requests['object_auth'] = requests['user_hrn'].split('.')[0] + '.' + requests['user_hrn'].split('@')[1] + except: + print "This object has no user_hrn" + + pi_authority = user_authority + '.' + user_username.split("@")[1] context = super(ManagementRequestsView, self).get_context_data(**kwargs) - print "testing" - print ctx_my_authorities - print auth_hrn - print user_username - print pi_authority - - ++ #print "testing" ++ #print ctx_my_authorities ++ #print auth_hrn ++ #print user_username ++ #print pi_authority context['my_authorities'] = ctx_my_authorities context['sub_authorities'] = ctx_sub_authorities context['delegation_authorities'] = ctx_delegation_authorities diff --cc portal/registrationview.py index 25a050a8,e55e30fd..c52689f6 --- a/portal/registrationview.py +++ b/portal/registrationview.py @@@ -58,10 -60,9 +62,9 @@@ class RegistrationView (FreeAccessView # get the domain url current_site = Site.objects.get_current() current_site = current_site.domain - + - #authorities_query = Query.get('authority').select('name', 'authority_hrn') - #authorities = execute_admin_query(wsgi_request, authorities_query) - + print "############ BREAKPOINT 3 #################" - ++ for authority in authorities: if authority['name'] == wsgi_request.POST.get('org_name', ''): authority_hrn = authority['authority_hrn'] @@@ -86,27 -87,19 +91,29 @@@ 'current_site' : current_site, 'email_hash' : email_hash, 'pi' : '', - 'validation_link': 'http://' + current_site + '/portal/email_activation/'+ email_hash + 'validation_link': 'https://' + current_site + '/portal/email_activation/'+ email_hash } - + + print "############ BREAKPOINT 5 #################" + # Construct user_hrn from email (XXX Should use common code) - split_email = user_request['email'].split("@")[0] - split_email = split_email.replace(".", "_") - # Replace + by _ => more convenient for testing and validate with a real email - split_email = split_email.replace("+", "_") - user_request['user_hrn'] = user_request['authority_hrn'] \ - + '.' + split_email + # split_email = user_request['email'].split("@")[0] + # split_email = split_email.replace(".", "_") + # user_request['user_hrn'] = user_request['authority_hrn'] \ + # + '.' + split_email + username = user_request['username'] + + if user_request['authority_hrn'] == "fibre" : + user_request['username'] = user_request['username'] + "@" + "rnp" # catch-all island + split_authority = user_request['authority_hrn'] + else : + split_authority = user_request['authority_hrn'].split(".")[1] + user_request['username'] = user_request['username'] + '@' + split_authority + split_authority = user_request['authority_hrn'].split(".")[0] + + user_request['user_hrn'] = split_authority + '.' + user_request['username'] + # Validate input UserModel = get_user_model() if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None): @@@ -134,14 -119,26 +142,26 @@@ user_query = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn']) user_details_sfa = execute_admin_query(wsgi_request, user_query) - for user in user_details_sfa: - if user['user_email'] == user_request['email']: - errors.append('Email already registered in OneLab registry. Contact OneLab support or use another email.') - if user['user_hrn'] == user_request['user_hrn']: - # add random number if user_hrn already exists in the registry - user_request['user_hrn'] = user_request['authority_hrn'] \ - + '.' + split_email + str(randint(1,1000000)) - + # for user in user_details_sfa: + # if user['user_email'] == user_request['email']: + # errors.append('Email already registered in SFA registry. Please use another email.') + # if user['user_hrn'] == user_request['user_hrn']: + # # add random number if user_hrn already exists in the registry + # user_request['user_hrn'] = user_request['authority_hrn'] \ + # + '.' + split_email + str(randint(1,1000000)) + + # checking in django unfold db portal application pending users + # sqlite3 /var/unfold/unfold.sqlite3 + # select email from portal_pendinguser; + if PendingUser.objects.filter(email__iexact = user_request['email']): + errors.append('Account pending for validation. Please wait till your account is validated or contact OneLab support.') + + # checking in django_db !! + # sqlite3 /var/unfold/unfold.sqlite3 + # select email from auth_user; + if UserModel._default_manager.filter(email__iexact = user_request['email']): - errors.append('Contact OneLab support or try with another email.') ++ errors.append('Please try with another email.') + # XXX TODO: Factorize with portal/accountview.py # XXX TODO: Factorize with portal/registrationview.py # XXX TODO: Factorize with portal/joinview.py @@@ -176,10 -173,12 +196,13 @@@ if not errors: create_pending_user(wsgi_request, user_request, user_detail) self.template_name = 'user_register_complete.html' - + # log user activity - activity.user.registered(self.request) - return render(wsgi_request, self.template, {'theme': self.theme}) ++ #activity.user.registered(self.request) ++ + return render(wsgi_request, self.template, {'theme': self.theme, 'REQINST':wsgi_request.POST.get('org_name', '').split(".")[1].upper()}) else: + print "############ BREAKPOINT A #################" user_request = {} ## this is coming from onelab website onelab.eu reg_form = { diff --cc portal/slicerequestview.py index c4c00db1,e6683bd4..97a11dd0 --- a/portal/slicerequestview.py +++ b/portal/slicerequestview.py @@@ -173,10 -178,10 +178,10 @@@ class SliceRequestView (LoginRequiredAu 'purpose': purpose, 'email': user_email, 'user_hrn': user_hrn, - 'exp_url': exp_url, + 'url': url, 'pi': pi, 'authority_name': authority_name, - 'authority_hrn': user_authority, + 'authority_hrn': user_authority, 'cc_myself': True, 'authorities': authorities, 'theme': self.theme, diff --cc portal/sliceresourceview.py index e5614b04,eaf7931c..fd66ffb3 --- a/portal/sliceresourceview.py +++ b/portal/sliceresourceview.py @@@ -24,10 -24,14 +24,13 @@@ from plugins.testbed from plugins.scheduler2 import Scheduler2 # Bristol plugin - from plugins.univbrisfoam import UnivbrisFoam - from plugins.univbrisfv import UnivbrisFv - from plugins.univbrisfvf import UnivbrisFvf + from plugins.univbris import Univbris + from plugins.univbrisfoam import UnivbrisFoam + from plugins.univbrisfv import UnivbrisFv + from plugins.univbrisfvf import UnivbrisFvf + from plugins.univbrisfvfo import UnivbrisFvfo + from plugins.univbristopo import UnivbrisTopo - from plugins.columns_editor import ColumnsEditor from plugins.sladialog import SlaDialog from plugins.lists.simplelist import SimpleList @@@ -245,52 -256,87 +260,131 @@@ class SliceResourceView (LoginRequiredV query = main_query, username = request.user, ) + + # Bristol plugin + univbrisfoamlist = UnivbrisFoam( + page = page, + title = 'univbris_foam_ports_selection', + domid = 'univbris_foam_ports_selection', + query = univbrisfoam_query, + query_all = univbrisfoam_query, + checkboxes = False, + datatables_options = { + 'iDisplayLength': 10, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + #plugin which manages the different flowspaces that the user creates, and also sends flowspaces to manifold + univbrisfvlist = UnivbrisFv( + page = page, + title = 'univbris_flowspace_selection', + domid = 'univbris_flowspace_selection', + query = None, + query_all = None, + datatables_options = { + 'iDisplayLength': 5, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + #plugin which allows the definition of a single flowspace + univbrisfvform = UnivbrisFvf( + page = page, + title = 'univbris_flowspace_form', + domid = 'univbris_flowspace_form', + query = None, + query_all = None, + datatables_options = { + 'iDisplayLength': 3, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + # -------------------------------------------------------------------------- + # Ofelia OpenFlow Plugin + # Bristol plugin + + # plugin which display a "gathering resources" message + # waiting for all resources to be returned by manifold + univbriswelcome = Univbris( + page = page, + title = 'univbris_welcome', + domid = 'univbris_welcome', + query = query_resource_all, + ) + univbrisfoamlist = UnivbrisFoam( + page = page, + title = 'univbris_foam_ports_selection', + domid = 'univbris_foam_ports_selection', + query = query_resource_all, + query_all = query_resource_all, + checkboxes = False, + datatables_options = { + 'iDisplayLength': 10, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + #plugin which manages the different flowspaces that the user creates, and also sends flowspaces to manifold + univbrisfvlist = UnivbrisFv( + page = page, + title = 'univbris_flowspace_selection', + domid = 'univbris_flowspace_selection', + query = None, + query_all = None, + sync_query = query_resource_all, + datatables_options = { + 'iDisplayLength': 5, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + #plugin which allows the definition of a single flowspace + univbrisfvform = UnivbrisFvf( + page = page, + title = 'univbris_flowspace_form', + domid = 'univbris_flowspace_form', + query = query_resource_all, + query_all = None, + datatables_options = { + 'iDisplayLength': 3, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + #plugin which allows the definition the match criteria on a single OPTICAL flowspace + + univbrisofvform = UnivbrisFvfo( + page = page, + title = 'univbris_oflowspace_form', + domid = 'univbris_oflowspace_form', + query = None, + query_all = None, + datatables_options = { + 'iDisplayLength': 3, + 'bLengthChange' : True, + 'bAutoWidth' : True, + }, + ) + + #plugin which display the gathered topology + univbristopology = UnivbrisTopo( + page = page, + title = 'univbris_topology', + domid = 'univbris_topology', + query = query_resource_all, + #query = query_resource_all, + ) + # -------------------------------------------------------------------------- # SLA View and accept dialog @@@ -341,10 -387,13 +435,13 @@@ template_env['scheduler'] = resources_as_scheduler2.render(self.request) # Bristol plugin + template_env['welcome'] = univbriswelcome.render(self.request) template_env['resources'] = univbrisfoamlist.render(self.request) - template_env['flowspaces']= univbrisfvlist.render(self.request) - template_env['flowspaces_form']= univbrisfvform.render(self.request) + template_env['flowspaces'] = univbrisfvlist.render(self.request) + template_env['oflowspaces_form'] = univbrisofvform.render(self.request) + template_env['flowspaces_form'] = univbrisfvform.render(self.request) + template_env['topology'] = univbristopology.render(self.request) - + # template_env['pending_resources'] = pending_resources.render(self.request) template_env['sla_dialog'] = '' # sla_dialog.render(self.request) template_env["theme"] = self.theme diff --cc portal/templates/base.html index aa3062dd,0f2ecb52..a7dc6fd3 --- a/portal/templates/base.html +++ b/portal/templates/base.html @@@ -86,9 -86,8 +86,8 @@@ $(document).ready(function() {% block container %} {% block topmenu %} - {% widget "_widget-topmenu.html" %} + {% widget "__widget-topmenu.html" %} {% endblock topmenu %} - {% include 'messages-transient.html' %} {% block base_content %} {% endblock %} {% endblock container %} diff --cc portal/templates/email_activation.html index 0ad87694,ce763ba3..49fdbff1 --- a/portal/templates/email_activation.html +++ b/portal/templates/email_activation.html @@@ -6,9 -6,14 +6,13 @@@

User RegistrationUser sign-up

- {%if activation_status == 'success'%} -

Signup request confirmed.

+ {% if activation_status == 'success' %} +

Signup request confirmed.

-

You are currently able to log in to the portal using your email address and the password that you provided, but your access is still limited.

You will have full access as soon as your account is validated by a manager at your organization. We have sent an email to the managers with a validation request.

+ {% elif activation_status == 'validated' %} +

Account validated.

+

We have identified you as a valid PLE user. Your OneLab account has automatically been approved.

+

You have a full access to OneLab testbeds.

{%else%}

Signup confirmation failed.

You have probably arrived at this page by clicking a confirmation link in an email that we have sent to you. However, diff --cc portal/templates/management-tab-requests.html index eeb84a65,ddac594d..d22bdebb --- a/portal/templates/management-tab-requests.html +++ b/portal/templates/management-tab-requests.html @@@ -40,81 -52,110 +52,180 @@@ } ); } - }; - function showMore(buttonId, divId){ - } - function on_click_reject() { ++ }; ++ function showMore(buttonId, divId){ + var element = document.getElementById(buttonId); + var div_element = document.getElementById(divId); + if (element.value === '(+)'){ + element.value = '(-)'; + $('#'+divId).slideDown('fast'); + } + else { + element.value = '(+)'; + $('#'+divId).slideUp('fast'); + } + return false; - } ++ } ++ function on_click_reject() { + var ids = []; + $('.portal__validate__checkbox').each(function(i, el) { + if ($(el).prop('checked')) { + // portal__validate__checkbox__slice__2 + var id_array = $(el).attr('id').split('__'); + // push(slice__2) + ids.push(id_array[3] + '__' + id_array[4]); + } + }); + if (ids.length > 0) { + var id_str = ids.join('/'); + + // XXX spinner + + $.getJSON('/portal/reject_action/' + id_str, + function(status) { + $.each(status, function(request_type__id, request_status) { + // request_status: NAME -> dict (status, description) + var status_str = ''; + $.each(request_status, function(name, result) { + if (status_str != '') + status_str += ' -- '; + + if (result.status) { + status_str += 'Rejected'; + $('#portal__validate__checkbox__' + request_type__id).hide(); + } else { + status_str += 'ERROR: ' + result.description + ''; + } + }); + $('#portal__status__' + request_type__id).html(status_str); + + + }); + } + ); + } + } +

-

Authorities

+

From your authorities

{% if my_authorities %} - +
+ + + + + + + + + + + + + {% for authority, requests in my_authorities.items %} + {% if authority == pi_authority or authority == "fibre" %} ++ ++ ++ + {% endif %} + + {% endfor %} +
IDTypeAuthorityInfoDateStatus
+
+ {% endif %} - {% endfor %} ++--> + + {% for request in requests %} + + {% if request.type == 'user' %} + + {% elif request.type == 'slice' %} + + {% else %} + + {% endif %} + {{ request.id }} + + {% if request.allowed == 'allowed' %} + + {% else %} + {% if request.allowed == 'expired' %}expired{% else %}denied{% endif %} + {% endif %} + + {{ request.type }} + {{authority}}{{request.site_authority}} + + {% if request.type == 'user' %} + {{request.first_name}} {{request.last_name}} <{{request.email}}> ++ ++ + + {% elif request.type == 'slice' %} + {{request.slice_name}} -- Number of nodes: {{request.number_of_nodes}} -- Type of nodes: {{request.type_of_nodes}} -- Purpose: {{request.purpose}} + {% else %} + {{request.site_name}} ({{request.site_authority}}) -- {{request.address_city}}, {{request.address_country}} + {% endif %} + + {{ request.timestamp }} + + + + + + + {% endfor %} + + {% endfor %} + + +
{% else %}
There is no pending request waiting for validation. diff --cc portal/templates/slice-resource-view.html index 626b7f5d,17e13830..2346bf23 --- a/portal/templates/slice-resource-view.html +++ b/portal/templates/slice-resource-view.html @@@ -105,13 -91,20 +91,25 @@@ $(document).ready(function()
{{map_resources}}
+
+ +

{{welcome}}

+

{{flowspaces}}

+

{{flowspaces_form}}

+

{{oflowspaces_form}}

+

{{topology}}

+

{{resources}}

+ +

{{below_table}}

+ +
- {{scheduler}} + {{scheduler}} +
+
+ {{resources}} + {{flowspaces}} + {{flowspaces_form}}