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