use logger instead of print as often as possible
[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 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)
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         if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):           
66             activation = 'success'
67
68             # AUTO VALIDATION of PLE enabled users (only for OneLab Portal)
69             if self.theme == "onelab":
70                 # Auto-Validation of pending user, which is enabled in a trusted SFA Registry (example: PLE)
71                 # We could check in the Registry based on email, but it takes too long 
72                 # as we currently need to do a Resolve on each user_hrn of the Registry in order to get its email
73                 # TODO in SFA XXX We need a Resolve based on email
74                 # TODO maybe we can use MyPLC API for PLE
75                 pending_users = PendingUser.objects.filter(email_hash__iexact = hash_code)
76
77                 # by default user is not in PLE
78                 ple_user_enabled = False
79
80                 if pending_users:
81                     pending_user = pending_users[0]
82                     
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                         # sending email after activation success
95                         #try:
96                         #    # Send an email: the recipient is the user
97                         #    recipients = pending_user_eamil 
98                         #    theme.template_name = 'user_request_email.html'
99                         #    html_content = render_to_string(theme.template, request)
100                         #    theme.template_name = 'user_request_email.txt'
101                         #    text_content = render_to_string(theme.template, request)
102                         #    theme.template_name = 'user_request_email_subject.txt'
103                         #    subject = render_to_string(theme.template, request)
104                         #    subject = subject.replace('\n', '')
105                         #    theme.template_name = 'email_default_sender.txt'
106                         #    sender =  render_to_string(theme.template, request)
107                         #    sender = sender.replace('\n', '')
108                         #    msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
109                         #    msg.attach_alternative(html_content, "text/html")
110                         #    msg.send()
111                         #except Exception as e:
112                         #    logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
113                         #    import traceback
114                         #    logger.error(traceback.format_exc())
115             
116             PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True')
117         else:
118             activation = 'failed'
119         
120         # get the domain url
121         current_site = Site.objects.get_current()
122         current_site = current_site.domain
123
124         
125         context = super(ActivateEmailView, self).get_context_data(**kwargs)
126         context['activation_status'] = activation
127         # XXX This is repeated in all pages
128         # more general variables expected in the template
129         context['title'] = 'Platforms connected to MySlice'
130         # the menu items on the top
131         context['topmenu_items'] = topmenu_items_live('My Account', page)
132         # so we can sho who is logged
133         context['username'] = the_user(self.request)
134         #context['first_name'] = first_name
135         #context['last_name'] = last_name
136         #context['authority_hrn'] = authority_hrn
137         #context['public_key'] = public_key
138         #context['email'] = email
139         #context['user_hrn'] = user_hrn
140         #context['current_site'] = current_site
141         context['theme'] = self.theme
142 #        context ['firstname'] = config['firstname']
143         prelude_env = page.prelude_env()
144         context.update(prelude_env)
145         return context