Merged My Account css, changed the html name to account-view.html
[myslice.git] / portal / accountview.py
1 from portal.templateviews            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
6 #
7 from myslice.viewutils               import topmenu_items, the_user
8 #
9 from django.http                     import HttpResponse
10 from django.contrib.auth.decorators  import login_required
11 import json
12
13 # requires login
14 class AccountView(LoginRequiredAutoLogoutView):
15     template_name = "account-view.html"
16     
17     def dispatch(self, *args, **kwargs):
18         return super(AccountView, self).dispatch(*args, **kwargs)
19
20
21     def get_context_data(self, **kwargs):
22
23         user_query  = Query().get('local:user').select('config','email')
24         user_details = execute_query(self.request, user_query)
25         
26         # not always found in user_details...
27         config={}
28         for user_detail in user_details:
29             #email = user_detail['email']
30             if user_detail['config']:
31                 config = json.loads(user_detail['config'])
32
33         platform_query  = Query().get('local:platform').select('platform_id','platform')
34         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
35         platform_details = execute_query(self.request, platform_query)
36         account_details = execute_query(self.request, account_query)
37        
38         # initial assignment needed for users having no account  
39         platform_name = ''
40         account_type = ''
41         account_usr_hrn = ''
42         account_pub_key = ''
43         platform_name_list = []
44         account_type_list = []
45         usr_hrn_list = []
46         pub_key_list = []          
47         for account_detail in account_details:
48             for platform_detail in platform_details:
49                 if platform_detail['platform_id'] == account_detail['platform_id']:
50                     platform_name = platform_detail['platform']
51                     account_type = account_detail['auth_type']
52                     account_config = json.loads(account_detail['config'])
53                     # a bit more pythonic
54                     account_usr_hrn = account_config.get('user_hrn','N/A')
55                     account_pub_key = account_config.get('user_public_key','N/A')
56                     
57                     platform_name_list.append(platform_name)
58                     account_type_list.append(account_type)
59                     usr_hrn_list.append(account_usr_hrn)
60                     pub_key_list.append(account_pub_key)
61         
62         # combining 4 lists into 1 [to render in the template] 
63         lst = [{'platform_name': t[0], 'account_type': t[1], 'usr_hrn':t[2], 'usr_pubkey':t[3]} 
64                for t in zip(platform_name_list, account_type_list, usr_hrn_list, pub_key_list)]
65         #print "test"
66         #print lst
67
68         context = super(AccountView, self).get_context_data(**kwargs)
69         context['data'] = lst
70         context['person']   = self.request.user
71         context ['firstname'] = config.get('firstname',"?")
72         context ['lastname'] = config.get('lastname',"?")
73         context ['fullname'] = context['firstname'] +' '+ context['lastname']
74         context ['authority'] = config.get('authority',"Unknown Authority")
75         #context['users'] = userlist.render(self.request)
76         
77         # XXX This is repeated in all pages
78         # more general variables expected in the template
79         context['title'] = 'Platforms connected to MySlice'
80         # the menu items on the top
81         context['topmenu_items'] = topmenu_items('My Account', self.request)
82         # so we can sho who is logged
83         context['username'] = the_user(self.request)
84 #        context ['firstname'] = config['firstname']
85         #context.update(page.prelude_env())
86         return context
87
88
89 @login_required
90 #my_acc form value processing
91 def account_process(request):
92     user_query  = Query().get('local:user').select('password','config')
93     user_details = execute_query(request, user_query)
94
95     if 'submit_name' in request.POST:
96         edited_first_name =  request.POST['fname']
97         edited_last_name =  request.POST['lname']
98         
99         config={}
100         for user_config in user_details:
101         #email = user_detail['email']
102             if user_config['config']:
103                 config = json.loads(user_config['config'])
104                 config['firstname'] = edited_first_name
105                 config['lastname'] = edited_last_name
106                 config['authority'] = config.get('authority','Unknown Authority')
107                 updated_config = json.dumps(config)
108         
109         # updating config local:user in manifold       
110         user_params = { 'config': updated_config}
111         manifold_update_user(request,user_params)
112         # this will be depricated, we will show the success msg in same page
113         return HttpResponse('Sucess: First Name and Last Name Updated!')       
114     elif 'submit_pass' in request.POST:
115         edited_password = request.POST['password']
116         
117         for user_pass in user_details:
118             user_pass['password'] = edited_password
119         #updating password in local:user
120         user_params = { 'password': user_pass['password']}
121         manifold_update_user(request,user_params)
122
123         return HttpResponse('Success: Password Changed!!')
124     elif 'generate' in request.POST:
125         # Generate public and private keys using SFA Library
126         from sfa.trust.certificate  import Keypair
127         k = Keypair(create=True)
128         public_key = k.get_pubkey_string()
129         private_key = k.as_pem()
130         private_key = ''.join(private_key.split())
131         public_key = "ssh-rsa " + public_key
132         # Saving to DB
133         keypair = '{"user_public_key":"'+ public_key + '", "user_private_key":"'+ private_key + '"}'
134 #        keypair = re.sub("\r", "", keypair)
135 #        keypair = re.sub("\n", "\\n", keypair)
136 #        #keypair = keypair.rstrip('\r\n')
137 #        keypair = ''.join(keypair.split())
138         get_user.keypair = keypair
139         get_user.save()
140         return HttpResponse('Success: New Keypair Generated! %s' % keypair)
141
142     elif 'upload_key' in request.POST:
143         up_file = request.FILES['pubkey']
144         file_content =  up_file.read()
145         file_name = up_file.name
146         file_extension = os.path.splitext(file_name)[1] 
147         allowed_extension =  ['.pub','.txt']
148         if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
149             file_content = '{"user_public_key":"'+ file_content +'"}'
150             file_content = re.sub("\r", "", file_content)
151             file_content = re.sub("\n", "\\n",file_content)
152             file_content = ''.join(file_content.split())
153             get_user.keypair = file_content
154             get_user.save()
155             return HttpResponse('Success: Publickey uploaded! Old records overwritten')
156         else:
157             return HttpResponse('Please upload a valid RSA public key [.txt or .pub].')    
158         
159     else:
160         message = 'You submitted an empty form.'
161         return HttpResponse(message)