Added a save to current status while deleting a job
[flowspy] / flowspec / views.py
1 # Create your views here.
2 import urllib2
3 import socket
4 import json
5 from django import forms
6 from django.views.decorators.csrf import csrf_exempt
7 from django.core import urlresolvers
8 from django.core import serializers
9 from django.contrib.auth.decorators import login_required
10 from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
11 from django.shortcuts import get_object_or_404, render_to_response
12 from django.core.context_processors import request
13 from django.template.context import RequestContext
14 from django.template.loader import get_template, render_to_string
15 from django.utils import simplejson
16 from django.core.urlresolvers import reverse
17 from django.contrib import messages
18 from flowspy.accounts.models import *
19
20 from django.contrib.auth import authenticate, login
21
22 from django.forms.models import model_to_dict
23
24 from flowspy.flowspec.forms import * 
25 from flowspy.flowspec.models import *
26
27 from copy import deepcopy
28 from flowspy.utils.decorators import shib_required
29
30 from django.views.decorators.cache import never_cache
31 from django.conf import settings
32 from django.core.mail import mail_admins, mail_managers, send_mail
33
34
35 @login_required
36 def user_routes(request):
37     user_routes = Route.objects.filter(applier=request.user)
38     return render_to_response('user_routes.html', {'routes': user_routes},
39                               context_instance=RequestContext(request))
40
41 def welcome(request):
42     return render_to_response('welcome.html', context_instance=RequestContext(request))
43
44 @login_required
45 @never_cache
46 def group_routes(request):
47     group_routes = []
48     peer = request.user.get_profile().peer
49     if peer:
50        peer_members = UserProfile.objects.filter(peer=peer)
51        users = [prof.user for prof in peer_members]
52        group_routes = Route.objects.filter(applier__in=users)
53     return render_to_response('user_routes.html', {'routes': group_routes},
54                               context_instance=RequestContext(request))
55
56
57 @login_required
58 @never_cache
59 def add_route(request):
60     applier = request.user.pk
61     applier_peer_networks = request.user.get_profile().peer.networks.all()
62     if not applier_peer_networks:
63          messages.add_message(request, messages.WARNING,
64                              "Insufficient rights on administrative networks. Cannot add rule. Contact your administrator")
65          return HttpResponseRedirect(reverse("group-routes"))
66     if request.method == "GET":
67         form = RouteForm()
68         return render_to_response('apply.html', {'form': form, 'applier': applier},
69                                   context_instance=RequestContext(request))
70
71     else:
72         form = RouteForm(request.POST)
73         if form.is_valid():
74             route=form.save(commit=False)
75             route.applier = request.user
76             route.status = "PENDING"
77             route.save()
78             form.save_m2m()
79             route.commit_add()
80             mail_body = render_to_string("rule_add_mail.txt",
81                                              {"route": route})
82             mail_admins("Rule %s creation request submitted by %s" %(route.name, route.applier.username),
83                           mail_body, fail_silently=True)
84             return HttpResponseRedirect(reverse("group-routes"))
85         else:
86             return render_to_response('apply.html', {'form': form, 'applier':applier},
87                                       context_instance=RequestContext(request))
88
89 @login_required
90 @never_cache
91 def edit_route(request, route_slug):
92     applier = request.user.pk
93     applier_peer = request.user.get_profile().peer
94     route_edit = get_object_or_404(Route, name=route_slug)
95     route_edit_applier_peer = route_edit.applier.get_profile().peer
96     if applier_peer != route_edit_applier_peer:
97         messages.add_message(request, messages.WARNING,
98                              "Insufficient rights to edit rule %s" %(route_slug))
99         return HttpResponseRedirect(reverse("group-routes"))
100     if route_edit.status == "ADMININACTIVE" :
101         messages.add_message(request, messages.WARNING,
102                              "Administrator has disabled editing of rule %s" %(route_slug))
103         return HttpResponseRedirect(reverse("group-routes"))
104     if route_edit.status == "EXPIRED" :
105         messages.add_message(request, messages.WARNING,
106                              "Cannot edit the expired rule %s. Contact helpdesk to enable it" %(route_slug))
107         return HttpResponseRedirect(reverse("group-routes"))
108     if route_edit.status == "PENDING" :
109         messages.add_message(request, messages.WARNING,
110                              "Cannot edit a pending rule: %s." %(route_slug))
111         return HttpResponseRedirect(reverse("group-routes"))
112     route_original = deepcopy(route_edit)
113     if request.POST:
114         form = RouteForm(request.POST, instance = route_edit)
115         if form.is_valid():
116             route=form.save(commit=False)
117             route.name = route_original.name
118             route.applier = request.user
119             route.status = "PENDING"
120             route.save()
121             form.save_m2m()
122             route.commit_edit()
123             mail_body = render_to_string("rule_edit_mail.txt",
124                                              {"route": route})
125             mail_admins("Rule %s edit request submitted by %s" %(route.name, route.applier.username),
126                           mail_body, fail_silently=True)
127             return HttpResponseRedirect(reverse("group-routes"))
128         else:
129             return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
130                                       context_instance=RequestContext(request))
131     else:
132         dictionary = model_to_dict(route_edit, fields=[], exclude=[])
133         #form = RouteForm(instance=route_edit)
134         form = RouteForm(dictionary)
135         return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
136                                   context_instance=RequestContext(request))
137
138 @login_required
139 @never_cache
140 def delete_route(request, route_slug):
141     if request.is_ajax():
142         route = get_object_or_404(Route, name=route_slug)
143         applier_peer = route.applier.get_profile().peer
144         requester_peer = request.user.get_profile().peer
145         if applier_peer == requester_peer:
146             route.status = "PENDING"
147             route.save()
148             route.commit_delete()
149             mail_body = render_to_string("rule_delete_mail.txt",
150                                              {"route": route})
151             mail_admins("Rule %s removal request submitted by %s" %(route.name, route.applier.username),
152                           mail_body, fail_silently=True)
153         html = "<html><body>Done</body></html>"
154         return HttpResponse(html)
155     else:
156         return HttpResponseRedirect(reverse("group-routes"))
157
158 @login_required
159 @never_cache
160 def user_profile(request):
161     user = request.user
162     peer = request.user.get_profile().peer
163     
164     return render_to_response('profile.html', {'user': user, 'peer':peer},
165                                   context_instance=RequestContext(request))
166
167 @never_cache
168 def user_login(request):
169     try:
170         error_username = None
171         error_orgname = None
172         error_affiliation = None
173         error = ''
174         username = request.META['HTTP_EPPN']
175         if not username:
176             error_username = True
177         firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
178         lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
179         mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
180         organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
181         affiliation = request.META['HTTP_SHIB_EP_ENTITLEMENT']
182         if settings.SHIB_AUTH_AFFILIATION in affiliation.split(";"):
183             has_affiliation = True
184         if not has_affiliation:
185             error_affiliation = True
186         if not organization:
187             error_orgname = True
188         if error_username:
189             error = "Your idP should release the HTTP_EPPN attribute towards this service\n"
190         if error_orgname:
191             error = error + "Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service\n"
192         if error_affiliation:
193             error = error + "Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service"
194         if error_username or error_orgname or error_affiliation:
195             return render_to_response('error.html', {'error': error,},
196                                   context_instance=RequestContext(request))
197         user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, organization=organization, affiliation=affiliation)
198         if user is not None:
199             login(request, user)
200             update_user_attributes(user, firstname=firstname, lastname=lastname, mail=mail)
201             return HttpResponseRedirect(reverse("group-routes"))
202                 # Redirect to a success page.
203                 # Return a 'disabled account' error message
204         else:
205             error = "Something went wrong during user authentication. Contact your administrator"
206             return render_to_response('error.html', {'error': error,},
207                                   context_instance=RequestContext(request))
208     except Exception as e:
209         error = "Invalid login procedure"
210         return render_to_response('error.html', {'error': error,},
211                                   context_instance=RequestContext(request))
212         # Return an 'invalid login' error message.
213 #    return HttpResponseRedirect(reverse("user-routes"))
214
215 @login_required
216 @never_cache
217 def add_rate_limit(request):
218     if request.method == "GET":
219         form = ThenPlainForm()
220         return render_to_response('add_rate_limit.html', {'form': form,},
221                                   context_instance=RequestContext(request))
222
223     else:
224         form = ThenPlainForm(request.POST)
225         if form.is_valid():
226             then=form.save(commit=False)
227             then.action_value = "%sk"%then.action_value
228             then.save()
229             response_data = {}
230             response_data['pk'] = "%s" %then.pk
231             response_data['value'] = "%s:%s" %(then.action, then.action_value)
232             return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
233         else:
234             return render_to_response('add_rate_limit.html', {'form': form,},
235                                       context_instance=RequestContext(request))
236             
237 def update_user_attributes(user, firstname, lastname, mail):
238     user.first_name = firstname
239     user.last_name = lastname
240     user.email = mail
241     user.save()
242
243 @login_required
244 @never_cache
245 def add_port(request):
246     if request.method == "GET":
247         form = PortPlainForm()
248         return render_to_response('add_port.html', {'form': form,},
249                                   context_instance=RequestContext(request))
250
251     else:
252         form = PortPlainForm(request.POST)
253         if form.is_valid():
254             port=form.save()
255             response_data = {}
256             response_data['value'] = "%s" %port.pk
257             response_data['text'] = "%s" %port.port
258             return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
259         else:
260             return render_to_response('add_port.html', {'form': form,},
261                                       context_instance=RequestContext(request))
262
263 @login_required
264 @never_cache
265 def user_logout(request):
266     return HttpResponseRedirect(settings.SHIB_LOGOUT_URL)
267     
268 @never_cache
269 def load_jscript(request, file):
270     return render_to_response('%s.js' % file, context_instance=RequestContext(request), mimetype="text/javascript")