use logger instead of print as often as possible
[myslice.git] / portal / actions.py
index 047288d..7d57b9d 100644 (file)
@@ -14,7 +14,7 @@ from django.core.mail               import EmailMultiAlternatives, send_mail
 
 from myslice.theme                  import ThemeView
 from myslice.configengine           import ConfigEngine
-
+from myslice.settings               import logger
 
 theme = ThemeView()
 
@@ -81,8 +81,8 @@ def authority_check_pis(request, user_email):
             pi_status = True
         return pi_status
 
-    except Exception,e:
-        print "Exception in actions.py in authority_check_pis %s" % e
+    except Exception as e:
+        logger.error("Exception in actions.py in authority_check_pis {}".format(e))
         return None
 
 
@@ -98,8 +98,8 @@ def authority_add_pis(request, authority_hrn,user_hrn):
         results = execute_query(request,query)
         newpis = authority_get_pis (request, authority_hrn)
         return newpis
-    except Exception,e: 
-        print "Exception in actions.py in authority_add_pis %s" % e
+    except Exception as e: 
+        logger.error("Exception in actions.py in authority_add_pis {}".format(e))
         return None
 
 
@@ -115,14 +115,14 @@ def authority_remove_pis(request, authority_hrn,user_hrn):
         results = execute_query(request,query)
         newpis = authority_get_pis (request, authority_hrn)
         return newpis
-    except Exception,e: 
-        print "Exception in actions.py in authority_remove_pis %s" % e
+    except Exception as e: 
+        logger.error("Exception in actions.py in authority_remove_pis {}".format(e))
         return None
 
 
 def authority_get_pi_emails(request, authority_hrn):
     pi_users = authority_get_pis(request,authority_hrn)
