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