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
16 class AccountView(LoginRequiredAutoLogoutView):
17 template_name = "account-view.html"
19 def dispatch(self, *args, **kwargs):
20 return super(AccountView, self).dispatch(*args, **kwargs)
23 def get_context_data(self, **kwargs):
25 user_query = Query().get('local:user').select('config','email')
26 user_details = execute_query(self.request, user_query)
28 # not always found in user_details...
30 for user_detail in user_details:
31 #email = user_detail['email']
32 if user_detail['config']:
33 config = json.loads(user_detail['config'])
35 platform_query = Query().get('local:platform').select('platform_id','platform')
36 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
37 platform_details = execute_query(self.request, platform_query)
38 account_details = execute_query(self.request, account_query)
40 # initial assignment needed for users having no account
45 platform_name_list = []
46 account_type_list = []
47 delegation_type_list = []
50 for account_detail in account_details:
51 for platform_detail in platform_details:
52 if platform_detail['platform_id'] == account_detail['platform_id']:
53 platform_name = platform_detail['platform']
54 if 'reference' in account_detail['auth_type']:
55 account_type = 'Reference'
57 elif 'managed' in account_detail['auth_type']:
58 account_type = 'Principal'
59 delegation = 'Automatic'
61 account_type = 'Principal'
63 account_config = json.loads(account_detail['config'])
65 account_usr_hrn = account_config.get('user_hrn','N/A')
66 account_pub_key = account_config.get('user_public_key','N/A')
68 platform_name_list.append(platform_name)
69 account_type_list.append(account_type)
70 delegation_type_list.append(delegation)
71 usr_hrn_list.append(account_usr_hrn)
72 pub_key_list.append(account_pub_key)
74 # to hide private key row if it doesn't exist
75 if 'myslice' in platform_detail['platform']:
76 account_config = json.loads(account_detail['config'])
77 account_priv_key = account_config.get('user_private_key','N/A')
79 print account_priv_key
82 # combining 5 lists into 1 [to render in the template]
83 lst = [{'platform_name': t[0], 'account_type': t[1], 'delegation_type': t[2], 'usr_hrn':t[3], 'usr_pubkey':t[4]}
84 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list)]
86 context = super(AccountView, self).get_context_data(**kwargs)
88 context['person'] = self.request.user
89 context ['firstname'] = config.get('firstname',"?")
90 context ['lastname'] = config.get('lastname',"?")
91 context ['fullname'] = context['firstname'] +' '+ context['lastname']
92 context ['authority'] = config.get('authority',"Unknown Authority")
93 context['user_private_key'] = account_priv_key
95 # XXX This is repeated in all pages
96 # more general variables expected in the template
97 context['title'] = 'Platforms connected to MySlice'
98 # the menu items on the top
99 context['topmenu_items'] = topmenu_items('My Account', self.request)
100 # so we can sho who is logged
101 context['username'] = the_user(self.request)
102 # context ['firstname'] = config['firstname']
103 #context.update(page.prelude_env())
108 #my_acc form value processing
109 def account_process(request):
110 user_query = Query().get('local:user').select('password','config')
111 user_details = execute_query(request, user_query)
113 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
114 account_details = execute_query(request, account_query)
116 platform_query = Query().get('local:platform').select('platform_id','platform')
117 platform_details = execute_query(request, platform_query)
119 # for account_detail in account_details:
120 # if account_detail['platform_id'] == 5:
121 # account_config = json.loads(account_detail['config'])
123 if 'submit_name' in request.POST:
124 edited_first_name = request.POST['fname']
125 edited_last_name = request.POST['lname']
128 for user_config in user_details:
129 #email = user_detail['email']
130 if user_config['config']:
131 config = json.loads(user_config['config'])
132 config['firstname'] = edited_first_name
133 config['lastname'] = edited_last_name
134 config['authority'] = config.get('authority','Unknown Authority')
135 updated_config = json.dumps(config)
136 user_params = {'config': updated_config}
137 else: # it's needed if the config is empty
138 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
139 user_params = {'config': user_config['config']}
140 # updating config local:user in manifold
141 #user_params = { 'config': updated_config}
142 manifold_update_user(request,user_params)
143 # this will be depricated, we will show the success msg in same page
144 # return HttpResponse('Sucess: First Name and Last Name Updated!')
145 # Redirect to same page with success message
146 messages.success(request, 'Sucess: First Name and Last Name Updated.')
147 return HttpResponseRedirect("/portal/account/")
149 elif 'submit_pass' in request.POST:
150 edited_password = request.POST['password']
152 for user_pass in user_details:
153 user_pass['password'] = edited_password
154 #updating password in local:user
155 user_params = { 'password': user_pass['password']}
156 manifold_update_user(request,user_params)
157 # return HttpResponse('Success: Password Changed!!')
158 messages.success(request, 'Sucess: Password Updated.')
159 return HttpResponseRedirect("/portal/account/")
161 # XXX TODO: Factorize with portal/registrationview.py
163 elif 'generate' in request.POST:
164 for account_detail in account_details:
165 for platform_detail in platform_details:
166 if platform_detail['platform_id'] == account_detail['platform_id']:
167 if 'myslice' in platform_detail['platform']:
168 from Crypto.PublicKey import RSA
169 private = RSA.generate(1024)
170 private_key = json.dumps(private.exportKey())
171 public = private.publickey()
172 public_key = json.dumps(public.exportKey(format='OpenSSH'))
173 # Generate public and private keys using SFA Library
174 # from sfa.trust.certificate import Keypair
175 # k = Keypair(create=True)
176 # public_key = k.get_pubkey_string()
177 # private_key = k.as_pem()
178 # private_key = ''.join(private_key.split())
179 # public_key = "ssh-rsa " + public_key
180 # now we overwrite the config field with keypair
181 # once there will be user_hrn, we need to keep user_hrn and change only the keypair
182 # see submit_name section for implementing this
183 # keypair = re.sub("\r", "", keypair)
184 # keypair = re.sub("\n", "\\n", keypair)
185 # #keypair = keypair.rstrip('\r\n')
186 # keypair = ''.join(keypair.split())
187 # updating maniolf local:account table
188 account_config = json.loads(account_detail['config'])
189 # preserving user_hrn
190 user_hrn = account_config.get('user_hrn','N/A')
191 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
192 updated_config = json.dumps(account_config)
194 user_params = { 'config': keypair, 'auth_type':'managed'}
195 manifold_update_account(request,user_params)
196 messages.success(request, 'Sucess: New Keypair Generated!')
197 return HttpResponseRedirect("/portal/account/")
199 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
200 return HttpResponseRedirect("/portal/account/")
202 elif 'upload_key' in request.POST:
203 for account_detail in account_details:
204 for platform_detail in platform_details:
205 if platform_detail['platform_id'] == account_detail['platform_id']:
206 if 'myslice' in platform_detail['platform']:
207 up_file = request.FILES['pubkey']
208 file_content = up_file.read()
209 file_name = up_file.name
210 file_extension = os.path.splitext(file_name)[1]
211 allowed_extension = ['.pub','.txt']
212 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
213 account_config = json.loads(account_detail['config'])
214 # preserving user_hrn
215 user_hrn = account_config.get('user_hrn','N/A')
216 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
217 #file_content = re.sub("\r", "", file_content)
218 #file_content = re.sub("\n", "\\n",file_content)
219 file_content = ''.join(file_content.split())
220 #update manifold local:account table
221 user_params = { 'config': file_content, 'auth_type':'user'}
222 manifold_update_account(request,user_params)
223 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
224 return HttpResponseRedirect("/portal/account/")
226 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
227 return HttpResponseRedirect("/portal/account/")
229 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
230 return HttpResponseRedirect("/portal/account/")
232 elif 'dl_pubkey' in request.POST:
233 for account_detail in account_details:
234 for platform_detail in platform_details:
235 if platform_detail['platform_id'] == account_detail['platform_id']:
236 if 'myslice' in platform_detail['platform']:
237 account_config = json.loads(account_detail['config'])
238 public_key = account_config['user_public_key']
239 response = HttpResponse(public_key, content_type='text/plain')
240 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
244 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
245 return HttpResponseRedirect("/portal/account/")
247 elif 'dl_pkey' in request.POST:
248 for account_detail in account_details:
249 for platform_detail in platform_details:
250 if platform_detail['platform_id'] == account_detail['platform_id']:
251 if 'myslice' in platform_detail['platform']:
252 account_config = json.loads(account_detail['config'])
253 if 'user_private_key' in account_config:
254 private_key = account_config['user_private_key']
255 response = HttpResponse(private_key, content_type='text/plain')
256 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
259 messages.error(request, 'Download error: Private key is not stored in the server')
260 return HttpResponseRedirect("/portal/account/")
263 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
264 return HttpResponseRedirect("/portal/account/")
266 elif 'delete' in request.POST:
267 for account_detail in account_details:
268 for platform_detail in platform_details:
269 if platform_detail['platform_id'] == account_detail['platform_id']:
270 if 'myslice' in platform_detail['platform']:
271 account_config = json.loads(account_detail['config'])
272 if 'user_private_key' in account_config:
273 for key in account_config.keys():
274 if key== 'user_private_key':
275 del account_config[key]
277 updated_config = json.dumps(account_config)
278 user_params = { 'config': updated_config, 'auth_type':'user'}
279 manifold_update_account(request,user_params)
280 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
281 return HttpResponseRedirect("/portal/account/")
283 messages.error(request, 'Delete error: Private key is not stored in the server')
284 return HttpResponseRedirect("/portal/account/")
287 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
288 return HttpResponseRedirect("/portal/account/")
292 messages.info(request, 'Under Construction. Please try again later!')
293 return HttpResponseRedirect("/portal/account/")