-    print "pi_users = %s" % pi_users
+    logger.info("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' 
@@ -174,13 +174,13 @@ def clear_user_creds(request, user_email):
                         else:
                             return None
 
-    except Exception,e:
-        print "Exception in actions.py in clear_user_creds %s" % e
+    except Exception as e:
+        logger.error("Exception in actions.py in clear_user_creds {}".format(e))
         return None
 
 def is_pi(wsgi_request, user_hrn, authority_hrn):
     # authorities from user where user_hrn == "ple.upmc.jordan_auge"
-    print "#### actions.py is_pi authority_hrn = ", authority_hrn
+    logger.debug("#### actions.py is_pi authority_hrn = {}".format(authority_hrn))
     try:
         # CACHE PB with fields
         page = Page(wsgi_request)
@@ -192,12 +192,11 @@ def is_pi(wsgi_request, user_hrn, authority_hrn):
         query  = Query().get('myslice:user').select(user_fields).filter_by('user_hrn','==',user_hrn)
         #query = Query.get('myslice:user').filter_by('user_hrn', '==', user_hrn).select('pi_authorities')
         results = execute_query(wsgi_request, query)
-        print "is_pi results = ", results
         for user_detail in results:
             if authority_hrn in user_detail['pi_authorities']:
                 return True
-    except Exception,e:
-        print "Exception in actions.py in is_pi %s" % e
+    except Exception as e:
+        logger.error("Exception in actions.py in is_pi {}".format(e))
     return False
     
 # SFA get record
@@ -224,7 +223,7 @@ def sfa_add_authority(request, authority_params):
     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
     query = Query.create('myslice:authority').set(authority_params).select('authority_hrn')
     results = execute_query(request, query)
-    print "sfa_add_auth results=",results
+    logger.info("sfa_add_auth results={}".format(results))
     if not results:
         raise Exception, "Could not create %s. Already exists ?" % authority_params['hrn']
     return results
@@ -305,13 +304,15 @@ def manifold_update_account(request,user_id,account_params):
     return results
 
 #explicitly mention the platform_id
-def manifold_delete_account(request, platform_id, user_id, account_params):
-    query = Query.delete('local:account').filter_by('platform_id', '==', platform_id).filter_by('user_id', '==', user_id).set(account_params).select('user_id')
+def manifold_delete_account(request, user_id, platform_id = None):
+    query = Query.delete('local:account').filter_by('user_id', '==', user_id)
+    if platform_id is not None:
+        query.filter_by('platform_id', '==', platform_id)
     results = execute_admin_query(request,query)
     return results
 
-def manifold_delete_user(request, user_id, user_params):
-    query = Query.delete('local:user').filter_by('user_id', '==', user_id).set(user_params).select('user_id')
+def manifold_delete_user(request, user_id):
+    query = Query.delete('local:user').filter_by('user_id', '==', user_id).select('user_id')
     results = execute_admin_query(request,query)
     return results
 
@@ -325,6 +326,35 @@ def manifold_add_platform(request, platform_params):
     result, = results
     return result['platform_id']
 
+def delete_local_user(wsgi_request, user_email):
+    user_query = Query().get('local:user') \
+        .filter_by('email', '==', user_email)           \
+        .select('user_id','config')
+    user = execute_admin_query(wsgi_request, user_query)
+    if len(user) == 0:
+        return False
+        #raise Exception, "User not found, check local DB"
+    else:
+        user_id = user[0]['user_id']
+        user_config = json.loads(user[0]['config'])
+        authority_hrn = user_config.get('authority', None)
+        
+        if is_pi(wsgi_request, '$user_hrn', authority_hrn):
+            # removing from Django auth_user
+            UserModel = get_user_model()
+            UserModel._default_manager.filter(email__iexact = user_email).delete()
+
+            # removing manifold account
+            manifold_delete_account(wsgi_request, user_id)           
+                     
+            # removing manifold user
+            manifold_delete_user(wsgi_request, user_id)
+        else:
+            return False
+            #raise Exception, "No sufficient rights on authority = ",authority_hrn
+
+    return True      
+
 
 def make_request_user(user):
     request = {}
@@ -399,7 +429,7 @@ def make_request_authority(authority):
     return request
 
 def make_requests(pending_users, pending_slices, pending_authorities, pending_projects, pending_joins):
-    print "$$$$$$$$$$$$$$$  make_request"
+    logger.info("$$$$$$$$$$$$$$$  make_request")
     requests = []
     for user in pending_users:
         requests.append(make_request_user(user))
@@ -414,7 +444,7 @@ def make_requests(pending_users, pending_slices, pending_authorities, pending_pr
     return requests   
 
 def get_request_by_id(ids):
-    print "$$$$$$$$$$$$$$$$  get_request_by_id"
+    logger.info("$$$$$$$$$$$$$$$$  get_request_by_id")
     sorted_ids = { 'user': [], 'slice': [], 'authority': [], 'project': [], 'join': [] }
     for type__id in ids:
         type, id = type__id.split('__')
@@ -436,7 +466,7 @@ def get_request_by_id(ids):
     return make_requests(pending_users, pending_slices, pending_authorities, pending_projects, pending_joins)
 
 def get_requests(authority_hrns=None):
-    print "$$$$$$$$$$$$$   get_request_by_authority auth_hrns = ", authority_hrns
+    logger.info("$$$$$$$$$$$$$   get_request_by_authority auth_hrns = {}".format(authority_hrns))
     if not authority_hrns:
         ## get those pending users who have confirmed their emails
         pending_users  = PendingUser.objects.filter(status__iexact = 'True')
@@ -543,7 +573,7 @@ def portal_validate_request(wsgi_request, request_ids):
                     #'pi'        : None,
                     #'enabled'    : True
                 }
-                print "ADD Authority"
+                logger.info("ADD Authority")
                 sfa_add_authority(wsgi_request, sfa_authority_params)
                 request_status['SFA authority'] = {'status': True }
                 PendingAuthority.objects.get(id=request['id']).delete()
@@ -656,33 +686,13 @@ def portal_reject_request(wsgi_request, request_ids):
                     msg = EmailMultiAlternatives(subject, text_content, sender, [user_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"   
-            
-                # removing from Django auth_user
-                UserModel = get_user_model()
-                UserModel._default_manager.filter(email__iexact = user_email).delete()
+                except Exception as e:
+                    logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")   
+
                 # removing from Django portal_pendinguser
                 PendingUser.objects.get(id=request['id']).delete()
-                # removing from manifold
-                # removing manifold account
-                user_query = Query().get('local:user') \
-                    .filter_by('email', '==', user_email)           \
-                    .select('user_id')
-                user = execute_admin_query(wsgi_request, user_query)
-                user_id = user[0]['user_id']
-        
-                platform_query = Query().get('local:platform') \
-                    .filter_by('platform', '==', 'myslice')           \
-                    .select('platform_id')
-                platform = execute_admin_query(wsgi_request, platform_query)
-                platform_id = platform[0]['platform_id']
-                account_params = {'user_id':user_id}
-                manifold_delete_account(request, platform_id, user_id, account_params)           
-             
-                # removing manifold user
-                user_params = {'user_id':user_id}
-                manifold_delete_user(request, user_id, user_params)
+            
+                delete_local_user(wsgi_request, user_email)
             except Exception, e:
                 request_status['SFA authority'] = {'status': False, 'description': str(e)}
                       
@@ -717,8 +727,8 @@ def portal_reject_request(wsgi_request, request_ids):
                 msg = EmailMultiAlternatives(subject, text_content, sender, [user_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"
+            except Exception as e:
+                logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
                       
             PendingSlice.objects.get(id=request['id']).delete()
 
@@ -756,8 +766,8 @@ def portal_reject_request(wsgi_request, request_ids):
                 msg = EmailMultiAlternatives(subject, text_content, sender, [user_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"
+            except Exception as e:
+                logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
             PendingAuthority.objects.get(id=request['id']).delete()
 
@@ -855,8 +865,8 @@ def create_slice(wsgi_request, request):
             msg = EmailMultiAlternatives(subject, text_content, sender, [user_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"
+        except Exception as e:
+            logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
        
     return results
 
@@ -893,8 +903,8 @@ def create_pending_slice(wsgi_request, request, 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"
+    except Exception as e:
+        logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
 
 def create_pending_project(wsgi_request, request):
@@ -1050,8 +1060,8 @@ def sfa_create_user(wsgi_request, request, namespace = None, as_admin = False):
             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"
+        except Exception as e:
+            logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
     return results
 
@@ -1089,7 +1099,7 @@ def iotlab_create_user (wsgi_request, request, namespace = None, as_admin=False)
    
     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
+    logger.info('Create iotlab user : {} {}'.format(r.status_code, r.text))
     return r.text
 
 def create_user(wsgi_request, request, namespace = None, as_admin = False):
@@ -1185,8 +1195,8 @@ def create_pending_user(wsgi_request, request, user_detail):
             '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'])
+    except Exception as e:
+        logger.error("Failed creating manifold account on platform {} for user: {}".format('myslice', request['email']))
 
     try:
         # Send an email: the recipients are the PI of the authority
@@ -1211,6 +1221,6 @@ def create_pending_user(wsgi_request, request, user_detail):
         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"
+        logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
         import traceback
-        traceback.print_exc()
+        logger.error(traceback.format_exc())