- reasons for asking an account; rnp as a catch-all island; changing email messages...
[myslice.git] / portal / actions.py
index ccdd38f..93a32b9 100644 (file)
@@ -1,12 +1,16 @@
-from django.http                 import HttpResponse
-from manifold.core.query         import Query
-from manifoldapi.manifoldapi        import execute_query,execute_admin_query
-from portal.models               import PendingUser, PendingSlice, PendingAuthority
+from django.http                import HttpResponse
+from manifold.core.query        import Query
+from manifoldapi.manifoldapi    import execute_query,execute_admin_query
+from portal.models              import PendingUser, PendingSlice, PendingAuthority
 import json
 
 from django.contrib.auth.models import User
-from django.template.loader      import render_to_string
-from django.core.mail            import send_mail
+from django.template.loader     import render_to_string
+from django.core.mail           import EmailMultiAlternatives, send_mail
+
+from myslice.theme              import ThemeView
+
+theme = ThemeView()
 
 # Thierry: moving this right into the code so 
 # most people can use myslice without having to install sfa
@@ -19,6 +23,7 @@ from django.core.mail            import send_mail
 def authority_get_pis(request, authority_hrn):
     query = Query.get('authority').filter_by('authority_hrn', '==', authority_hrn).select('pi_users')
     results = execute_admin_query(request, query)
+    print "authority_get_pis = %s" % results
     # NOTE: temporarily commented. Because results is giving empty list. 
     # Needs more debugging
     #if not results:
@@ -29,7 +34,14 @@ def authority_get_pis(request, authority_hrn):
 
 def authority_get_pi_emails(request, authority_hrn):
     pi_users = authority_get_pis(request,authority_hrn)
-    if any(d['pi_users'] == None for d in pi_users):
+    print "pi_users = %s" % pi_users
+
+    if any(pi['pi_users'] == None or not pi['pi_users']  for pi in pi_users):
+        #theme.template_name = 'email_default_recipients.txt' 
+        #default_email = render_to_string(theme.template, request)
+        #default_email = default_email.replace('\n', '')
+        #return default_email
+        # the above doesn't work
         return ['support@myslice.info']
     else:
         pi_user_hrns = [ hrn for x in pi_users for hrn in x['pi_users'] ]
@@ -37,6 +49,44 @@ def authority_get_pi_emails(request, authority_hrn):
         results = execute_admin_query(request, query)
         return [result['user_email'] for result in results]
 
+#clear user credentials
+def clear_user_creds(request, user_email):
+    try:
+        user_query  = Query().get('local:user').filter_by('email', '==', user_email).select('user_id','email','password','config')
+        user_details = execute_admin_query(request, user_query)
+    
+        # getting the user_id from the session
+        for user_detail in user_details:
+            user_id = user_detail['user_id']
+            user_email = user_detail['email']
+    
+        account_query  = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
+        account_details = execute_admin_query(request, account_query)
+    
+        platform_query  = Query().get('local:platform').select('platform_id','platform')
+        platform_details = execute_admin_query(request, platform_query)
+    
+        for account_detail in account_details:
+            for platform_detail in platform_details:
+                if platform_detail['platform_id'] == account_detail['platform_id']:
+                    if 'myslice' in platform_detail['platform']:
+                        account_config = json.loads(account_detail['config'])
+                        user_cred = account_config.get('delegated_user_credential','N/A')
+                        if 'N/A' not in user_cred:
+                            user_hrn = account_config.get('user_hrn','N/A')
+                            user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
+                            user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
+                            updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
+                            user_params = { 'config': updated_config}
+                            manifold_update_account(request, user_id,user_params)
+                            return user_email
+                        else:
+                            return None
+
+    except Exception,e:
+        print "Exception in actions.py in clear_user_creds %s" % e
+        return None
+
 def is_pi(wsgi_request, user_hrn, authority_hrn):
     # XXX could be done in a single query !
 
