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