1 from unfold.loginrequired import LoginRequiredAutoLogoutView
3 from manifold.core.query import Query
4 from manifold.manifoldapi import execute_query
5 from portal.actions import manifold_update_user, manifold_update_account
7 from ui.topmenu import topmenu_items, the_user
9 from django.http import HttpResponse, HttpResponseRedirect
10 from django.contrib import messages
11 from django.contrib.auth.decorators import login_required
12 from django.core.mail import send_mail
15 import json, os, re, itertools
18 class AccountView(LoginRequiredAutoLogoutView):
19 template_name = "account-view.html"
21 def dispatch(self, *args, **kwargs):
22 return super(AccountView, self).dispatch(*args, **kwargs)
25 def get_context_data(self, **kwargs):
27 user_query = Query().get('local:user').select('config','email')
28 user_details = execute_query(self.request, user_query)
30 # not always found in user_details...
32 for user_detail in user_details:
33 #email = user_detail['email']
34 if user_detail['config']:
35 config = json.loads(user_detail['config'])
37 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
38 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
39 platform_details = execute_query(self.request, platform_query)
40 account_details = execute_query(self.request, account_query)
42 # initial assignment needed for users having no account
47 account_reference = ''
48 platform_name_list = []
49 platform_name_secondary_list = []
50 platform_access_list = []
51 platform_no_access_list = []
52 total_platform_list = []
53 account_type_list = []
54 account_type_secondary_list = []
55 account_reference_list = []
56 delegation_type_list = []
57 exp_user_cred_list = []
59 slice_cred_exp_list = []
63 for platform_detail in platform_details:
64 if 'sfa' in platform_detail['gateway_type'] and platform_detail['disabled']==0:
65 total_platform = platform_detail['platform']
66 total_platform_list.append(total_platform)
68 for account_detail in account_details:
69 if platform_detail['platform_id'] == account_detail['platform_id']:
70 platform_name = platform_detail['platform']
71 account_config = json.loads(account_detail['config'])
72 account_usr_hrn = account_config.get('user_hrn','N/A')
73 account_pub_key = account_config.get('user_public_key','N/A')
74 account_reference = account_config.get ('reference_platform','N/A')
76 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
77 if 'N/A' not in acc_slice_cred:
78 for key, value in acc_slice_cred.iteritems():
79 slice_list.append(key)
81 exp_date = re.search('<expires>(.*)</expires>', value)
83 exp_date = exp_date.group(1)
84 slice_cred_exp_list.append(exp_date)
86 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
87 for t in zip(slice_list, slice_cred_exp_list)]
89 account_user_credential = account_config.get('delegated_user_credential','N/A')
91 result = re.search('<expires>(.*)</expires>', account_user_credential)
93 exp_user_cred = result.group(1)
94 # for reference accounts
95 if 'reference' in account_detail['auth_type']:
96 account_type = 'Reference'
98 platform_name_secondary_list.append(platform_name)
99 account_type_secondary_list.append(account_type)
100 account_reference_list.append(account_reference)
101 secondary_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
102 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
104 elif 'managed' in account_detail['auth_type']:
105 account_type = 'Principal'
106 delegation = 'Automatic'
108 account_type = 'Principal'
109 delegation = 'Manual'
110 # for principal (auth_type=user/managed) accounts
111 if 'reference' not in account_detail['auth_type']:
112 platform_name_list.append(platform_name)
113 account_type_list.append(account_type)
114 delegation_type_list.append(delegation)
115 exp_user_cred_list.append(exp_user_cred)
116 usr_hrn_list.append(account_usr_hrn)
117 pub_key_list.append(account_pub_key)
118 # combining 5 lists into 1 [to render in the template]
119 lst = [{'platform_name': t[0], 'account_type': t[1], 'delegation_type': t[2], 'credential_expiration':t[3], 'usr_hrn':t[4], 'usr_pubkey':t[5]}
120 for t in zip(platform_name_list, account_type_list, delegation_type_list, exp_user_cred_list, usr_hrn_list, pub_key_list)]
121 # to hide private key row if it doesn't exist
122 if 'myslice' in platform_detail['platform']:
123 account_config = json.loads(account_detail['config'])
124 account_priv_key = account_config.get('user_private_key','N/A')
125 if 'sfa' in platform_detail['gateway_type']:
126 platform_access = platform_detail['platform']
127 platform_access_list.append(platform_access)
129 # Removing the platform which already has access
130 for platform in platform_access_list:
131 total_platform_list.remove(platform)
132 # we could use zip. this one is used if columns have unequal rows
133 platform_list = [{'platform_no_access': t[0]}
134 for t in itertools.izip_longest(total_platform_list)]
137 context = super(AccountView, self).get_context_data(**kwargs)
138 context['data'] = lst
139 context['ref_acc'] = secondary_list
140 context['platform_list'] = platform_list
141 context['my_slices'] = my_slices
142 context['person'] = self.request.user
143 context['firstname'] = config.get('firstname',"?")
144 context['lastname'] = config.get('lastname',"?")
145 context['fullname'] = context['firstname'] +' '+ context['lastname']
146 context['authority'] = config.get('authority',"Unknown Authority")
147 context['user_private_key'] = account_priv_key
149 # XXX This is repeated in all pages
150 # more general variables expected in the template
151 context['title'] = 'Platforms connected to MySlice'
152 # the menu items on the top
153 context['topmenu_items'] = topmenu_items('My Account', self.request)
154 # so we can sho who is logged
155 context['username'] = the_user(self.request)
156 # context ['firstname'] = config['firstname']
157 #context.update(page.prelude_env())
162 #my_acc form value processing
163 def account_process(request):
164 user_query = Query().get('local:user').select('password','config')
165 user_details = execute_query(request, user_query)
167 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
168 account_details = execute_query(request, account_query)
170 platform_query = Query().get('local:platform').select('platform_id','platform')
171 platform_details = execute_query(request, platform_query)
173 # for account_detail in account_details:
174 # if account_detail['platform_id'] == 5:
175 # account_config = json.loads(account_detail['config'])
177 if 'submit_name' in request.POST:
178 edited_first_name = request.POST['fname']
179 edited_last_name = request.POST['lname']
182 for user_config in user_details:
183 #email = user_detail['email']
184 if user_config['config']:
185 config = json.loads(user_config['config'])
186 config['firstname'] = edited_first_name
187 config['lastname'] = edited_last_name
188 config['authority'] = config.get('authority','Unknown Authority')
189 updated_config = json.dumps(config)
190 user_params = {'config': updated_config}
191 else: # it's needed if the config is empty
192 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
193 user_params = {'config': user_config['config']}
194 # updating config local:user in manifold
195 #user_params = { 'config': updated_config}
196 manifold_update_user(request,user_params)
197 # this will be depricated, we will show the success msg in same page
198 # return HttpResponse('Sucess: First Name and Last Name Updated!')
199 # Redirect to same page with success message
200 messages.success(request, 'Sucess: First Name and Last Name Updated.')
201 return HttpResponseRedirect("/portal/account/")
203 elif 'submit_pass' in request.POST:
204 edited_password = request.POST['password']
206 for user_pass in user_details:
207 user_pass['password'] = edited_password
208 #updating password in local:user
209 user_params = { 'password': user_pass['password']}
210 manifold_update_user(request,user_params)
211 # return HttpResponse('Success: Password Changed!!')
212 messages.success(request, 'Sucess: Password Updated.')
213 return HttpResponseRedirect("/portal/account/")
215 # XXX TODO: Factorize with portal/registrationview.py
217 elif 'generate' in request.POST:
218 for account_detail in account_details:
219 for platform_detail in platform_details:
220 if platform_detail['platform_id'] == account_detail['platform_id']:
221 if 'myslice' in platform_detail['platform']:
222 from Crypto.PublicKey import RSA
223 private = RSA.generate(1024)
224 private_key = json.dumps(private.exportKey())
225 public = private.publickey()
226 public_key = json.dumps(public.exportKey(format='OpenSSH'))
227 # Generate public and private keys using SFA Library
228 # from sfa.trust.certificate import Keypair
229 # k = Keypair(create=True)
230 # public_key = k.get_pubkey_string()
231 # private_key = k.as_pem()
232 # private_key = ''.join(private_key.split())
233 # public_key = "ssh-rsa " + public_key
234 # now we overwrite the config field with keypair
235 # once there will be user_hrn, we need to keep user_hrn and change only the keypair
236 # see submit_name section for implementing this
237 # keypair = re.sub("\r", "", keypair)
238 # keypair = re.sub("\n", "\\n", keypair)
239 # #keypair = keypair.rstrip('\r\n')
240 # keypair = ''.join(keypair.split())
241 # updating maniolf local:account table
242 account_config = json.loads(account_detail['config'])
243 # preserving user_hrn
244 user_hrn = account_config.get('user_hrn','N/A')
245 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
246 updated_config = json.dumps(account_config)
248 user_params = { 'config': keypair, 'auth_type':'managed'}
249 manifold_update_account(request,user_params)
250 messages.success(request, 'Sucess: New Keypair Generated!')
251 return HttpResponseRedirect("/portal/account/")
253 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
254 return HttpResponseRedirect("/portal/account/")
256 elif 'upload_key' in request.POST:
257 for account_detail in account_details:
258 for platform_detail in platform_details:
259 if platform_detail['platform_id'] == account_detail['platform_id']:
260 if 'myslice' in platform_detail['platform']:
261 up_file = request.FILES['pubkey']
262 file_content = up_file.read()
263 file_name = up_file.name
264 file_extension = os.path.splitext(file_name)[1]
265 allowed_extension = ['.pub','.txt']
266 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
267 account_config = json.loads(account_detail['config'])
268 # preserving user_hrn
269 user_hrn = account_config.get('user_hrn','N/A')
270 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
271 #file_content = re.sub("\r", "", file_content)
272 #file_content = re.sub("\n", "\\n",file_content)
273 file_content = ''.join(file_content.split())
274 #update manifold local:account table
275 user_params = { 'config': file_content, 'auth_type':'user'}
276 manifold_update_account(request,user_params)
277 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
278 return HttpResponseRedirect("/portal/account/")
280 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
281 return HttpResponseRedirect("/portal/account/")
283 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
284 return HttpResponseRedirect("/portal/account/")
286 elif 'dl_pubkey' in request.POST:
287 for account_detail in account_details:
288 for platform_detail in platform_details:
289 if platform_detail['platform_id'] == account_detail['platform_id']:
290 if 'myslice' in platform_detail['platform']:
291 account_config = json.loads(account_detail['config'])
292 public_key = account_config['user_public_key']
293 response = HttpResponse(public_key, content_type='text/plain')
294 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
298 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
299 return HttpResponseRedirect("/portal/account/")
301 elif 'dl_pkey' in request.POST:
302 for account_detail in account_details:
303 for platform_detail in platform_details:
304 if platform_detail['platform_id'] == account_detail['platform_id']:
305 if 'myslice' in platform_detail['platform']:
306 account_config = json.loads(account_detail['config'])
307 if 'user_private_key' in account_config:
308 private_key = account_config['user_private_key']
309 response = HttpResponse(private_key, content_type='text/plain')
310 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
313 messages.error(request, 'Download error: Private key is not stored in the server')
314 return HttpResponseRedirect("/portal/account/")
317 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
318 return HttpResponseRedirect("/portal/account/")
320 elif 'delete' in request.POST:
321 for account_detail in account_details:
322 for platform_detail in platform_details:
323 if platform_detail['platform_id'] == account_detail['platform_id']:
324 if 'myslice' in platform_detail['platform']:
325 account_config = json.loads(account_detail['config'])
326 if 'user_private_key' in account_config:
327 for key in account_config.keys():
328 if key== 'user_private_key':
329 del account_config[key]
331 updated_config = json.dumps(account_config)
332 user_params = { 'config': updated_config, 'auth_type':'user'}
333 manifold_update_account(request,user_params)
334 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
335 return HttpResponseRedirect("/portal/account/")
337 messages.error(request, 'Delete error: Private key is not stored in the server')
338 return HttpResponseRedirect("/portal/account/")
341 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
342 return HttpResponseRedirect("/portal/account/")
344 elif 'fuseco' in request.POST:
345 # The recipients are the PI of the authority
346 #recipients = authority_get_pi_emails(request, authority_hrn)
347 recipients = ["support@myslice.info"]
348 requester = request.user # current user
349 sender = 'yasin.upmc@gmail.com' # the server email
350 msg = "OneLab user %s requested account in fuseco Platform" % requester
351 send_mail("Onelab user %s requested an account in Fuseco"%requester , msg, sender, recipients)
352 messages.info(request, 'Request to get access on Fuseco platform received. Please wait for PI\'s reply.')
353 return HttpResponseRedirect("/portal/account/")
355 elif 'ple' in request.POST:
356 # The recipients are the PI of the authority
357 #recipients = authority_get_pi_emails(request, authority_hrn)
358 recipients = ["support@myslice.info"]
359 requester = request.user # current user
360 sender = 'yasin.upmc@gmail.com' # the server email
361 msg = "OneLab user %s requested account in fuseco Platform" % requester
362 send_mail("Onelab user %s requested an account in PLE"%requester , msg, sender, recipients)
363 messages.info(request, 'Request to get access on PLE platform received. Please wait for PI\'s reply.')
364 return HttpResponseRedirect("/portal/account/")
366 elif 'omf' in request.POST:
367 # The recipients are the PI of the authority
368 #recipients = authority_get_pi_emails(request, authority_hrn)
369 recipients = ["support@myslice.info"]
370 requester = request.user # current user
371 sender = 'yasin.upmc@gmail.com' # the server email
372 msg = "OneLab user %s requested account in omf:nitos Platform" % requester
373 send_mail("Onelab user %s requested an account in OMF:NITOS"%requester , msg, sender, recipients)
374 messages.info(request, 'Request to get access on OMF:NITOS platform received. Please wait for PI\'s reply.')
375 return HttpResponseRedirect("/portal/account/")
377 elif 'wilab' in request.POST:
378 # The recipients are the PI of the authority
379 #recipients = authority_get_pi_emails(request, authority_hrn)
380 recipients = ["support@myslice.info"]
381 requester = request.user # current user
382 sender = 'yasin.upmc@gmail.com' # the server email
383 msg = "OneLab user %s requested account in Wilab Platform" % requester
384 send_mail("Onelab user %s requested an account in Wilab"%requester , msg, sender, recipients)
385 messages.info(request, 'Request to get access on Wilab platform received. Please wait for PI\'s reply.')
386 return HttpResponseRedirect("/portal/account/")
388 elif 'iotlab' in request.POST:
389 # The recipients are the PI of the authority
390 #recipients = authority_get_pi_emails(request, authority_hrn)
391 recipients = ["support@myslice.info"]
392 requester = request.user # current user
393 sender = 'yasin.upmc@gmail.com' # the server email
394 msg = "OneLab user %s requested account in IOTLab Platform" % requester
395 send_mail("Onelab user %s requested an account in IOTLab"%requester , msg, sender, recipients)
396 messages.info(request, 'Request to get access on IOTLab platform received. Please wait for PI\'s reply.')
397 return HttpResponseRedirect("/portal/account/")
400 messages.info(request, 'Under Construction. Please try again later!')
401 return HttpResponseRedirect("/portal/account/")