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