Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
[myslice.git] / portal / registrationview.py
1 import os.path, re
2 import json
3 from random     import randint
4 from hashlib    import md5
5
6 from django.views.generic       import View
7 from django.template.loader     import render_to_string
8
9 from django.shortcuts           import render
10 from django.contrib.auth        import get_user_model
11 from django.contrib.sites.models import Site
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
21 from portal.actions             import create_pending_user
22
23 from myslice.theme import ThemeView
24
25 import activity.user
26
27 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
28 # so let's override 'get' and 'post' instead
29 #
30 class RegistrationView (FreeAccessView, ThemeView):
31     template_name = 'registration_view.html'
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, wsgi_request, method):
40         """
41         """
42         errors = []
43         authority_hrn = None
44         authorities_query = Query.get('authority').select('name', 'authority_hrn')
45         authorities = execute_admin_query(wsgi_request, authorities_query)
46         if authorities is not None:
47             authorities = sorted(authorities)
48         
49         print "############ BREAKPOINT 1 #################"
50         # Page rendering
51         page = Page(wsgi_request)
52         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/jquery.qtip.min.js","js/jquery-ui.js" ] )
53         page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css" ] )
54         page.add_css_files ( [ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
55         print "############ BREAKPOINT 2 #################"
56         if method == 'POST':
57             reg_form = {}
58             # The form has been submitted
59             
60             # get the domain url
61             current_site = Site.objects.get_current()
62             current_site = current_site.domain
63             
64             print "############ BREAKPOINT 3 #################"
65             
66             for authority in authorities:
67                 if authority['name'] == wsgi_request.POST.get('org_name', ''):
68                     authority_hrn = authority['authority_hrn']     
69
70             # Handle the case when the template uses only hrn and not name
71             if authority_hrn is None:
72                 authority_hrn = wsgi_request.POST.get('org_name', '')
73             
74             print "############ BREAKPOINT 4 #################"
75             
76             post_email = wsgi_request.POST.get('email','').lower()
77             salt = randint(1,100000)
78             email_hash = md5(str(salt)+post_email).hexdigest()
79             #email_hash = md5(post_email).digest().encode('base64')[:-1]
80             user_request = {
81                 'first_name'    : wsgi_request.POST.get('firstname',     ''),
82                 'last_name'     : wsgi_request.POST.get('lastname',      ''),
83                 'organization'  : wsgi_request.POST.get('org_name', ''),
84                 'authority_hrn' : authority_hrn, 
85                 'email'         : post_email,
86                 'password'      : wsgi_request.POST.get('password',      ''),
87                 'current_site'  : current_site,
88                 'email_hash'    : email_hash,
89                 'pi'            : '',
90                 'validation_link': 'http://' + current_site + '/portal/email_activation/'+ email_hash
91             }
92             
93             print "############ BREAKPOINT 5 #################"
94             
95             # Construct user_hrn from email (XXX Should use common code)
96             split_email = user_request['email'].split("@")[0] 
97             split_email = split_email.replace(".", "_")
98             # Replace + by _ => more convenient for testing and validate with a real email
99             split_email = split_email.replace("+", "_")
100             user_request['user_hrn'] = user_request['authority_hrn'] \
101                      + '.' + split_email
102             
103             # Validate input
104             UserModel = get_user_model()
105             if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
106                 errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
107             if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
108                 errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
109             # Does the user exist in Manifold?
110             user_query  = Query().get('local:user').select('user_id','email')
111             user_details = execute_admin_query(wsgi_request, user_query)
112             for user_detail in user_details:
113                 if user_detail['email'] == user_request['email']:
114                     errors.append('Email already registered. <a href="/">Login</a> with your existing account. <a href="/portal/pass_reset/">Forgot your password?</a>')
115
116             # Does the user exist in sfa? [query is very slow!!]
117             #user_query  = Query().get('user').select('user_hrn','user_email')
118             # XXX Test based on the user_hrn is quick
119             user_query  = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
120             user_details_sfa = execute_admin_query(wsgi_request, user_query)
121
122             for user in user_details_sfa:
123                 if user['user_email'] == user_request['email']:
124                     errors.append('Email already registered in OneLab registry. <a href="/contact">Contact OneLab support</a> or use another email.')
125                 if user['user_hrn'] == user_request['user_hrn']:
126                     # add random number if user_hrn already exists in the registry
127                     user_request['user_hrn'] = user_request['authority_hrn'] \
128                             + '.' + split_email + str(randint(1,1000000))
129
130             # checking in django unfold db portal application pending users
131             # sqlite3 /var/unfold/unfold.sqlite3
132             # select email from portal_pendinguser;
133             if PendingUser.objects.filter(email__iexact = user_request['email']):
134                 errors.append('Account pending for validation. Please wait till your account is validated or contact OneLab support.')
135
136             # checking in django_db !!
137             # sqlite3 /var/unfold/unfold.sqlite3
138             # select email from auth_user;
139             if UserModel._default_manager.filter(email__iexact = user_request['email']): 
140                 errors.append('<a href="/contact">Contact OneLab support</a> or try with another email.')
141
142             # XXX TODO: Factorize with portal/accountview.py
143             # XXX TODO: Factorize with portal/registrationview.py
144             # XXX TODO: Factorize with portal/joinview.py
145             if 'generate' in wsgi_request.POST['question']:
146                 user_request['auth_type'] = 'managed'
147
148                 # XXX Common code, dependency ?
149                 from Crypto.PublicKey import RSA
150                 private = RSA.generate(1024)
151
152                 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
153                 # Example: public_key = 'ssh-rsa AAAAB3...'
154                 user_request['private_key'] = private.exportKey()
155                 user_request['public_key']  = private.publickey().exportKey(format='OpenSSH')
156
157             else: 
158                 user_request['auth_type'] = 'user'
159
160                 up_file        = wsgi_request.FILES['user_public_key']
161
162                 file_content   = up_file.read().strip()
163                 file_name      = up_file.name
164                 file_extension = os.path.splitext(file_name)[1]
165
166                 ALLOWED_EXTENSIONS =  ['.pub','.txt']
167                 if file_extension not in ALLOWED_EXTENSIONS or not re.search(r'ssh-rsa',file_content):
168                     errors.append('Please upload a valid RSA public key.')
169                 # user_request['private_key'] can't be Null because all db fields are set as NOT NULL
170                 user_request['private_key'] = ""
171                 user_request['public_key']  = file_content
172                 
173             if not errors:
174                 create_pending_user(wsgi_request, user_request, user_detail)
175                 self.template_name = 'user_register_complete.html'
176                 # log user activity
177                 activity.user.registered(self.request)
178                 return render(wsgi_request, self.template, {'theme': self.theme}) 
179
180         else:
181             print "############ BREAKPOINT A #################"
182             user_request = {}
183             ## this is coming from onelab website onelab.eu
184             reg_form = {
185                 'first_name':  wsgi_request.GET.get('first_name', ''),
186                 'last_name': wsgi_request.GET.get('last_name', ''),
187                 'email': wsgi_request.GET.get('email', ''),
188                 }
189             # log user activity
190             activity.user.signup(self.request)
191             print "############ BREAKPOINT B #################"
192
193         template_env = {
194           'topmenu_items': topmenu_items_live('Register', page),
195           'errors': errors,
196           'authorities': authorities,
197           'theme': self.theme
198           }
199         template_env.update(user_request)
200         template_env.update(reg_form)
201         template_env.update(page.prelude_env ())
202         print "############ BREAKPOINT C #################"
203         return render(wsgi_request, self.template,template_env)