emails
[myslice.git] / portal / emailactivationview.py
1 import json
2 import os
3 import re
4 import itertools
5
6 from django.http                        import HttpResponse, HttpResponseRedirect
7 from django.contrib                     import messages
8 from django.contrib.auth.decorators     import login_required
9 from django.core.mail                   import EmailMultiAlternatives, send_mail
10
11 from manifold.core.query                import Query
12 from manifoldapi.manifoldapi            import execute_query, execute_admin_query
13
14 from unfold.loginrequired               import FreeAccessView
15
16 from portal.actions                     import (
17     manifold_update_user, manifold_update_account, manifold_add_account,
18     manifold_delete_account, sfa_update_user, authority_get_pi_emails,
19     make_request_user, create_user, send_email_to_pis)
20 from portal.models                      import PendingUser, PendingAuthority
21
22 from unfold.page                        import Page    
23 from ui.topmenu                         import topmenu_items_live, the_user
24
25 from myslice.theme                      import ThemeView
26 from myslice.settings import logger
27
28 def ValuesQuerySetToDict(vqs):
29     return [item for item in vqs]
30
31 # requires login
32 class ActivateEmailView(FreeAccessView, ThemeView):
33     template_name = "email_activation.html"
34     def is_ple_enabled(self, pending_user):
35         pending_authorities = PendingAuthority.objects.filter(site_authority__iexact = pending_user.authority_hrn)
36         if pending_authorities:
37             return False                        
38         pending_user_email = pending_user.email
39         try:
40             query = Query.get('myplcuser').filter_by('email', '==', pending_user_email).select('enabled')
41             results = execute_admin_query(self.request, query)
42             for result in results:
43                 # User is enabled in PLE
44                 if 'enabled' in result and result['enabled']==True:
45                     return True
46         except Exception as e:
47             logger.error("Exception in myplc query = {}".format(e))
48
49         return False
50
51     def dispatch(self, *args, **kwargs):
52         return super(ActivateEmailView, self).dispatch(*args, **kwargs)
53
54     def get_context_data(self, **kwargs):
55
56         page = Page(self.request)
57         #page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
58         #page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
59         if self.request.is_secure():
60             current_site = 'https://'
61         else:
62             current_site = 'http://'
63         current_site += self.request.META['HTTP_HOST']
64
65         for key, value in kwargs.iteritems():
66             if key == "hash_code":
67                 hash_code=value
68
69         #if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):
70         if PendingUser.objects.filter(email_hash__iexact = hash_code):
71             activation = 'success'
72             pending_users = PendingUser.objects.filter(email_hash__iexact = hash_code)
73             pending_user = pending_users[0]
74
75             # AUTO VALIDATION of PLE enabled users (only for OneLab Portal)
76             if self.theme == "onelab":
77                 # Auto-Validation of pending user, which is enabled in a trusted SFA Registry (example: PLE)
78                 # We could check in the Registry based on email, but it takes too long 
79                 # as we currently need to do a Resolve on each user_hrn of the Registry in order to get its email
80                 # TODO in SFA XXX We need a Resolve based on email
81                 # TODO maybe we can use MyPLC API for PLE
82
83                 # by default user is not in PLE
84                 ple_user_enabled = False
85
86                 if pending_user:
87                     # Auto Validation 
88                     if self.is_ple_enabled(pending_user):
89                         pending_user_request = make_request_user(pending_user)
90                         # Create user in SFA and Update in Manifold
91                         create_user(self.request, pending_user_request, namespace = 'myslice', as_admin = True)
92                         # Delete pending user
93                         PendingUser.objects.filter(email_hash__iexact = hash_code).delete()
94
95                         # template user auto validated
96                         activation = 'validated'
97             
98             PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True')
99             u = {}
100             u['first_name']    =  pending_user.first_name   
101             u['last_name']     =  pending_user.last_name    
102             u['authority_hrn'] =  pending_user.authority_hrn
103             u['email']         =  pending_user.email        
104             u['user_hrn']      =  pending_user.user_hrn     
105             u['pi']            =  pending_user.pi           
106             u['public_key']    =  pending_user.public_key
107             u['current_site']  = current_site
108
109             send_email_to_pis(self.request, u, 'user')
110         else:
111             activation = 'failed'
112         
113         
114         context = super(ActivateEmailView, self).get_context_data(**kwargs)
115         context['activation_status'] = activation
116         # XXX This is repeated in all pages
117         # more general variables expected in the template
118         context['title'] = 'Platforms connected to MySlice'
119         # the menu items on the top
120         context['topmenu_items'] = topmenu_items_live('My Account', page)
121         # so we can sho who is logged
122         context['username'] = the_user(self.request)
123         #context['first_name'] = first_name
124         #context['last_name'] = last_name
125         #context['authority_hrn'] = authority_hrn
126         #context['email'] = email
127         #context['user_hrn'] = user_hrn
128         context['theme'] = self.theme
129 #        context ['firstname'] = config['firstname']
130         prelude_env = page.prelude_env()
131         context.update(prelude_env)
132         return context