Project emails: generic template works for both onelab and f4f
[myslice.git] / portal / projectrequestview.py
1 import json
2 import time
3 import re
4
5 from django.shortcuts           import render
6 from django.contrib.sites.models import Site
7
8 from manifold.core.query        import Query
9 from manifoldapi.manifoldapi    import execute_admin_query, execute_query
10
11 from unfold.loginrequired       import LoginRequiredAutoLogoutView
12
13 from portal.actions import create_pending_project, create_pending_join, sfa_add_authority, authority_add_pis, is_pi
14 from portal.models import PendingProject, PendingJoin
15
16 from myslice.theme import ThemeView
17 from myslice.settings import logger
18
19 class ProjectRequestView(LoginRequiredAutoLogoutView, ThemeView):
20     template_name = 'projectrequest_view.html'
21     
22     def getAuthorities(self, request):
23         #if self.theme == 'fed4fire':
24         authorities_query = Query.get('myslice:authority').select('authority_hrn')
25         #else:
26         #    authorities_query = Query.get('authority').select('name', 'authority_hrn')
27         authorities = execute_admin_query(request, authorities_query)
28         if authorities is not None:
29             # Remove the root authority from the list
30             matching = [s for s in authorities if "." in s['authority_hrn']]
31             authorities = sorted(matching, key=lambda k: k['authority_hrn'])
32             #if self.theme != 'fed4fire':
33             #    authorities = sorted(matching, key=lambda k: k['name'])
34         return authorities
35     
36     def getUserAuthority(self, request):
37         # Get user_email (XXX Would deserve to be simplified)
38         user_query  = Query().get('local:user').select('email','config')
39         user_details = execute_query(request, user_query)
40         for user_detail in user_details:
41             user_config = json.loads(user_detail['config'])
42             user_authority = user_config.get('authority','N/A')
43         return user_authority
44     
45     def getUserHrn(self, request):
46         user_hrn = None
47         
48         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
49         account_details = execute_query(request, account_query)
50
51         platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
52         platform_details = execute_query(request, platform_query)
53         
54         # getting user_hrn from local:account
55         for account_detail in account_details:
56             for platform_detail in platform_details:
57                 if platform_detail['platform_id'] == account_detail['platform_id']:
58                     # taking user_hrn only from myslice account
59                     # NOTE: we should later handle accounts filter_by auth_type= managed OR user
60                     if 'myslice' in platform_detail['platform']:
61                         account_config = json.loads(account_detail['config'])
62                         user_hrn = account_config.get('user_hrn','N/A')
63         return user_hrn        
64
65     def getUserEmail(self, request):
66         # Get user_email (XXX Would deserve to be simplified)
67         user_query  = Query().get('local:user').select('email','config')
68         user_details = execute_query(request, user_query)
69         user_email = user_details[0].get('email')
70         return user_email
71                    
72     def post(self, request):
73         return self.handle_request(request, 'POST')
74
75     def get(self, request):
76         return self.handle_request(request, 'GET')
77
78     def handle_request(self, wsgi_request, method):
79         errors = []
80         authority_hrn = None
81         authority_name = None
82         
83         #errors.append(wsgi_request.POST)
84
85         user_hrn = self.getUserHrn(wsgi_request)
86
87         user_email = self.getUserEmail(wsgi_request)
88         
89         authorities = self.getAuthorities(wsgi_request)
90         
91         user_authority = self.getUserAuthority(wsgi_request)
92         
93         # getting the org from authority
94         #for authority in authorities:
95         #    if authority['authority_hrn'] == user_authority:
96         #        authority_name = authority['name']
97         
98         if method == 'POST' :
99
100             project_name = wsgi_request.POST.get('project_name', '')
101             if not project_name or len(project_name) == 0 :
102                 errors.append('Project name can\'t be empty')
103
104             # accept only lowercase names
105             project_name = project_name.lower()
106
107             if 'join' in wsgi_request.POST:
108                 post = {
109                     'user_hrn'          : user_hrn,
110                     'email'             : user_email,
111                     'project_name'      : project_name,
112                     'authority_hrn'     : project_name,
113                 }
114
115             else:
116                 post = {
117                     'user_hrn'          : user_hrn,
118                     'email'             : user_email,
119                     'authority_hrn'     : wsgi_request.POST.get('authority_name', ''),
120                     'project_name'      : project_name,
121                     'purpose'           : wsgi_request.POST.get('purpose', ''),
122                 }
123
124                 # for new projects max project_name length is 10
125                 if (len(post['project_name']) >10):
126                     errors.append('Project name can be maximum 10 characters long')
127
128                 #if (post['authority_hrn'] is None or post['authority_hrn'] == ''):
129                 #    errors.append('Organization is mandatory')
130     
131                 if post['purpose'] is None or post['purpose'] == '':
132                     errors.append('Project purpose is mandatory')
133
134                 if re.search(r'^[A-Za-z0-9_]*$', post['project_name']) is None:
135                     errors.append('Project name may contain only letters, numbers, and underscore.')
136
137             # What kind of project name is valid?
138             if post['project_name'] is None or post['project_name'] == '':
139                 errors.append('Project name is mandatory')   
140             
141             if not errors:
142                 logger.info("is_pi on auth_hrn = {}".format(user_authority))
143                 if is_pi(wsgi_request, user_hrn, post['authority_hrn']):
144                     # PIs can directly create/join project in their own authority...
145                     if 'join' in wsgi_request.POST:
146                         # join existing project
147                         authority_add_pis(wsgi_request, post['project_name'], user_hrn)
148                     else:
149                         # Create project
150                         hrn = post['authority_hrn'] + '.' + post['project_name']
151                         sfa_add_authority(wsgi_request, {'authority_hrn':hrn})
152                         authority_add_pis(wsgi_request, hrn, user_hrn)
153                     self.template_name = 'project-request-done-view.html'
154                 else:
155                     # Otherwise a wsgi_request is sent to the PI
156                     if 'join' in wsgi_request.POST:
157                         create_pending_join(wsgi_request, post)
158                     else:
159                         create_pending_project(wsgi_request, post)
160                     self.template_name = 'project-request-ack-view.html'
161
162         # retrieves the pending projects creation list
163         pending_projects = PendingProject.objects.all().filter(user_hrn=user_hrn)
164         # retrieves the pending join a project list
165         pending_join_projects = PendingJoin.objects.all().filter(user_hrn=user_hrn)
166
167         root_authority = user_authority.split('.', 1)[0]                  
168         env = {
169                'errors':        errors,
170                'username':      wsgi_request.user,
171                'theme':         self.theme,
172                'authorities':   authorities,
173                'authority_hrn': user_authority,
174                'root_authority_hrn': root_authority,
175                'pending_projects': pending_projects,
176                'pending_join_projects': pending_join_projects,
177         }
178         return render(wsgi_request, self.template, env)