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 from django.shortcuts           import render
9 from django.contrib.auth        import get_user_model
10 from django.contrib.sites.models import Site
11
12 from unfold.page                import Page
13 from unfold.loginrequired       import FreeAccessView
14 from ui.topmenu                 import topmenu_items_live
15
16 from manifoldapi.manifoldapi    import execute_admin_query
17 from manifold.core.query        import Query
18
19 from portal.models              import PendingUser
20 from portal.actions             import create_pending_user
21
22 from myslice.theme import ThemeView
23
24 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
25 # so let's override 'get' and 'post' instead
26 #
27 class RegistrationView (FreeAccessView, ThemeView):
28     template_name = 'registration_view.html'
29     
30     def post (self, request):
31         return self.get_or_post (request, 'POST')
32
33     def get (self, request):
34         return self.get_or_post (request, 'GET')
35
36     def get_or_post(self, wsgi_request, method):
37         """
38         """
39         errors = []
40
41         authorities_query = Query.get('authority').select('name', 'authority_hrn')
42         authorities = execute_admin_query(wsgi_request, authorities_query)
43         if authorities is not None:
44             authorities = sorted(authorities)
45         
46         # Page rendering
47         page = Page(wsgi_request)
48         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/jquery.qtip.min.js","js/jquery-ui.js" ] )
49         page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css" ] )
50         page.add_css_files ( [ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
51
52         if method == 'POST':
53             reg_form = {}
54             # The form has been submitted
55             
56             # get the domain url
57             current_site = Site.objects.get_current()
58             current_site = current_site.domain
59
60             authorities_query = Query.get('authority').select('name', 'authority_hrn')
61             authorities = execute_admin_query(wsgi_request, authorities_query)
62     
63             for authority in authorities:
64                 if authority['name'] == wsgi_request.POST.get('org_name', ''):
65                     authority_hrn = authority['authority_hrn']     
66
67             post_email = wsgi_request.POST.get('email','').lower()
68             salt = randint(1,100000)
69             email_hash = md5(str(salt)+post_email).hexdigest()
70             #email_hash = md5(post_email).digest().encode('base64')[:-1]
71             user_request = {
72                 'first_name'    : wsgi_request.POST.get('firstname',     ''),
73                 'last_name'     : wsgi_request.POST.get('lastname',      ''),
74                 'organization'  : wsgi_request.POST.get('org_name', ''),
75                 'authority_hrn' : authority_hrn, 
76                 'email'         : post_email,
77                 'password'      : wsgi_request.POST.get('password',      ''),
78                 'current_site'  : current_site,
79                 'email_hash'    : email_hash,
80                 'validation_link': 'http://' + current_site + '/portal/email_activation/'+ email_hash
81             }
82
83             # Construct user_hrn from email (XXX Should use common code)
84             split_email = user_request['email'].split("@")[0] 
85             split_email = split_email.replace(".", "_")
86             user_request['user_hrn'] = user_request['authority_hrn'] \
87                      + '.' + split_email
88             
89             # Validate input
90             UserModel = get_user_model()
91             if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
92                 errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
93             if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
94                 errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
95             # checking in django_db !!
96             if PendingUser.objects.filter(email__iexact = user_request['email']):
97                 errors.append('Email is pending for validation. Please provide a new email address.')
98             if UserModel._default_manager.filter(email__iexact = user_request['email']): 
99                 errors.append('This email is not usable. Please contact the administrator or try with another email.')
100             # Does the user exist in Manifold?
101             user_query  = Query().get('local:user').select('user_id','email')
102             user_details = execute_admin_query(wsgi_request, user_query)
103             for user_detail in user_details:
104                 if user_detail['email'] == user_request['email']:
105                     errors.append('Email already registered in Manifold. Please provide a new email address.')
106             # Does the user exist in sfa? [query is very slow!!]
107             #user_query  = Query().get('user').select('user_hrn','user_email')
108             # XXX Test based on the user_hrn is quick
109             user_query  = Query().get('user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
110             user_details_sfa = execute_admin_query(wsgi_request, user_query)
111
112             for user in user_details_sfa:
113                 if user['user_email'] == user_request['email']:
114                     errors.append('Email already registered in SFA registry. Please use another email.')
115                 if user['user_hrn'] == user_request['user_hrn']:
116                     # add random number if user_hrn already exists in the registry
117                     user_request['user_hrn'] = user_request['authority_hrn'] \
118                             + '.' + split_email + str(randint(1,1000000))
119                 
120             # XXX TODO: Factorize with portal/accountview.py
121             if 'generate' in wsgi_request.POST['question']:
122                 user_request['auth_type'] = 'managed'
123
124                 # XXX Common code, dependency ?
125                 from Crypto.PublicKey import RSA
126                 private = RSA.generate(1024)
127
128                 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
129                 # Example: public_key = 'ssh-rsa AAAAB3...'
130                 user_request['private_key'] = private.exportKey()
131                 user_request['public_key']  = private.publickey().exportKey(format='OpenSSH')
132
133             else: 
134                 user_request['auth_type'] = 'user'
135
136                 up_file        = wsgi_request.FILES['user_public_key']
137
138                 file_content   = up_file.read().strip()
139                 file_name      = up_file.name
140                 file_extension = os.path.splitext(file_name)[1]
141
142                 ALLOWED_EXTENSIONS =  ['.pub','.txt']
143                 if file_extension not in ALLOWED_EXTENSIONS or not re.search(r'ssh-rsa',file_content):
144                     errors.append('Please upload a valid RSA public key.')
145
146                 user_request['private_key'] = None
147                 user_request['public_key']  = file_content
148                 
149             if not errors:
150                 create_pending_user(wsgi_request, user_request, user_detail)
151                 self.template_name = 'user_register_complete.html'
152                 return render(wsgi_request, self.template, {'theme': self.theme}) 
153
154         else:
155             user_request = {}
156             ## this is coming from onelab website onelab.eu
157             reg_form = {
158                 'first_name':  wsgi_request.GET.get('first_name', ''),
159                 'last_name': wsgi_request.GET.get('last_name', ''),
160                 'email': wsgi_request.GET.get('email', ''),
161                 }
162
163         template_env = {
164           'topmenu_items': topmenu_items_live('Register', page),
165           'errors': errors,
166           'authorities': authorities,
167           'theme': self.theme
168           }
169         template_env.update(user_request)
170         template_env.update(reg_form)
171         template_env.update(page.prelude_env ())
172         return render(wsgi_request, self.template,template_env)