AiC and REST login
[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
13 from unfold.page                import Page
14 from unfold.loginrequired       import FreeAccessView
15 from ui.topmenu                 import topmenu_items_live
16
17 from manifoldapi.manifoldapi    import execute_admin_query
18 from manifold.core.query        import Query
19
20 from portal.models              import PendingUser,PendingAuthority
21 from portal.actions             import authority_get_pi_emails, manifold_add_user,manifold_add_account, create_pending_user
22
23 from myslice.theme import ThemeView
24 from myslice.settings import logger
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
158                 if request.is_secure():
159                     current_site = 'https://'
160                 else:
161                     current_site = 'http://'
162                 current_site += request.META['HTTP_HOST']
163
164                 email_hash = md5(str(salt)+reg_email).hexdigest()
165                 user_request = {
166                     'first_name'    : reg_fname,
167                     'last_name'     : reg_lname,
168                     'organization'  : reg_site_name,
169                     'authority_hrn' : reg_auth,
170                     'email'         : reg_email,
171                     'password'      : reg_password,
172                     'public_key'    : public_key,
173                     'private_key'   : private_key,
174                     'current_site'  : current_site,
175                     'email_hash'    : email_hash,
176                     'user_hrn'      : user_hrn,
177                     'pi'            : [reg_auth],
178                     'auth_type'     : 'managed',
179                     'validation_link': current_site + '/portal/email_activation/'+ email_hash
180                 }
181
182                 
183                 create_pending_user(request, user_request, user_detail)
184                 # saves the user to django auth_user table [needed for password reset]
185                 #user = User.objects.create_user(reg_email, reg_email, reg_password)
186
187                 #creating user to manifold local:user
188                 #user_config = '{"first_name":"'+ reg_fname + '", "last_name":"'+ reg_lname + '", "authority_hrn":"'+ reg_auth + '"}'
189                 #user_params = {'email': reg_email, 'password': reg_password, 'config': user_config, 'status': 1}
190                 #manifold_add_user(request,user_params)
191                 #creating local:account in manifold
192                 #user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
193                 #account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
194                 #manifold_add_account(request,account_params)
195
196                 # Send email
197                 try: 
198                     ctx = {
199                         'site_name'             : reg_site_name,             
200                         'authority_hrn'         : reg_root_authority_hrn + '.' + reg_site_authority,
201                         'site_abbreviated_name' : reg_site_abbreviated_name, 
202                         'site_url'              : reg_site_url,
203                         'address_city'          : reg_address_city,
204                         'address_country'       : reg_address_country,
205                         'first_name'            : reg_fname, 
206                         'last_name'             : reg_lname, 
207                         'authority_hrn'         : reg_auth,
208                         'email'                 : reg_email,
209                         'user_hrn'              : user_hrn,
210                         'public_key'            : public_key,
211                         }
212
213                     #recipients = authority_get_pi_emails(request,reg_auth)
214                     
215                     self.template_name = 'authority_request_email.html'
216                     html_content = render_to_string(self.template, ctx)
217             
218                     self.template_name = 'authority_request_email.txt'
219                     text_content = render_to_string(self.template, ctx)
220             
221                     self.template_name = 'authority_request_email_subject.txt'
222                     subject = render_to_string(self.template, ctx)
223                     subject = subject.replace('\n', '')
224             
225                     #theme.template_name = 'email_default_sender.txt'
226                     #sender =  render_to_string(theme.template, ctx)
227                     #sender = sender.replace('\n', '')
228                     sender = reg_email
229                     
230                     msg = EmailMultiAlternatives(subject, text_content, sender, ['support@onelab.eu'])
231                     msg.attach_alternative(html_content, "text/html")
232                     msg.send()
233     
234                 except Exception, e:
235                     logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
236                     import traceback
237                     logger.error(traceback.format_exc())
238
239                 self.template_name = 'join_complete.html'
240                 # log institution activity
241                 activity.institution.joined(self.request)
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         # log institution activity
273         activity.institution.join(self.request)
274         return render(request, 'join_view.html',template_env)