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