4680256ca8285547c98d5409b78dc4cda8e5aefa
[unfold.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         if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):           
42             activation = 'success'
43
44             # AUTO VALIDATION of PLE enabled users (only for OneLab Portal)
45             if self.theme == "onelab":
46                 # Auto-Validation of pending user, which is enabled in a trusted SFA Registry (example: PLE)
47                 # We could check in the Registry based on email, but it takes too long 
48                 # as we currently need to do a Resolve on each user_hrn of the Registry in order to get its email
49                 # TODO in SFA XXX We need a Resolve based on email
50                 # TODO maybe we can use MyPLC API for PLE
51                 pending_users = PendingUser.objects.filter(email_hash__iexact = hash_code)
52
53                 # by default user is not in PLE
54                 ple_user_enabled = False
55
56                 if pending_users:
57                     pending_user = pending_users[0]
58                     pending_user_request = make_request_user(pending_user)
59                     pending_user_email = pending_users[0].email
60                     query = Query.get('myplcuser').filter_by('email', '==', pending_user_email).select('enabled')
61                     results = execute_admin_query(self.request, query)
62                     for result in results:
63                         # User is enabled in PLE
64                         if 'enabled' in result and result['enabled']==True:
65                             ple_user_enabled = True
66                             break
67
68                     # Auto Validation 
69                     if ple_user_enabled:
70                         # Create user in SFA and Update in Manifold
71                         create_user(self.request, pending_user_request, namespace = 'myslice', as_admin = True)
72                         # Delete pending user
73                         #PendingUser.objects.filter(email_hash__iexact = hash_code).delete()
74
75                         # template user auto validated
76                         activation = 'validated'
77
78                         # sending email after activation success
79                         #try:
80                         #    # Send an email: the recipient is the user
81                         #    recipients = pending_user_eamil 
82                         #    theme.template_name = 'user_request_email.html'
83                         #    html_content = render_to_string(theme.template, request)
84                         #    theme.template_name = 'user_request_email.txt'
85                         #    text_content = render_to_string(theme.template, request)
86                         #    theme.template_name = 'user_request_email_subject.txt'
87                         #    subject = render_to_string(theme.template, request)
88                         #    subject = subject.replace('\n', '')
89                         #    theme.template_name = 'email_default_sender.txt'
90                         #    sender =  render_to_string(theme.template, request)
91                         #    sender = sender.replace('\n', '')
92                         #    msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
93                         #    msg.attach_alternative(html_content, "text/html")
94                         #    msg.send()
95                         #except Exception, e:
96                         #    print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
97                         #    import traceback
98                         #    traceback.print_exc()
99             
100             PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True')
101         else:
102             activation = 'failed'
103         
104         # get the domain url
105         current_site = Site.objects.get_current()
106         current_site = current_site.domain
107
108         
109         context = super(ActivateEmailView, self).get_context_data(**kwargs)
110         context['activation_status'] = activation
111         # XXX This is repeated in all pages
112         # more general variables expected in the template
113         context['title'] = 'Platforms connected to MySlice'
114         # the menu items on the top
115         context['topmenu_items'] = topmenu_items_live('My Account', page)
116         # so we can sho who is logged
117         context['username'] = the_user(self.request)
118         #context['first_name'] = first_name
119         #context['last_name'] = last_name
120         #context['authority_hrn'] = authority_hrn
121         #context['public_key'] = public_key
122         #context['email'] = email
123         #context['user_hrn'] = user_hrn
124         #context['current_site'] = current_site
125         context['theme'] = self.theme
126 #        context ['firstname'] = config['firstname']
127         prelude_env = page.prelude_env()
128         context.update(prelude_env)
129         return context