3 from random import randint
4 from hashlib import md5
6 from django.views.generic import View
7 from django.template.loader import render_to_string
9 from django.shortcuts import render
10 from django.contrib.auth import get_user_model
11 from django.contrib.sites.models import Site
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
27 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
28 # so let's override 'get' and 'post' instead
30 class RegistrationView (FreeAccessView, ThemeView):
31 template_name = 'registration_view.html'
33 def post (self, request):
34 return self.get_or_post (request, 'POST')
36 def get (self, request):
37 return self.get_or_post (request, 'GET')
39 def get_or_post(self, wsgi_request, method):
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)
49 print "############ BREAKPOINT 1 #################"
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 #################"
58 # The form has been submitted
61 current_site = Site.objects.get_current()
62 current_site = current_site.domain
64 print "############ BREAKPOINT 3 #################"
66 for authority in authorities:
67 if authority['name'] == wsgi_request.POST.get('org_name', ''):
68 authority_hrn = authority['authority_hrn']
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', '')
74 print "############ BREAKPOINT 4 #################"
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]
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,
86 'password' : wsgi_request.POST.get('password', ''),
87 'current_site' : current_site,
88 'email_hash' : email_hash,
90 'validation_link': 'http://' + current_site + '/portal/email_activation/'+ email_hash
93 print "############ BREAKPOINT 5 #################"
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'] \
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>')
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)
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))
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.')
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.')
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'
148 # XXX Common code, dependency ?
149 from Crypto.PublicKey import RSA
150 private = RSA.generate(1024)
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')
158 user_request['auth_type'] = 'user'
160 up_file = wsgi_request.FILES['user_public_key']
162 file_content = up_file.read().strip()
163 file_name = up_file.name
164 file_extension = os.path.splitext(file_name)[1]
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
174 create_pending_user(wsgi_request, user_request, user_detail)
175 self.template_name = 'user_register_complete.html'
177 activity.user.registered(self.request)
178 return render(wsgi_request, self.template, {'theme': self.theme})
181 print "############ BREAKPOINT A #################"
183 ## this is coming from onelab website onelab.eu
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', ''),
190 activity.user.signup(self.request)
191 print "############ BREAKPOINT B #################"
194 'topmenu_items': topmenu_items_live('Register', page),
196 'authorities': authorities,
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)