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 authorities = sorted(authorities)
50 # xxx tocheck - if authorities is empty, it's no use anyway
51 # (users won't be able to validate the form anyway)
54 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
55 page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
56 page.add_css_files ( [ "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
58 print 'registration view, method',method
60 user_query = Query().get('local:user').select('user_id','email')
61 user_details = execute_admin_query(self.request, user_query)
64 # We shall use a form here
66 #get_email = PendingUser.objects.get(email)
67 reg_fname = request.POST.get('firstname', '')
68 reg_lname = request.POST.get('lastname', '')
69 #reg_aff = request.POST.get('affiliation','')
70 reg_auth = request.POST.get('authority_hrn', '')
71 #reg_login = request.POST.get('login', '')
72 reg_email = request.POST.get('email','').lower()
74 split_email = reg_email.split("@")[0]
75 split_email = split_email.replace(".", "_")
76 user_hrn = reg_auth + '.' + split_email
78 UserModel = get_user_model()
80 #POST value validation
81 if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
82 errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
83 if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
84 errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
85 # checking in django_db !!
86 if PendingUser.objects.filter(email__iexact=reg_email):
87 errors.append('Email is pending for validation. Please provide a new email address.')
88 if UserModel._default_manager.filter(email__iexact=reg_email):
89 errors.append('This email is not usable. Please contact the administrator or try with another email.')
90 for user_detail in user_details:
91 if user_detail['email']==reg_email:
92 errors.append('Email already registered in Manifold. Please provide a new email address.')
94 # XXX TODO: Factorize with portal/accountview.py
95 if 'generate' in request.POST['question']:
96 from Crypto.PublicKey import RSA
97 private = RSA.generate(1024)
98 private_key = json.dumps(private.exportKey())
99 public = private.publickey()
100 public_key = json.dumps(public.exportKey(format='OpenSSH'))
102 # # Generate public and private keys using SFA Library
103 # from sfa.trust.certificate import Keypair
104 # k = Keypair(create=True)
105 # public_key = k.get_pubkey_string()
106 # private_key = k.as_pem()
107 # private_key = ''.join(private_key.split())
108 # public_key = "ssh-rsa " + public_key
110 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
111 auth_type = 'managed'
112 #keypair = re.sub("\r", "", keypair)
113 #keypair = re.sub("\n", "\\n", keypair)
114 #keypair = keypair.rstrip('\r\n')
115 #keypair = ''.join(keypair.split())
116 #for sending email: removing existing double qoute
117 public_key = public_key.replace('"', '');
119 up_file = request.FILES['user_public_key']
120 file_content = up_file.read()
121 file_name = up_file.name
122 file_extension = os.path.splitext(file_name)[1]
123 allowed_extension = ['.pub','.txt']
124 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
125 keypair = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
126 keypair = re.sub("\r", "", keypair)
127 keypair = re.sub("\n", "\\n",keypair)
128 keypair = ''.join(keypair.split())
131 public_key = file_content
132 public_key = ''.join(public_key.split())
134 errors.append('Please upload a valid RSA public key [.txt or .pub].')
136 #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff,
137 # email=reg_email, password=request.POST['password'], keypair=keypair)
139 #saving to django db 'portal_pendinguser' table
142 first_name = reg_fname,
143 last_name = reg_lname,
144 #affiliation = reg_aff,
145 authority_hrn = reg_auth,
148 password = request.POST['password'],
152 # saves the user to django auth_user table [needed for password reset]
153 user = User.objects.create_user(reg_email, reg_email, request.POST['password'])
154 #creating user to manifold local:user
155 config = '{"firstname":"'+ reg_fname + '", "lastname":"'+ reg_lname + '", "authority":"'+ reg_auth + '"}'
156 user_params = {'email': reg_email, 'password': request.POST['password'], 'config': config}
157 manifold_add_user(request,user_params)
158 #creating local:account in manifold
159 user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
160 user_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': keypair}
161 manifold_add_account(request,user_params)
165 'first_name' : reg_fname,
166 'last_name' : reg_lname,
167 'authority_hrn' : reg_auth,
169 'user_hrn' : user_hrn,
170 'public_key' : public_key,
171 'cc_myself' : True # form.cleaned_data['cc_myself']
173 recipients = authority_get_pi_emails(request,reg_auth)
176 recipients.append(ctx['email'])
178 msg = render_to_string('user_request_email.txt', ctx)
179 send_mail("Onelab New User request for %s submitted"%reg_email, msg, 'support@myslice.info', recipients)
180 return render(request, 'user_register_complete.html')
183 'topmenu_items': topmenu_items_live('Register', page),
185 'firstname': request.POST.get('firstname', ''),
186 'lastname': request.POST.get('lastname', ''),
187 #'affiliation': request.POST.get('affiliation', ''),
188 'authority_hrn': request.POST.get('authority_hrn', ''),
189 'email': request.POST.get('email', ''),
190 'password': request.POST.get('password', ''),
191 'authorities': authorities,
193 template_env.update(page.prelude_env ())
194 return render(request, 'registration_view.html',template_env)