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