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