4 from random import randint
5 from hashlib import md5
7 from django.views.generic import View
8 from django.template.loader import render_to_string
10 from django.shortcuts import render
11 from django.contrib.auth import get_user_model
13 from unfold.page import Page
14 from unfold.loginrequired import FreeAccessView
15 from ui.topmenu import topmenu_items_live
17 from manifoldapi.manifoldapi import execute_admin_query
18 from manifold.core.query import Query
20 from portal.models import PendingUser
21 from portal.actions import create_pending_user
23 from myslice.theme import ThemeView
24 from myslice.settings import logger
28 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
29 # so let's override 'get' and 'post' instead
31 class RegistrationView (FreeAccessView, ThemeView):
32 template_name = 'registration_view.html'
34 def post (self, request):
35 return self.get_or_post (request, 'POST')
37 def get (self, request):
38 return self.get_or_post (request, 'GET')
40 def get_or_post(self, wsgi_request, method):
45 # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
46 authorities_query = Query.get('authority').select('name', 'authority_hrn')
47 authorities = execute_admin_query(wsgi_request, authorities_query)
48 logger.info("RegistrationView authorities = {}".format(authorities))
49 if authorities is not None:
50 # Remove the root authority from the list
51 matching = [s for s in authorities if "." in s['authority_hrn']]
52 authorities = sorted(matching, key=lambda k: k['authority_hrn'])
53 authorities = sorted(matching, key=lambda k: k['name'])
55 logger.debug("############ BREAKPOINT 1 #################")
57 page = Page(wsgi_request)
59 page.add_css_files ( [ "https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" ] )
61 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/jquery.qtip.min.js","js/jquery-ui.js","js/jquery-ui-combobox.js" ] )
63 page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css", "css/jquery.ui.combobox.css" ] )
64 page.expose_js_metadata()
65 logger.debug("############ BREAKPOINT 2 #################")
68 # The form has been submitted
70 if wsgi_request.is_secure():
71 current_site = 'https://'
73 current_site = 'http://'
74 current_site += wsgi_request.META['HTTP_HOST']
77 logger.debug("############ BREAKPOINT 3 #################")
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]
83 'first_name' : wsgi_request.POST.get('firstname', ''),
84 'last_name' : wsgi_request.POST.get('lastname', ''),
85 'authority_hrn' : wsgi_request.POST.get('org_name', ''),
87 'password' : wsgi_request.POST.get('password', ''),
88 'current_site' : current_site,
89 'email_hash' : email_hash,
91 'validation_link': current_site + '/portal/email_activation/'+ email_hash
94 logger.debug("############ BREAKPOINT 4 #################")
95 auth = wsgi_request.POST.get('org_name', None)
96 if auth is None or auth == "":
97 errors.append('Organization required: please select one or request its addition')
100 logger.debug("############ BREAKPOINT 5 #################")
102 # Construct user_hrn from email (XXX Should use common code)
103 split_email = user_request['email'].split("@")[0]
104 split_email = split_email.replace(".", "_")
105 # Replace + by _ => more convenient for testing and validate with a real email
106 split_email = split_email.replace("+", "_")
107 user_request['user_hrn'] = user_request['authority_hrn'] \
111 UserModel = get_user_model()
112 if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
113 errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
114 if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
115 errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
116 # Does the user exist in Manifold?
117 user_query = Query().get('local:user').select('user_id','email')
118 user_details = execute_admin_query(wsgi_request, user_query)
119 for user_detail in user_details:
120 if user_detail['email'] == user_request['email']:
121 errors.append('Email already registered. <a href="/">Login</a> with your existing account. <a href="/portal/pass_reset/">Forgot your password?</a>')
123 # Does the user exist in sfa? [query is very slow!!]
124 #user_query = Query().get('user').select('user_hrn','user_email')
125 # XXX Test based on the user_hrn is quick
127 # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
128 user_query = Query().get('myslice:user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
129 user_details_sfa = execute_admin_query(wsgi_request, user_query)
131 for user in user_details_sfa:
132 if user['user_email'] == user_request['email']:
133 errors.append('Email already registered in OneLab registry. <a href="/contact">Contact OneLab support</a> or use another email.')
134 if user['user_hrn'] == user_request['user_hrn']:
135 # add random number if user_hrn already exists in the registry
136 user_request['user_hrn'] = user_request['authority_hrn'] \
137 + '.' + split_email + str(randint(1,1000000))
139 # checking in django unfold db portal application pending users
140 # sqlite3 /var/unfold/unfold.sqlite3
141 # select email from portal_pendinguser;
142 if PendingUser.objects.filter(email__iexact = user_request['email']):
143 errors.append('Account pending for validation. Please wait till your account is validated or contact OneLab support.')
145 # checking in django_db !!
146 # sqlite3 /var/unfold/unfold.sqlite3
147 # select email from auth_user;
148 if UserModel._default_manager.filter(email__iexact = user_request['email']):
149 errors.append('<a href="/contact">Contact support</a> or try with another email.')
151 # XXX TODO: Factorize with portal/accountview.py
152 # XXX TODO: Factorize with portal/registrationview.py
153 # XXX TODO: Factorize with portal/joinview.py
154 if 'generate' in wsgi_request.POST['question']:
155 user_request['auth_type'] = 'managed'
157 # XXX Common code, dependency ?
158 from Crypto.PublicKey import RSA
159 private = RSA.generate(1024)
161 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
162 # Example: public_key = 'ssh-rsa AAAAB3...'
163 user_request['private_key'] = private.exportKey()
164 user_request['public_key'] = private.publickey().exportKey(format='OpenSSH')
167 user_request['auth_type'] = 'user'
169 up_file = wsgi_request.FILES['user_public_key']
171 file_content = up_file.read().strip()
172 file_name = up_file.name
173 file_extension = os.path.splitext(file_name)[1]
175 ALLOWED_EXTENSIONS = ['.pub','.txt']
176 if file_extension not in ALLOWED_EXTENSIONS or not re.search(r'ssh-rsa',file_content):
177 errors.append('Please upload a valid RSA public key.')
178 # user_request['private_key'] can't be Null because all db fields are set as NOT NULL
179 user_request['private_key'] = ""
180 user_request['public_key'] = file_content
183 create_pending_user(wsgi_request, user_request, user_detail)
184 self.template_name = 'user_register_complete.html'
186 activity.user.registered(self.request)
187 return render(wsgi_request, self.template, {'theme': self.theme})
190 logger.debug("############ BREAKPOINT A #################")
192 ## this is coming from onelab website onelab.eu
194 'first_name': wsgi_request.GET.get('first_name', ''),
195 'last_name': wsgi_request.GET.get('last_name', ''),
196 'email': wsgi_request.GET.get('email', ''),
199 activity.user.signup(self.request)
200 logger.debug("############ BREAKPOINT B #################")
203 #'topmenu_items': topmenu_items_live('Register', page),
205 'authorities': authorities,
208 template_env.update(user_request)
209 template_env.update(reg_form)
210 template_env.update(page.prelude_env ())
211 logger.debug("############ BREAKPOINT C #################")
212 return render(wsgi_request, self.template,template_env)