d28daba9442f5544bf239a5fa7a99f1cb291e5be
[myslice.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'^[A-Za-z0-9_ ]*$', reg_site_name) == None):
97                 errors.append('Name of organization  may contain only letters, numbers, and underscore.')
98             if (re.search(r'^[A-Za-z ]*$', reg_address_city) == None):
99                 errors.append('City may contain only letters.')
100             if (re.search(r'^[A-Za-z ]*$', reg_address_country) == None):
101                 errors.append('Country may contain only letters.')
102             if (re.search(r'^[A-Za-z0-9]*$', reg_site_abbreviated_name) == None):
103                 errors.append('Shortname  may contain only letters and numbers')
104             if (re.search(r'^[0-9]*$', reg_phone) == None):
105                 errors.append('Phone number may contain only numbers.')
106             #if (re.search(r'^\w+$', reg_site_authority) == None):
107             #    errors.append('Site Authority may contain only letters or numbers.')
108             # checking in django_db !!
109             if PendingUser.objects.filter(email__iexact=reg_email):
110                 errors.append('Email is pending for validation. Please provide a new email address.')
111             if PendingAuthority.objects.filter(site_abbreviated_name__iexact=reg_site_abbreviated_name):
112                 errors.append('This site is pending for validation.')
113             #if PendingAuthority.objects.filter(site_name__iexact=reg_site_name):
114             #    errors.append('This site is pending for validation.')
115
116             if UserModel._default_manager.filter(email__iexact=reg_email): 
117                 errors.append('This email is not usable. Please contact the administrator or try with another email.')
118             for user_detail in list_users:
119                 if user_detail['email']==reg_email:
120                     errors.append('Email already registered in Manifold. Please provide a new email address.')
121
122 # XXX TODO: Factorize with portal/accountview.py
123 # XXX TODO: Factorize with portal/registrationview.py
124 # XXX TODO: Factorize with portal/joinview.py
125 #            if 'generate' in request.POST['question']:
126             from Crypto.PublicKey import RSA
127             private = RSA.generate(1024)
128             private_key = private.exportKey()
129             public_key = private.publickey().exportKey(format='OpenSSH')
130             # Saving to DB
131             auth_type = 'managed'
132
133             if not errors:
134                 reg_password = request.POST['pi_password']
135                 a = PendingAuthority(
136                     site_name             = reg_site_name,             
137                     site_authority        = reg_auth, 
138                     site_abbreviated_name = reg_site_abbreviated_name, 
139                     site_url              = reg_site_url,
140                     site_latitude         = reg_site_latitude, 
141                     site_longitude        = reg_site_longitude,
142                     address_line1         = reg_address_line1,
143                     address_line2         = reg_address_line2,
144                     address_line3         = reg_address_line3,
145                     address_city          = reg_address_city,
146                     address_postalcode    = reg_address_postalcode,
147                     address_state         = reg_address_state,
148                     address_country       = reg_address_country,
149                     authority_hrn         = reg_root_authority_hrn,
150                 )
151                 a.save()
152  
153                 reg_password = request.POST['pi_password']
154                 salt = randint(1,100000)
155                 # get the domain url
156                 current_site = Site.objects.get_current()
157                 current_site = current_site.domain
158
159                 email_hash = md5(str(salt)+reg_email).hexdigest()
160                 user_request = {
161                     'first_name'    : reg_fname,
162                     'last_name'     : reg_lname,
163                     'organization'  : reg_site_name,
164                     'authority_hrn' : reg_auth,
165                     'email'         : reg_email,
166                     'password'      : reg_password,
167                     'public_key'    : public_key,
168                     'private_key'   : private_key,
169                     'current_site'  : current_site,
170                     'email_hash'    : email_hash,
171                     'user_hrn'      : user_hrn,
172                     'pi'            : [reg_auth],
173                     'auth_type'     : 'managed',
174                     'validation_link': 'http://' + current_site + '/portal/email_activation/'+ email_hash
175                 }
176
177                 
178                 create_pending_user(request, user_request, user_detail)
179                 # saves the user to django auth_user table [needed for password reset]
180                 #user = User.objects.create_user(reg_email, reg_email, reg_password)
181
182                 #creating user to manifold local:user
183                 #user_config = '{"first_name":"'+ reg_fname + '", "last_name":"'+ reg_lname + '", "authority_hrn":"'+ reg_auth + '"}'
184                 #user_params = {'email': reg_email, 'password': reg_password, 'config': user_config, 'status': 1}
185                 #manifold_add_user(request,user_params)
186                 #creating local:account in manifold
187                 #user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
188                 #account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
189                 #manifold_add_account(request,account_params)
190
191                 # Send email
192                 try: 
193                     ctx = {
194                         'site_name'             : reg_site_name,             
195                         'authority_hrn'         : reg_root_authority_hrn + '.' + reg_site_authority,
196                         'site_abbreviated_name' : reg_site_abbreviated_name, 
197                         'site_url'              : reg_site_url,
198                         'site_latitude'         : reg_site_latitude, 
199                         'site_longitude'        : reg_site_longitude,
200                         'address_line1'         : reg_address_line1,
201                         'address_line2'         : reg_address_line2,
202                         'address_line3'         : reg_address_line3,
203                         'address_city'          : reg_address_city,
204                         'address_postalcode'    : reg_address_postalcode,
205                         'address_state'         : reg_address_state,
206                         'address_country'       : reg_address_country,
207                         'first_name'            : reg_fname, 
208                         'last_name'             : reg_lname, 
209                         'authority_hrn'         : reg_auth,
210                         'email'                 : reg_email,
211                         'user_hrn'              : user_hrn,
212                         'public_key'            : public_key,
213                         }
214                     recipients = authority_get_pi_emails(request,reg_auth)
215                     
216                     # We don't need to send this email to user.
217                     # it's for the PI only
218                     #if ctx['cc_myself']:
219                     #    recipients.append(ctx['email'])
220                     theme.template_name = 'authority_request_email.html'
221                     html_content = render_to_string(theme.template, ctx)
222             
223                     theme.template_name = 'authority_request_email.txt'
224                     text_content = render_to_string(theme.template, ctx)
225             
226                     theme.template_name = 'authority_request_email_subject.txt'
227                     subject = render_to_string(theme.template, ctx)
228                     subject = subject.replace('\n', '')
229             
230                     theme.template_name = 'email_default_sender.txt'
231                     sender =  render_to_string(theme.template, ctx)
232                     sender = sender.replace('\n', '')
233             
234                     msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
235                     msg.attach_alternative(html_content, "text/html")
236                     msg.send()
237     
238                 except Exception, e:
239                     print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
240                 
241                 self.template_name = 'join_complete.html'
242                 return render(request, self.template, {'theme': self.theme})
243                 #return render(request, 'user_register_complete.html') 
244
245         template_env = {
246           'topmenu_items': topmenu_items_live('join', page),
247           'errors': errors,
248           'pi_first_name': request.POST.get('pi_first_name', ''),
249           'pi_last_name': request.POST.get('pi_last_name', ''),
250           'pi_email': request.POST.get('pi_email', ''),
251           'pi_phone': request.POST.get('pi_phone', ''),
252           'pi_password': request.POST.get('pi_password', ''),           
253           'site_name': request.POST.get('site_name', ''),
254           'site_authority': request.POST.get('site_authority', '').lower(),
255           'site_abbreviated_name': request.POST.get('site_abbreviated_name', ''),
256           'site_url': request.POST.get('site_url', ''),
257           'site_latitude': request.POST.get('site_latitude', ''),
258           'site_longitude': request.POST.get('site_longitude', ''),
259           'address_line1': request.POST.get('address_line1', ''),
260           'address_line2': request.POST.get('address_line2', ''),
261           'address_line3': request.POST.get('address_line3', ''),
262           'address_city': request.POST.get('address_city', ''),
263           'address_postalcode': request.POST.get('address_postalcode', ''),
264           'address_state': request.POST.get('address_state', ''),
265           'address_country': request.POST.get('address_country', ''),
266           'root_authority_hrn': request.POST.get('root_authority_hrn', '').lower(),
267           'root_authorities': root_authorities,
268           'authorities': authorities,
269           'theme': self.theme
270           }
271         template_env.update(page.prelude_env ())
272         return render(request, 'join_view.html',template_env)