79f2c0ec9b87061d9b92eb042bdcc80fccc3a703
[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         # get the domain url
63         current_site = Site.objects.get_current()
64         current_site = current_site.domain
65
66         for key, value in kwargs.iteritems():
67             if key == "hash_code":
68                 hash_code=value
69
70         if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):           
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