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, getAuthorities
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 authorities = getAuthorities(wsgi_request, admin = True)
48 ## REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
49 #authorities_query = Query.get('authority').select('name', 'authority_hrn')
50 #authorities = execute_admin_query(wsgi_request, authorities_query)
51 #if authorities is not None:
52 # # Remove the root authority from the list
53 # matching = [s for s in authorities if "." in s['authority_hrn']]
54 # authorities = sorted(matching, key=lambda k: k['authority_hrn'])
55 # authorities = sorted(matching, key=lambda k: k['name'])
57 logger.debug("############ BREAKPOINT 1 #################")
59 page = Page(wsgi_request)
61 page.add_css_files ( [ "https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" ] )
63 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" ] )
65 page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css", "css/jquery.ui.combobox.css" ] )
66 page.expose_js_metadata()
67 logger.debug("############ BREAKPOINT 2 #################")
70 # The form has been submitted
72 if wsgi_request.is_secure():
73 current_site = 'https://'
75 current_site = 'http://'
76 current_site += wsgi_request.META['HTTP_HOST']
78 logger.debug("############ BREAKPOINT 3 #################")
79 post_email = wsgi_request.POST.get('email','').lower()
80 salt = randint(1,100000)
81 email_hash = md5(str(salt)+post_email).hexdigest()
82 #email_hash = md5(post_email).digest().encode('base64')[:-1]
84 'first_name' : wsgi_request.POST.get('firstname', ''),
85 'last_name' : wsgi_request.POST.get('lastname', ''),
86 'authority_hrn' : wsgi_request.POST.get('org_name', ''),
88 'password' : wsgi_request.POST.get('password', ''),
89 'current_site' : current_site,
90 'email_hash' : email_hash,
92 'validation_link': current_site + '/portal/email_activation/'+ email_hash
95 logger.debug("############ BREAKPOINT 4 #################")
96 auth = wsgi_request.POST.get('org_name', None)
97 if auth is None or auth == "":
98 errors.append('Organization required: please select one or request its addition')
101 logger.debug("############ BREAKPOINT 5 #################")
103 # Construct user_hrn from email (XXX Should use common code)
104 split_email = user_request['email'].split("@")[0]
105 split_email = split_email.replace(".", "_")
106 # Replace + by _ => more convenient for testing and validate with a real email
107 split_email = split_email.replace("+", "_")
108 user_request['user_hrn'] = user_request['authority_hrn'] \
112 UserModel = get_user_model()
113 if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
114 errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
115 if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
116 errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
117 # Does the user exist in Manifold?
118 user_query = Query().get('local:user').select('user_id','email')
119 user_details = execute_admin_query(wsgi_request, user_query)
120 for user_detail in user_details:
121 if user_detail['email'] == user_request['email']:
122 errors.append('Email already registered. <a href="/">Login</a> with your existing account. <a href="/portal/pass_reset/">Forgot your password?</a>')
124 # Does the user exist in sfa? [query is very slow!!]
125 #user_query = Query().get('user').select('user_hrn','user_email')
126 # XXX Test based on the user_hrn is quick
128 # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
129 user_query = Query().get('myslice:user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
130 user_details_sfa = execute_admin_query(wsgi_request, user_query)
132 for user in user_details_sfa:
133 if user['user_email'] == user_request['email']:
134 errors.append('Email already registered in OneLab registry. <a href="/contact">Contact OneLab support</a> or use another email.')
135 if user['user_hrn'] == user_request['user_hrn']:
136 # add random number if user_hrn already exists in the registry
137 user_request['user_hrn'] = user_request['authority_hrn'] \
138 + '.' + split_email + str(randint(1,1000000))
140 # checking in django unfold db portal application pending users
141 # sqlite3 /var/unfold/unfold.sqlite3
142 # select email from portal_pendinguser;
143 if PendingUser.objects.filter(email__iexact = user_request['email']):
144 errors.append('Account pending for validation. Please wait till your account is validated or contact OneLab support.')
146 # checking in django_db !!
147 # sqlite3 /var/unfold/unfold.sqlite3
148 # select email from auth_user;
149 if UserModel._default_manager.filter(email__iexact = user_request['email']):
150 errors.append('<a href="/contact">Contact support</a> or try with another email.')
152 # XXX TODO: Factorize with portal/accountview.py
153 # XXX TODO: Factorize with portal/registrationview.py
154 # XXX TODO: Factorize with portal/joinview.py
155 if 'generate' in wsgi_request.POST['question']:
156 user_request['auth_type'] = 'managed'
158 # XXX Common code, dependency ?
159 from Crypto.PublicKey import RSA
160 private = RSA.generate(1024)
162 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
163 # Example: public_key = 'ssh-rsa AAAAB3...'
164 user_request['private_key'] = private.exportKey()
165 user_request['public_key'] = private.publickey().exportKey(format='OpenSSH')
168 user_request['auth_type'] = 'user'
170 up_file = wsgi_request.FILES['user_public_key']
172 file_content = up_file.read().strip()
173 file_name = up_file.name
174 file_extension = os.path.splitext(file_name)[1]
176 ALLOWED_EXTENSIONS = ['.pub','.txt']
177 if file_extension not in ALLOWED_EXTENSIONS or not re.search(r'ssh-rsa',file_content):
178 errors.append('Please upload a valid RSA public key.')
179 # user_request['private_key'] can't be Null because all db fields are set as NOT NULL
180 user_request['private_key'] = ""
181 user_request['public_key'] = file_content
184 create_pending_user(wsgi_request, user_request, user_detail)
185 self.template_name = 'user_register_complete.html'
187 activity.user.registered(self.request)
188 return render(wsgi_request, self.template, {'theme': self.theme})
191 logger.debug("############ BREAKPOINT A #################")
193 ## this is coming from onelab website onelab.eu
195 'first_name': wsgi_request.GET.get('first_name', ''),
196 'last_name': wsgi_request.GET.get('last_name', ''),
197 'email': wsgi_request.GET.get('email', ''),
200 activity.user.signup(self.request)
201 logger.debug("############ BREAKPOINT B #################")
204 #'topmenu_items': topmenu_items_live('Register', page),
206 'authorities': authorities,
209 template_env.update(user_request)
210 template_env.update(reg_form)
211 template_env.update(page.prelude_env ())
212 logger.debug("############ BREAKPOINT C #################")
213 return render(wsgi_request, self.template,template_env)