Auto Validation of PLE users using MyPLC API based on the email instead of tweaking...
[myslice.git] / portal / emailactivationview.py
1 from unfold.loginrequired               import FreeAccessView
2 #
3 from manifold.core.query                import Query
4 from manifoldapi.manifoldapi            import execute_query, execute_admin_query
5 from portal.actions                     import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, authority_get_pi_emails, make_request_user, create_user
6 #
7 from unfold.page                        import Page    
8 from ui.topmenu                         import topmenu_items_live, the_user
9 #
10 from django.http                        import HttpResponse, HttpResponseRedirect
11 from django.contrib                     import messages
12 from django.contrib.auth.decorators     import login_required
13 from myslice.theme                      import ThemeView
14 from portal.models                      import PendingUser
15 from django.core.mail                   import EmailMultiAlternatives, send_mail
16 from django.contrib.sites.models        import Site
17
18 #
19 import json, os, re, itertools
20
21 def ValuesQuerySetToDict(vqs):
22     return [item for item in vqs]
23
24
25 # requires login
26 class ActivateEmailView(FreeAccessView, ThemeView):
27     template_name = "email_activation.html"
28     def dispatch(self, *args, **kwargs):
29         return super(ActivateEmailView, self).dispatch(*args, **kwargs)
30
31     def get_context_data(self, **kwargs):
32
33         page = Page(self.request)
34         #page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
35         #page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
36
37         for key, value in kwargs.iteritems():
38             #print "%s = %s" % (key, value)
39             if key == "hash_code":
40                 hash_code=value
41        
42         if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):           
43             # AUTO VALIDATION of PLE enabled users (only for OneLab Portal)
44             if self.theme == "onelab":
45                 # Auto-Validation of pending user, which is enabled in a trusted SFA Registry (example: PLE)
46                 # We could check in the Registry based on email, but it takes too long 
47                 # as we currently need to do a Resolve on each user_hrn of the Registry in order to get its email
48                 # TODO in SFA XXX We need a Resolve based on email
49                 # TODO maybe we can use MyPLC API for PLE
50                 pending_users = PendingUser.objects.filter(email_hash__iexact = hash_code)
51                 if pending_users:
52                     pending_user = pending_users[0]
53                     pending_user_request = make_request_user(pending_user)
54                     pending_user_email = pending_users[0].user_email
55                     query = Query.get('myplcuser').filter_by('email', '==', pending_user_email).select('enabled')
56                     results = execute_admin_query(self.request, query)
57                     for result in results:
58                         # User is enabled in PLE
59                         if 'user_enabled' in result and result['user_enabled']==True:
60                             ple_user_enabled = True
61                             break
62                         else:
63                             ple_user_enabled = False
64
65                     # Auto Validation 
66                     if ple_user_enabled:
67                         # Create user in SFA and Update in Manifold
68                         create_user(self.request, pending_user_request, namespace = 'myslice', as_admin = True)
69                         # Delete pending user
70                         PendingUser.objects.filter(email_hash__iexact = hash_code).delete()
71
72             #get_user.status= 'True'
73             #get_user.save()
74             #for user in PendingUser.objects.all():
75             #    first_name = user.first_name
76             #    last_name = user.last_name
77             #    authority_hrn = user.authority_hrn
78             #    public_key = user.public_key
79             #    email = user.email
80             #    user_hrn = user.user_hrn
81             PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True')
82             activation = 'success'
83             # sending email after activation success
84             #try:
85                 # Send an email: the recipients are the PI of the authority
86                 # If No PI is defined for this Authority, send to a default email (different for each theme)
87              #   recipients = authority_get_pi_emails(wsgi_request, authority_hrn)
88              #   theme.template_name = 'user_request_email.html'
89              #   html_content = render_to_string(theme.template, request)
90              #   theme.template_name = 'user_request_email.txt'
91              #   text_content = render_to_string(theme.template, request)
92              #   theme.template_name = 'user_request_email_subject.txt'
93              #   subject = render_to_string(theme.template, request)
94              #   subject = subject.replace('\n', '')
95              #   theme.template_name = 'email_default_sender.txt'
96              #   sender =  render_to_string(theme.template, request)
97              #   sender = sender.replace('\n', '')
98              #   msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
99              #   msg.attach_alternative(html_content, "text/html")
100              #   msg.send()
101            # except Exception, e:
102              #   print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
103              #   import traceback
104              #   traceback.print_exc()
105
106         else:
107             activation = 'failed'
108         
109         # get the domain url
110         current_site = Site.objects.get_current()
111         current_site = current_site.domain
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['public_key'] = public_key
127         #context['email'] = email
128         #context['user_hrn'] = user_hrn
129         #context['current_site'] = current_site
130         context['theme'] = self.theme
131 #        context ['firstname'] = config['firstname']
132         prelude_env = page.prelude_env()
133         context.update(prelude_env)
134         return context