@@ -103,15 +153,21 @@ def manifold_add_user(wsgi_request, request):
         ?
     
     """
+
+    authority_hrn = request['authority_hrn']
+    request['authority_hrn'] = authority_hrn.split(".")[0]
+
     USER_CONFIG = '{"firstname": "%(first_name)s", "lastname": "%(last_name)s", "authority": "%(authority_hrn)s"}'
 
     user_params = {
-        'email'     : request['email'],
+        'email'     : request['username'],
         'password'  : request['password'],
         'config'    : USER_CONFIG % request,
         'status'    : 1,
     }
 
+    request['authority_hrn'] = authority_hrn
+
     query = Query.create('local:user').set(user_params).select('email')
     results = execute_admin_query(request, query)
     if not results:
@@ -156,7 +212,7 @@ def manifold_add_platform(request, platform_params):
     query = Query.create('local:platform').set(platform_params).select(['user', 'platform'])
     results = execute_admin_query(request,query)
     if not results:
-        raise Exception, "Failed creating manifold  platform %s for user: %s" % (platform_params['platform'], platform_params['user'])
+        raise Exception, "Failed creating manifold platform %s for user: %s" % (platform_params['platform'], platform_params['user'])
     result, = results
     return result['platform_id']
 
@@ -174,6 +230,7 @@ def make_request_user(user):
     request['user_hrn']      = user.user_hrn
     request['public_key']    = user.public_key
     request['private_key']   = user.private_key
+    request['username']             = user.login
     return request
 
 def make_request_slice(slice):
@@ -240,7 +297,8 @@ def get_request_by_id(ids):
 def get_requests(authority_hrns=None):
     print "get_request_by_authority auth_hrns = ", authority_hrns
     if not authority_hrns:
-        pending_users  = PendingUser.objects.all()
+        ## get those pending users who have confirmed their emails
+        pending_users  = PendingUser.objects.filter(status__iexact = 'True')
         pending_slices = PendingSlice.objects.all()
         pending_authorities = PendingAuthority.objects.all()
     else:
@@ -272,7 +330,7 @@ def portal_validate_request(wsgi_request, request_ids):
             try:
                 create_user(wsgi_request, request)
                 request_status['SFA user'] = {'status': True }
-
+                PendingUser.objects.get(id=request['id']).delete()
             except Exception, e:
                  request_status['SFA user'] = {'status': False, 'description': str(e)}
                        
@@ -296,6 +354,7 @@ def portal_validate_request(wsgi_request, request_ids):
             try:
                 create_slice(wsgi_request, request)
                 request_status['SFA slice'] = {'status': True }
+                PendingSlice.objects.get(id=request['id']).delete()
 
             except Exception, e:
                 request_status['SFA slice'] = {'status': False, 'description': str(e)}
@@ -307,17 +366,19 @@ def portal_validate_request(wsgi_request, request_ids):
                 # XXX tmp sfa dependency
                 from sfa.util.xrn import Xrn 
                 urn = Xrn(hrn, request['type']).get_urn()
-
+                
+                # Only hrn is required for Manifold Query 
                 sfa_authority_params = {
-                    'hrn'        : hrn,
-                    'urn'        : urn,
-                    'type'       : request['type'],
+                    'authority_hrn'        : hrn,
+                    #'authority_urn'        : urn,
+                    #'type'       : request['type'],
                     #'pi'        : None,
-                    'enabled'    : True
+                    #'enabled'    : True
                 }
                 print "ADD Authority"
                 sfa_add_authority(wsgi_request, sfa_authority_params)
                 request_status['SFA authority'] = {'status': True }
+                PendingAuthority.objects.get(id=request['id']).delete()
 
             except Exception, e:
                 request_status['SFA authority'] = {'status': False, 'description': str(e)}
@@ -361,6 +422,8 @@ def create_slice(wsgi_request, request):
     # Add User to Slice if we have the user_hrn in pendingslice table
     user_hrn = request.get('user_hrn', None)
     user_hrns = list([user_hrn]) if user_hrn else list()
+    
+    user_email = request.get
 
     # XXX We should create a slice with Manifold terminology
     slice_params = {
@@ -376,9 +439,16 @@ def create_slice(wsgi_request, request):
     results = execute_query(wsgi_request, query)
     if not results:
         raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn']
+    ## We do not store the email in pendingslice table. As a result receiver's email is unknown ##
+    ## Need modification in pendingslice table ###
+    #else:
+    #    subject = 'Slice created'
+    #    msg = 'A manager of your institution has validated your slice request. You can now add resources to the slice and start experimenting.'
+    #    send_mail(subject, msg, 'support@onelab.eu',['yasin.upmc@gmail.com'], fail_silently=False)
+       
     return results
 
-def create_pending_slice(wgsi_request, request):
+def create_pending_slice(wsgi_request, request, email):
     """
     """
 
@@ -387,15 +457,35 @@ def create_pending_slice(wgsi_request, request):
         slice_name      = request['slice_name'],
         user_hrn        = request['user_hrn'],
         authority_hrn   = request['authority_hrn'],
-        number_of_nodes = request['number_of_nodes'],
+        number_of_nodes = request['exp_url'],
         purpose         = request['purpose'],
     )
     s.save()
 
-    # Send an email: the recipients are the PI of the authority
-    recipients = authority_get_pi_emails(wsgi_request, authority_hrn)
-    msg = render_to_string('slice-request-email.txt', request)
-    send_mail("Onelab user %(email)s requested a slice" % request, msg, email, recipients)
+    try:
+        # Send an email: the recipients are the PI of the authority
+        recipients = authority_get_pi_emails(wsgi_request, request['authority_hrn'])
+
+        theme.template_name = 'slice_request_email.txt' 
+        text_content = render_to_string(theme.template, request)
+    
+        theme.template_name = 'slice_request_email.html' 
+        html_content = render_to_string(theme.template, request)
+    
+        theme.template_name = 'slice_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', '')
+
+        #sender = email
+        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"
 
 #-------------------------------------------------------------------------------
 # REQUESTS - Users
@@ -409,7 +499,7 @@ def manifold_add_reference_user_accounts(wsgi_request, request):
     # Retrieve user information
     user_query  = Query().get('local:user')             \
         .select('user_id', 'config', 'email', 'status') \
-        .filter_by('email', '==', request['email'])
+        .filter_by('email', '==', request['username'])
     user_details = execute_admin_query(wsgi_request, user_query)
 
     # USER MAIN ACCOUNT != reference
@@ -474,8 +564,144 @@ def sfa_create_user(wsgi_request, request):
     results = execute_query(wsgi_request, query)
     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
 
+def ldap_create_user(wsgi_request, request, user_detail):
+    """
+    Populating LDAP withuser data - Edelberto 10/03/2014
+    """
+    # import needed modules
+    import ldap
+    import ldap.modlist as modlist
+
+    # Open a connection
+    # XXX We need to create this in settings
+    # ldap.open is deprecated!
+    #l = ldap.open("127.0.0.1")
+    l = ldap.initialize('ldap://127.0.0.1:389')
+
+    # you should  set this to ldap.VERSION2 if you're using a v2 directory
+    l.protocol_version = ldap.VERSION3
+
+    # Bind/authenticate with a user with apropriate rights to add objects
+    # XXX Now we set the force rootd but after we need to set this in settings file for could change the dn and password of root
+    l.simple_bind_s("cn=Manager,dc=br","fibre")
+
+    # The dn of our new entry/object
+    #dn="uid=addtest@uff.br,ou=people,o=uff,dc=br"
+
+    # we need to create the dn entry
+    # Receiving an email address, how can we split and mount it in DN format?
+    #mail = "debora@uff.br"
+    mail = request['email']
+    login = mail.split('@')[0]
+    org = mail.split('@')[1]
+    o = org.split('.')[-2]
+    dc = org.split('.')[-1]
+
+    # DN format to authenticate - IMPORTANT!
+    #FIBRE-BR format
+    dn = "uid="+mail+",ou=people,o="+o+",dc="+dc
+
+    # DEBUG
+    print "dn:"+dn
+    print request['password']
+
+    # Creating a unique uidNumber - Necessary for experiments
+    # Was defined to began in 100000
+    unique = int(user_detail['user_id']) + 100000
+    #unique = int(unique)
+    print unique
+
+    # A dict to help build the "body" of the object
+    attrs = {}
+    attrs['objectclass'] = ['person','inetOrgPerson','posixAccount','eduPerson','brPerson','schacPersonalCharacteristics','fibre', 'ldapPublicKey']
+    # XXX Converting all unicodes to string
+    attrs['uid'] = mail.encode('utf-8')
+    attrs['cn'] = request['first_name'].encode('latin1')
+    attrs['sn'] = request['last_name'].encode('latin1')
+    # XXX we need to set a unique uidNumber. How?
+    attrs['uidNumber'] = str(unique)
+    attrs['gidNumber'] = '500'
+    attrs['homeDirectory'] = "/home/"+org+"/"+mail
+    attrs['homeDirectory'] = attrs['homeDirectory'].encode('utf-8')
+    attrs['mail'] = mail.encode('utf-8')
+    attrs['eppn'] = mail.encode('utf8')
+    attrs['userPassword'] = request['password'].encode('utf-8')
+    attrs['sshPublicKey'] = request['public_key'].encode('utf-8')
+    # XXX We really set TRUE for those attributes? 
+    #attrs['userEnable'] = 'TRUE'
+    # set FALSE and change after when the user is validated
+    attrs['userEnable'] = 'FALSE'
+    attrs['omfAdmin'] = 'TRUE'
+
+    # Convert our dict to nice syntax for the add-function using modlist-module
+    ldif = modlist.addModlist(attrs)
+
+    # DEBUG
+    print attrs['userPassword']
+    print attrs['cn']
+    print attrs['sn']
+    print attrs['homeDirectory']
+    #print ldif
+
+    # Do the actual synchronous add-operation to the ldapserver
+    l.add_s(dn,ldif)
+
+    # Its nice to the server to disconnect and free resources when done
+    l.unbind_s()
+
+    return ldif
+
+def ldap_modify_user(wsgi_request, request):
+    #Modify entries in an LDAP Directory
+
+    #Synchrounous modify
+    # import needed modules
+    import ldap
+    import ldap.modlist as modlist
+
+    # Open a connection
+    l = ldap.initialize("ldap://localhost:389/")
+
+    # Bind/authenticate with a user with apropriate rights to add objects
+    l.simple_bind_s("cn=Manager,dc=br","fibre")
+
+    # we need to create the dn entry
+    # Receiving an email address, how can we split and mount it in DN format?
+    #mail = "debora@uff.br"
+    mail = request['email']
+    login = mail.split('@')[0]
+    org = mail.split('@')[1]
+    o = org.split('.')[-2]
+    dc = org.split('.')[-1]
+
+    # DN format to authenticate - IMPORTANT!
+    #FIBRE-BR format
+    dn = "uid="+mail+",ou=people,o="+o+",dc="+dc
+
+    # The dn of our existing entry/object
+    #dn="uid=mario@uff.br,ou=people,o=uff,dc=br"
+
+    # Some place-holders for old and new values
+    old = {'userEnable':'FALSE'}
+    new = {'userEnable':'TRUE'}
+
+    # Convert place-holders for modify-operation using modlist-module
+    ldif = modlist.modifyModlist(old,new)
+
+    # Do the actual modification
+    l.modify_s(dn,ldif)
+
+    # Its nice to the server to disconnect and free resources when done
+    l.unbind_s()
+
+    return ldif
+
 def create_user(wsgi_request, request):
     
     # XXX This has to be stored centrally
@@ -483,16 +709,34 @@ def create_user(wsgi_request, request):
 
     # 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)
+    #sfa_create_user(wsgi_request, request)
 
     # 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)
+    
+# Add the user to the SFA registry
+    sfa_create_user(wsgi_request, request)
 
+    '''   
+    # LDAP update user userEnabled = True
+    try:
+        mail = request['email']
+        login = mail.split('@')[0]
+        org = mail.split('@')[1]
+        o = org.split('.')[-2]
+        dc = org.split('.')[-1]
+        # To know if user is a LDAP user - Need to has a 'dc' identifier
+        if dc == 'br' or 'eu':
+            ldap_modify_user(wsgi_request, request)
+    except Exception, e:
+        "LDAP create user failed"
+    '''
 def create_pending_user(wsgi_request, request, user_detail):
     """
     """
@@ -503,16 +747,39 @@ def create_pending_user(wsgi_request, request, user_detail):
         last_name     = request['last_name'],
         authority_hrn = request['authority_hrn'],
         email         = request['email'],
+        login         = request['username'],
         password      = request['password'],
         public_key    = request['public_key'],
         private_key   = request['private_key'],
         user_hrn      = request['user_hrn'],
-        pi            = '',                         # XXX Why not None ?
+        pi            = request['pi'],
+        email_hash    = request['email_hash'],
+       reasons       = request['reasons'],
+        status        = 'False',
     )
     b.save()
 
+    # sends email to user to activate the email
+    theme.template_name = 'activate_user.html'
+    html_content = render_to_string(theme.template, request)
+    theme.template_name = 'activate_user.txt'
+    text_content = render_to_string(theme.template, request)
+    theme.template_name = 'activate_user_email_subject.txt'
+    subject = render_to_string(theme.template, request)
+    subject = subject.replace('\n', '')
+    #sender = 'support@myslice.info'
+    theme.template_name = 'email_default_sender.txt'
+    sender =  render_to_string(theme.template, request)
+    sender = sender.replace('\n', '')
+    recipient = [request['email']]
+    #recipient = recipient.append(request['email'])
+
+    msg = EmailMultiAlternatives(subject, text_content, sender, recipient)
+    msg.attach_alternative(html_content, "text/html")
+    msg.send()
+   
     # saves the user to django auth_user table [needed for password reset]
-    user = User.objects.create_user(request['email'], request['email'], request['password'])
+    user = User.objects.create_user(request['username'], request['email'], request['password'])
 
     # Creating a manifold user
     user_id = manifold_add_user(wsgi_request, request)
@@ -527,15 +794,73 @@ def create_pending_user(wsgi_request, request, user_detail):
         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
-    account_params = {
-        'platform_id'   : 5, # XXX ALERT !!
-        'user_id'       : user_id, 
-        'auth_type'     : request['auth_type'], 
-        'config'        : json.dumps(account_config),
-    }
-    manifold_add_account(wsgi_request, account_params)
 
-    # Send an email: the recipients are the PI of the authority
-    recipients = authority_get_pi_emails(wsgi_request, request['authority_hrn'])
-    msg = render_to_string('user_request_email.txt', request)
-    send_mail("Onelab New User request for %(email)s submitted" % request, msg, 'support@myslice.info', recipients)
+    # 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'])
+
+    # Add user to LDAP userEnabled = False
+    # Not more here. Create before directly to the registrationview.py
+    # After we change userEnable = TRUE when validate the user
+
+    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)
+
+        split_authority_hrn = request['authority_hrn'].split(".")[0]
+
+        recipients = authority_get_pi_emails(wsgi_request, split_authority_hrn)
+
+        pis = authority_get_pis(request, split_authority_hrn)
+        pi_emails = []
+        for x in pis:
+            for e in x['pi_users']:
+                try:
+                    u = e.split(".")[1]
+                    y = User.objects.get(username = u)
+                    if y.username.count("@") != 0:
+                        if y.username.split("@")[1] == request['username'].split("@")[1]:
+                            pi_emails += [y.email]
+                except:
+                    print "fail"
+
+        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, pi_emails)
+
+        msg.attach_alternative(html_content, "text/html")
+        msg.send()
+       print pi_emails
+    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()