4 from django.core.mail import send_mail
5 from django.contrib.auth.models import User
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
11 from unfold.page import Page
12 from unfold.loginrequired import FreeAccessView
13 from ui.topmenu import topmenu_items_live
15 from manifold.manifoldapi import execute_admin_query
16 from manifold.core.query import Query
18 from portal.models import PendingUser
19 from portal.actions import authority_get_pi_emails, manifold_add_user,manifold_add_account
21 # since we inherit from FreeAccessView we cannot redefine 'dispatch'
22 # so let's override 'get' and 'post' instead
24 class RegistrationView (FreeAccessView):
26 def post (self, request):
27 return self.get_or_post (request, 'POST')
29 def get (self, request):
30 return self.get_or_post (request, 'GET')
32 def get_or_post (self, request, method):
35 # Using cache manifold-tables to get the list of authorities faster
36 authorities_query = Query.get('authority').select('name', 'authority_hrn')
38 #onelab_enabled_query = Query.get('local:platform').filter_by('platform', '==', 'ple').filter_by('disabled', '==', 'False')
39 #onelab_enabled = not not execute_admin_query(request, onelab_enabled_query)
42 print "ONELAB ENABLED"
43 #authorities_query = Query.get('ple:authority').select('name', 'authority_hrn').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc', 'ple.ibbtple', 'ple.nitos'])
46 print "FIREXP ENABLED"
48 authorities = execute_admin_query(request, authorities_query)
49 if authorities is not None:
50 authorities = sorted(authorities)
51 # xxx tocheck - if authorities is empty, it's no use anyway
52 # (users won't be able to validate the form anyway)
55 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
56 page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
57 page.add_css_files ( [ "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
59 print 'registration view, method',method
61 user_query = Query().get('local:user').select('user_id','email')
62 user_details = execute_admin_query(self.request, user_query)
65 # We shall use a form here
67 #get_email = PendingUser.objects.get(email)
68 reg_fname = request.POST.get('firstname', '')
69 reg_lname = request.POST.get('lastname', '')
70 #reg_aff = request.POST.get('affiliation','')
71 reg_auth = request.POST.get('authority_hrn', '')
72 #reg_login = request.POST.get('login', '')
73 reg_email = request.POST.get('email','').lower()
75 split_email = reg_email.split("@")[0]
76 split_email = split_email.replace(".", "_")
77 user_hrn = reg_auth + '.' + split_email
79 UserModel = get_user_model()
81 #POST value validation
82 if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
83 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
84 if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
85 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
86 # checking in django_db !!
87 if PendingUser.objects.filter(email__iexact=reg_email):
88 errors.append('Email is pending for validation. Please provide a new email address.')
89 if UserModel._default_manager.filter(email__iexact=reg_email):
90 errors.append('This email is not usable. Please contact the administrator or try with another email.')
91 for user_detail in user_details:
92 if user_detail['email']==reg_email:
93 errors.append('Email already registered in Manifold. Please provide a new email address.')
95 # XXX TODO: Factorize with portal/accountview.py
96 if 'generate' in request.POST['question']:
97 from Crypto.PublicKey import RSA
98 private = RSA.generate(1024)
99 private_key = json.dumps(private.exportKey())
100 public = private.publickey()
101 public_key = json.dumps(public.exportKey(format='OpenSSH'))
103 # # Generate public and private keys using SFA Library
104 # from sfa.trust.certificate import Keypair
105 # k = Keypair(create=True)
106 # public_key = k.get_pubkey_string()
107 # private_key = k.as_pem()
108 # private_key = ''.join(private_key.split())
109 # public_key = "ssh-rsa " + public_key
111 account_config = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
112 auth_type = 'managed'
113 #keypair = re.sub("\r", "", keypair)
114 #keypair = re.sub("\n", "\\n", keypair)
115 #keypair = keypair.rstrip('\r\n')
116 #keypair = ''.join(keypair.split())
117 #for sending email: removing existing double qoute
118 public_key = public_key.replace('"', '');
120 up_file = request.FILES['user_public_key']
121 file_content = up_file.read()
122 file_name = up_file.name
123 file_extension = os.path.splitext(file_name)[1]
124 allowed_extension = ['.pub','.txt']
125 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
126 account_config = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
127 account_config = re.sub("\r", "", account_config)
128 account_config = re.sub("\n", "\\n",account_config)
129 account_config = ''.join(account_config.split())
132 public_key = file_content
133 public_key = ''.join(public_key.split())
135 errors.append('Please upload a valid RSA public key [.txt or .pub].')
137 #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff,
138 # email=reg_email, password=request.POST['password'], keypair=keypair)
140 #saving to django db 'portal_pendinguser' table
143 first_name = reg_fname,
144 last_name = reg_lname,
145 #affiliation = reg_aff,
146 authority_hrn = reg_auth,
149 password = request.POST['password'],
150 keypair = account_config,
153 # saves the user to django auth_user table [needed for password reset]
154 user = User.objects.create_user(reg_email, reg_email, request.POST['password'])
155 #creating user to manifold local:user
156 user_config = '{"firstname":"'+ reg_fname + '", "lastname":"'+ reg_lname + '", "authority":"'+ reg_auth + '"}'
157 user_params = {'email': reg_email, 'password': request.POST['password'], 'config': user_config}
158 manifold_add_user(request,user_params)
159 #creating local:account in manifold
160 user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
161 account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
162 manifold_add_account(request,account_params)
166 'first_name' : reg_fname,
167 'last_name' : reg_lname,
168 'authority_hrn' : reg_auth,
170 'user_hrn' : user_hrn,
171 'public_key' : public_key,
172 'cc_myself' : True # form.cleaned_data['cc_myself']
174 recipients = authority_get_pi_emails(request,reg_auth)
177 recipients.append(ctx['email'])
179 msg = render_to_string('user_request_email.txt', ctx)
180 send_mail("Onelab New User request for %s submitted"%reg_email, msg, 'support@myslice.info', recipients)
181 return render(request, 'user_register_complete.html')
184 'topmenu_items': topmenu_items_live('Register', page),
186 'firstname': request.POST.get('firstname', ''),
187 'lastname': request.POST.get('lastname', ''),
188 #'affiliation': request.POST.get('affiliation', ''),
189 'authority_hrn': request.POST.get('authority_hrn', ''),
190 'email': request.POST.get('email', ''),
191 'password': request.POST.get('password', ''),
192 'authorities': authorities,
194 template_env.update(page.prelude_env ())
195 return render(request, 'registration_view.html',template_env)