translate most modules to using print() as imported from __future__
[myslice.git] / portal / joinview.py
1 from __future__ import print_function
2
3 import os.path, re
4 import json
5 from random import randint
6
7 from hashlib                    import md5
8 from django.core.mail           import EmailMultiAlternatives
9 from django.contrib.auth.models import User
10 from django.views.generic       import View
11 from django.template.loader     import render_to_string
12 from django.shortcuts           import render
13 from django.contrib.auth        import get_user_model
14 from django.contrib.sites.models import Site
15
16 from unfold.page                import Page
17 from unfold.loginrequired       import FreeAccessView
18 from ui.topmenu                 import topmenu_items_live
19
20 from manifoldapi.manifoldapi    import execute_admin_query
21 from manifold.core.query        import Query
22
23 from portal.models              import PendingUser,PendingAuthority
24 from portal.actions             import authority_get_pi_emails, manifold_add_user,manifold_add_account, create_pending_user
25
26 from myslice.theme import ThemeView
27
28 import activity.institution
29
30 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
31 # so let's override 'get' and 'post' instead
32 #
33 class JoinView (FreeAccessView, ThemeView):
34
35     def post (self, request):
36         return self.get_or_post (request, 'POST')
37
38     def get (self, request):
39         return self.get_or_post (request, 'GET')
40
41     def get_or_post  (self, request, method):
42         errors = []
43         # List authorities already in the Registry in order to avoid duplicates
44         # Using cache manifold-tables to get the list of authorities faster
45         authorities_query = Query.get('authority').select('name', 'authority_hrn')
46         authorities = execute_admin_query(request, authorities_query)
47         if authorities is not None:
48             authorities = sorted(authorities)
49         root_authorities = sorted([a for a in authorities if '.' not in a['authority_hrn']])
50
51         page = Page(request)
52         page.add_js_files  ( [ "js/jquery.validate.js", "js/join.js", "js/jquery.qtip.min.js" ] )
53         page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css" ] )
54         page.add_css_files ( [ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
55
56         if method == 'POST':
57             # xxx tocheck - if authorities is empty, it's no use anyway
58             # (users won't be able to validate the form anyway)
59     
60             # List local users in Manifold DB in order ot avoid duplicates
61             user_query  = Query().get('local:user').select('user_id','email')
62             list_users = execute_admin_query(self.request, user_query)
63    
64             reg_root_authority_hrn = request.POST.get('root_authority_hrn', '').lower()
65
66             reg_site_name = request.POST.get('site_name', '')
67             reg_site_authority = request.POST.get('site_authority', '').lower()
68             reg_site_abbreviated_name = request.POST.get('site_abbreviated_name', '').lower()
69             reg_site_url = request.POST.get('site_url', '')
70             reg_site_latitude = request.POST.get('site_latitude', '')
71             reg_site_longitude = request.POST.get('site_longitude', '')
72
73             reg_fname  = request.POST.get('pi_first_name', '')
74             reg_lname  = request.POST.get('pi_last_name', '')
75             reg_auth   = 'onelab.' + reg_site_abbreviated_name   
76             reg_email  = request.POST.get('pi_email','').lower()
77             reg_phone  = request.POST.get('pi_phone','')
78             #prepare user_hrn 
79             split_email = reg_email.split("@")[0] 
80             split_email = split_email.replace(".", "_")
81             # Replace + by _ => more convenient for testing and validate with a real email
82             split_email = split_email.replace("+", "_")
83             user_hrn = reg_auth + '.' + split_email
84             
85             UserModel = get_user_model()
86             
87             reg_address_line1 = request.POST.get('address_line1', '')
88             reg_address_line2 = request.POST.get('address_line2', '')
89             reg_address_line3 = request.POST.get('address_line3', '')
90             reg_address_city = request.POST.get('address_city', '')
91             reg_address_postalcode = request.POST.get('address_postalcode', '')
92             reg_address_state = request.POST.get('address_state', '')
93             reg_address_country = request.POST.get('address_country', '')
94
95             #POST value validation  
96             if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
97                 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
98             if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
99                 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
100             if (re.search(r'^[A-Za-z0-9_ ]*$', reg_site_name) == None):
101                 errors.append('Name of organization  may contain only letters, numbers, and underscore.')
102             if (re.search(r'^[A-Za-z ]*$', reg_address_city) == None):
103                 errors.append('City may contain only letters.')
104             if (re.search(r'^[A-Za-z ]*$', reg_address_country) == None):
105                 errors.append('Country may contain only letters.')
106             if (re.search(r'^[A-Za-z0-9]*$', reg_site_abbreviated_name) == None):
107                 errors.append('Shortname  may contain only letters and numbers')
108             if (re.search(r'^[0-9]*$', reg_phone) == None):
109                 errors.append('Phone number may contain only numbers.')
110             #if (re.search(r'^\w+$', reg_site_authority) == None):
111             #    errors.append('Site Authority may contain only letters or numbers.')
112             # checking in django_db !!
113             if PendingUser.objects.filter(email__iexact=reg_email):
114                 errors.append('Email is pending for validation. Please provide a new email address.')
115             if PendingAuthority.objects.filter(site_abbreviated_name__iexact=reg_site_abbreviated_name):
116                 errors.append('This site is pending for validation.')
117             #if PendingAuthority.objects.filter(site_name__iexact=reg_site_name):
118             #    errors.append('This site is pending for validation.')
119
120             if UserModel._default_manager.filter(email__iexact=reg_email): 
121                 errors.append('This email is not usable. Please contact the administrator or try with another email.')
122             for user_detail in list_users:
123                 if user_detail['email']==reg_email:
124                     errors.append('Email already registered in Manifold. Please provide a new email address.')
125
126 # XXX TODO: Factorize with portal/accountview.py
127 # XXX TODO: Factorize with portal/registrationview.py
128 # XXX TODO: Factorize with portal/joinview.py
129 #            if 'generate' in request.POST['question']:
130             from Crypto.PublicKey import RSA
131             private = RSA.generate(1024)
132             private_key = private.exportKey()
133             public_key = private.publickey().exportKey(format='OpenSSH')
134             # Saving to DB
135             auth_type = 'managed'
136
137             if not errors:
138                 reg_password = request.POST['pi_password']
139                 a = PendingAuthority(
140                     site_name             = reg_site_name,             
141                     site_authority        = reg_auth, 
142                     site_abbreviated_name = reg_site_abbreviated_name, 
143                     site_url              = reg_site_url,
144                     site_latitude         = reg_site_latitude, 
145                     site_longitude        = reg_site_longitude,
146                     address_line1         = reg_email, # XXX field name must be renamed. Email needed 4 rejection email.
147                     address_line2         = reg_address_line2,
148                     address_line3         = reg_address_line3,
149                     address_city          = reg_address_city,
150                     address_postalcode    = reg_address_postalcode,
151                     address_state         = reg_address_state,
152                     address_country       = reg_address_country,
153                     authority_hrn         = reg_root_authority_hrn,
154                 )
155                 a.save()
156  
157                 reg_password = request.POST['pi_password']
158                 salt = randint(1,100000)
159                 # get the domain url
160                 current_site = Site.objects.get_current()
161                 current_site = current_site.domain
162
163                 email_hash = md5(str(salt)+reg_email).hexdigest()
164                 user_request = {
165                     'first_name'    : reg_fname,
166                     'last_name'     : reg_lname,
167                     'organization'  : reg_site_name,
168                     'authority_hrn' : reg_auth,
169                     'email'         : reg_email,
170                     'password'      : reg_password,
171                     'public_key'    : public_key,
172                     'private_key'   : private_key,
173                     'current_site'  : current_site,
174                     'email_hash'    : email_hash,
175                     'user_hrn'      : user_hrn,
176                     'pi'            : [reg_auth],
177                     'auth_type'     : 'managed',
178                     'validation_link': current_site + '/portal/email_activation/'+ email_hash
179                 }
180
181                 
182                 create_pending_user(request, user_request, user_detail)
183                 # saves the user to django auth_user table [needed for password reset]
184                 #user = User.objects.create_user(reg_email, reg_email, reg_password)
185
186                 #creating user to manifold local:user
187                 #user_config = '{"first_name":"'+ reg_fname + '", "last_name":"'+ reg_lname + '", "authority_hrn":"'+ reg_auth + '"}'
188                 #user_params = {'email': reg_email, 'password': reg_password, 'config': user_config, 'status': 1}
189                 #manifold_add_user(request,user_params)
190                 #creating local:account in manifold
191                 #user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
192                 #account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
193                 #manifold_add_account(request,account_params)
194
195                 # Send email
196                 try: 
197                     ctx = {
198                         'site_name'             : reg_site_name,             
199                         'authority_hrn'         : reg_root_authority_hrn + '.' + reg_site_authority,
200                         'site_abbreviated_name' : reg_site_abbreviated_name, 
201                         'site_url'              : reg_site_url,
202                         'address_city'          : reg_address_city,
203                         'address_country'       : reg_address_country,
204                         'first_name'            : reg_fname, 
205                         'last_name'             : reg_lname, 
206                         'authority_hrn'         : reg_auth,
207                         'email'                 : reg_email,
208                         'user_hrn'              : user_hrn,
209                         'public_key'            : public_key,
210                         }
211
212                     #recipients = authority_get_pi_emails(request,reg_auth)
213                     
214                     self.template_name = 'authority_request_email.html'
215                     html_content = render_to_string(self.template, ctx)
216             
217                     self.template_name = 'authority_request_email.txt'
218                     text_content = render_to_string(self.template, ctx)
219             
220                     self.template_name = 'authority_request_email_subject.txt'
221                     subject = render_to_string(self.template, ctx)
222                     subject = subject.replace('\n', '')
223             
224                     #theme.template_name = 'email_default_sender.txt'
225                     #sender =  render_to_string(theme.template, ctx)
226                     #sender = sender.replace('\n', '')
227                     sender = reg_email
228                     
229                     msg = EmailMultiAlternatives(subject, text_content, sender, ['support@onelab.eu'])
230                     msg.attach_alternative(html_content, "text/html")
231                     msg.send()
232     
233                 except Exception, e:
234                     print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
235                     import traceback
236                     traceback.print_exc()
237
238                 self.template_name = 'join_complete.html'
239                 # log institution activity
240                 activity.institution.joined(self.request)
241                 return render(request, self.template, {'theme': self.theme})
242                 #return render(request, 'user_register_complete.html') 
243
244         template_env = {
245           'topmenu_items': topmenu_items_live('join', page),
246           'errors': errors,
247           'pi_first_name': request.POST.get('pi_first_name', ''),
248           'pi_last_name': request.POST.get('pi_last_name', ''),
249           'pi_email': request.POST.get('pi_email', ''),
250           'pi_phone': request.POST.get('pi_phone', ''),
251           'pi_password': request.POST.get('pi_password', ''),           
252           'site_name': request.POST.get('site_name', ''),
253           'site_authority': request.POST.get('site_authority', '').lower(),
254           'site_abbreviated_name': request.POST.get('site_abbreviated_name', ''),
255           'site_url': request.POST.get('site_url', ''),
256           'site_latitude': request.POST.get('site_latitude', ''),
257           'site_longitude': request.POST.get('site_longitude', ''),
258           'address_line1': request.POST.get('address_line1', ''),
259           'address_line2': request.POST.get('address_line2', ''),
260           'address_line3': request.POST.get('address_line3', ''),
261           'address_city': request.POST.get('address_city', ''),
262           'address_postalcode': request.POST.get('address_postalcode', ''),
263           'address_state': request.POST.get('address_state', ''),
264           'address_country': request.POST.get('address_country', ''),
265           'root_authority_hrn': request.POST.get('root_authority_hrn', '').lower(),
266           'root_authorities': root_authorities,
267           'authorities': authorities,
268           'theme': self.theme
269           }
270         template_env.update(page.prelude_env ())
271         # log institution activity
272         activity.institution.join(self.request)
273         return render(request, 'join_view.html',template_env)