3 from random import randint
5 from hashlib import md5
6 from django.core.mail import EmailMultiAlternatives
7 from django.contrib.auth.models import User
8 from django.views.generic import View
9 from django.template.loader import render_to_string
10 from django.shortcuts import render
11 from django.contrib.auth import get_user_model
12 from django.contrib.sites.models import Site
14 from unfold.page import Page
15 from unfold.loginrequired import FreeAccessView
16 from ui.topmenu import topmenu_items_live
18 from manifoldapi.manifoldapi import execute_admin_query
19 from manifold.core.query import Query
21 from portal.models import PendingUser,PendingAuthority
22 from portal.actions import authority_get_pi_emails, manifold_add_user,manifold_add_account, create_pending_user
24 from myslice.theme import ThemeView
26 import activity.institution
28 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
29 # so let's override 'get' and 'post' instead
31 class JoinView (FreeAccessView, ThemeView):
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, request, method):
41 # List authorities already in the Registry in order to avoid duplicates
42 # Using cache manifold-tables to get the list of authorities faster
43 authorities_query = Query.get('authority').select('name', 'authority_hrn')
44 authorities = execute_admin_query(request, authorities_query)
45 if authorities is not None:
46 authorities = sorted(authorities)
47 root_authorities = sorted([a for a in authorities if '.' not in a['authority_hrn']])
50 page.add_js_files ( [ "js/jquery.validate.js", "js/join.js", "js/jquery.qtip.min.js" ] )
51 page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css" ] )
52 page.add_css_files ( [ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
55 # xxx tocheck - if authorities is empty, it's no use anyway
56 # (users won't be able to validate the form anyway)
58 # List local users in Manifold DB in order ot avoid duplicates
59 user_query = Query().get('local:user').select('user_id','email')
60 list_users = execute_admin_query(self.request, user_query)
62 reg_root_authority_hrn = request.POST.get('root_authority_hrn', '').lower()
64 reg_site_name = request.POST.get('site_name', '')
65 reg_site_authority = request.POST.get('site_authority', '').lower()
66 reg_site_abbreviated_name = request.POST.get('site_abbreviated_name', '').lower()
67 reg_site_url = request.POST.get('site_url', '')
68 reg_site_latitude = request.POST.get('site_latitude', '')
69 reg_site_longitude = request.POST.get('site_longitude', '')
71 reg_fname = request.POST.get('pi_first_name', '')
72 reg_lname = request.POST.get('pi_last_name', '')
73 reg_auth = 'onelab.' + reg_site_abbreviated_name
74 reg_email = request.POST.get('pi_email','').lower()
75 reg_phone = request.POST.get('pi_phone','')
77 split_email = reg_email.split("@")[0]
78 split_email = split_email.replace(".", "_")
79 # Replace + by _ => more convenient for testing and validate with a real email
80 split_email = split_email.replace("+", "_")
81 user_hrn = reg_auth + '.' + split_email
83 UserModel = get_user_model()
85 reg_address_line1 = request.POST.get('address_line1', '')
86 reg_address_line2 = request.POST.get('address_line2', '')
87 reg_address_line3 = request.POST.get('address_line3', '')
88 reg_address_city = request.POST.get('address_city', '')
89 reg_address_postalcode = request.POST.get('address_postalcode', '')
90 reg_address_state = request.POST.get('address_state', '')
91 reg_address_country = request.POST.get('address_country', '')
93 #POST value validation
94 if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
95 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
96 if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
97 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
98 if (re.search(r'^[A-Za-z0-9_ ]*$', reg_site_name) == None):
99 errors.append('Name of organization may contain only letters, numbers, and underscore.')
100 if (re.search(r'^[A-Za-z ]*$', reg_address_city) == None):
101 errors.append('City may contain only letters.')
102 if (re.search(r'^[A-Za-z ]*$', reg_address_country) == None):
103 errors.append('Country may contain only letters.')
104 if (re.search(r'^[A-Za-z0-9]*$', reg_site_abbreviated_name) == None):
105 errors.append('Shortname may contain only letters and numbers')
106 if (re.search(r'^[0-9]*$', reg_phone) == None):
107 errors.append('Phone number may contain only numbers.')
108 #if (re.search(r'^\w+$', reg_site_authority) == None):
109 # errors.append('Site Authority may contain only letters or numbers.')
110 # checking in django_db !!
111 if PendingUser.objects.filter(email__iexact=reg_email):
112 errors.append('Email is pending for validation. Please provide a new email address.')
113 if PendingAuthority.objects.filter(site_abbreviated_name__iexact=reg_site_abbreviated_name):
114 errors.append('This site is pending for validation.')
115 #if PendingAuthority.objects.filter(site_name__iexact=reg_site_name):
116 # errors.append('This site is pending for validation.')
118 if UserModel._default_manager.filter(email__iexact=reg_email):
119 errors.append('This email is not usable. Please contact the administrator or try with another email.')
120 for user_detail in list_users:
121 if user_detail['email']==reg_email:
122 errors.append('Email already registered in Manifold. Please provide a new email address.')
124 # XXX TODO: Factorize with portal/accountview.py
125 # XXX TODO: Factorize with portal/registrationview.py
126 # XXX TODO: Factorize with portal/joinview.py
127 # if 'generate' in request.POST['question']:
128 from Crypto.PublicKey import RSA
129 private = RSA.generate(1024)
130 private_key = private.exportKey()
131 public_key = private.publickey().exportKey(format='OpenSSH')
133 auth_type = 'managed'
136 reg_password = request.POST['pi_password']
137 a = PendingAuthority(
138 site_name = reg_site_name,
139 site_authority = reg_auth,
140 site_abbreviated_name = reg_site_abbreviated_name,
141 site_url = reg_site_url,
142 site_latitude = reg_site_latitude,
143 site_longitude = reg_site_longitude,
144 address_line1 = reg_email, # XXX field name must be renamed. Email needed 4 rejection email.
145 address_line2 = reg_address_line2,
146 address_line3 = reg_address_line3,
147 address_city = reg_address_city,
148 address_postalcode = reg_address_postalcode,
149 address_state = reg_address_state,
150 address_country = reg_address_country,
151 authority_hrn = reg_root_authority_hrn,
155 reg_password = request.POST['pi_password']
156 salt = randint(1,100000)
158 current_site = Site.objects.get_current()
159 current_site = current_site.domain
161 email_hash = md5(str(salt)+reg_email).hexdigest()
163 'first_name' : reg_fname,
164 'last_name' : reg_lname,
165 'organization' : reg_site_name,
166 'authority_hrn' : reg_auth,
168 'password' : reg_password,
169 'public_key' : public_key,
170 'private_key' : private_key,
171 'current_site' : current_site,
172 'email_hash' : email_hash,
173 'user_hrn' : user_hrn,
175 'auth_type' : 'managed',
176 'validation_link': 'http://' + current_site + '/portal/email_activation/'+ email_hash
180 create_pending_user(request, user_request, user_detail)
181 # saves the user to django auth_user table [needed for password reset]
182 #user = User.objects.create_user(reg_email, reg_email, reg_password)
184 #creating user to manifold local:user
185 #user_config = '{"first_name":"'+ reg_fname + '", "last_name":"'+ reg_lname + '", "authority_hrn":"'+ reg_auth + '"}'
186 #user_params = {'email': reg_email, 'password': reg_password, 'config': user_config, 'status': 1}
187 #manifold_add_user(request,user_params)
188 #creating local:account in manifold
189 #user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
190 #account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
191 #manifold_add_account(request,account_params)
196 'site_name' : reg_site_name,
197 'authority_hrn' : reg_root_authority_hrn + '.' + reg_site_authority,
198 'site_abbreviated_name' : reg_site_abbreviated_name,
199 'site_url' : reg_site_url,
200 'address_city' : reg_address_city,
201 'address_country' : reg_address_country,
202 'first_name' : reg_fname,
203 'last_name' : reg_lname,
204 'authority_hrn' : reg_auth,
206 'user_hrn' : user_hrn,
207 'public_key' : public_key,
210 #recipients = authority_get_pi_emails(request,reg_auth)
212 self.template_name = 'authority_request_email.html'
213 html_content = render_to_string(self.template, ctx)
215 self.template_name = 'authority_request_email.txt'
216 text_content = render_to_string(self.template, ctx)
218 self.template_name = 'authority_request_email_subject.txt'
219 subject = render_to_string(self.template, ctx)
220 subject = subject.replace('\n', '')
222 #theme.template_name = 'email_default_sender.txt'
223 #sender = render_to_string(theme.template, ctx)
224 #sender = sender.replace('\n', '')
227 msg = EmailMultiAlternatives(subject, text_content, sender, ['support@onelab.eu'])
228 msg.attach_alternative(html_content, "text/html")
232 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
234 traceback.print_exc()
236 self.template_name = 'join_complete.html'
237 # log institution activity
238 activity.institution.joined(self.request)
239 return render(request, self.template, {'theme': self.theme})
240 #return render(request, 'user_register_complete.html')
243 'topmenu_items': topmenu_items_live('join', page),
245 'pi_first_name': request.POST.get('pi_first_name', ''),
246 'pi_last_name': request.POST.get('pi_last_name', ''),
247 'pi_email': request.POST.get('pi_email', ''),
248 'pi_phone': request.POST.get('pi_phone', ''),
249 'pi_password': request.POST.get('pi_password', ''),
250 'site_name': request.POST.get('site_name', ''),
251 'site_authority': request.POST.get('site_authority', '').lower(),
252 'site_abbreviated_name': request.POST.get('site_abbreviated_name', ''),
253 'site_url': request.POST.get('site_url', ''),
254 'site_latitude': request.POST.get('site_latitude', ''),
255 'site_longitude': request.POST.get('site_longitude', ''),
256 'address_line1': request.POST.get('address_line1', ''),
257 'address_line2': request.POST.get('address_line2', ''),
258 'address_line3': request.POST.get('address_line3', ''),
259 'address_city': request.POST.get('address_city', ''),
260 'address_postalcode': request.POST.get('address_postalcode', ''),
261 'address_state': request.POST.get('address_state', ''),
262 'address_country': request.POST.get('address_country', ''),
263 'root_authority_hrn': request.POST.get('root_authority_hrn', '').lower(),
264 'root_authorities': root_authorities,
265 'authorities': authorities,
268 template_env.update(page.prelude_env ())
269 # log institution activity
270 activity.institution.join(self.request)
271 return render(request, 'join_view.html',template_env)