Statistics
| Branch: | Tag: | Revision:

root / flowspec / views.py @ 3bfa0ea6

History | View | Annotate | Download (12.9 kB)

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.contrib.auth import logout
11
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
12
from django.shortcuts import get_object_or_404, render_to_response
13
from django.core.context_processors import request
14
from django.template.context import RequestContext
15
from django.template.loader import get_template, render_to_string
16
from django.utils import simplejson
17
from django.core.urlresolvers import reverse
18
from django.contrib import messages
19
from flowspy.accounts.models import *
20

    
21
from django.contrib.auth import authenticate, login
22

    
23
from django.forms.models import model_to_dict
24

    
25
from flowspy.flowspec.forms import * 
26
from flowspy.flowspec.models import *
27

    
28
from copy import deepcopy
29
from flowspy.utils.decorators import shib_required
30

    
31
from django.views.decorators.cache import never_cache
32
from django.conf import settings
33
from django.core.mail import mail_admins, mail_managers, send_mail
34

    
35
import os
36

    
37
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
38
#FORMAT = '%(asctime)s %(levelname)s: %(message)s'
39
#logging.basicConfig(format=FORMAT)
40
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
41

    
42
logger = logging.getLogger(__name__)
43
logger.setLevel(logging.DEBUG)
44
handler = logging.FileHandler(LOG_FILENAME)
45
handler.setFormatter(formatter)
46
logger.addHandler(handler)
47

    
48
@login_required
49
def user_routes(request):
50
    user_routes = Route.objects.filter(applier=request.user)
51
    return render_to_response('user_routes.html', {'routes': user_routes},
52
                              context_instance=RequestContext(request))
53

    
54
def welcome(request):
55
    return render_to_response('welcome.html', context_instance=RequestContext(request))
56

    
57
@login_required
58
@never_cache
59
def group_routes(request):
60
    group_routes = []
61
    peer = request.user.get_profile().peer
62
    if peer:
63
       peer_members = UserProfile.objects.filter(peer=peer)
64
       users = [prof.user for prof in peer_members]
65
       group_routes = Route.objects.filter(applier__in=users)
66
    return render_to_response('user_routes.html', {'routes': group_routes},
67
                              context_instance=RequestContext(request))
68

    
69

    
70
@login_required
71
@never_cache
72
def add_route(request):
73
    applier = request.user.pk
74
    applier_peer_networks = request.user.get_profile().peer.networks.all()
75
    if not applier_peer_networks:
76
         messages.add_message(request, messages.WARNING,
77
                             "Insufficient rights on administrative networks. Cannot add rule. Contact your administrator")
78
         return HttpResponseRedirect(reverse("group-routes"))
79
    if request.method == "GET":
80
        form = RouteForm()
81
        return render_to_response('apply.html', {'form': form, 'applier': applier},
82
                                  context_instance=RequestContext(request))
83

    
84
    else:
85
        form = RouteForm(request.POST)
86
        if form.is_valid():
87
            route=form.save(commit=False)
88
            route.applier = request.user
89
            route.status = "PENDING"
90
            route.save()
91
            form.save_m2m()
92
            route.commit_add()
93
            mail_body = render_to_string("rule_add_mail.txt",
94
                                             {"route": route})
95
            send_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s creation request submitted by %s" %(route.name, route.applier.username),
96
                              mail_body, settings.SERVER_EMAIL,
97
                              get_peer_techc_mails(route.applier), fail_silently=True)
98
            logger.info(mail_body)
99
            return HttpResponseRedirect(reverse("group-routes"))
100
        else:
101
            return render_to_response('apply.html', {'form': form, 'applier':applier},
102
                                      context_instance=RequestContext(request))
103

    
104
@login_required
105
@never_cache
106
def edit_route(request, route_slug):
107
    applier = request.user.pk
108
    applier_peer = request.user.get_profile().peer
109
    route_edit = get_object_or_404(Route, name=route_slug)
110
    route_edit_applier_peer = route_edit.applier.get_profile().peer
111
    if applier_peer != route_edit_applier_peer:
112
        messages.add_message(request, messages.WARNING,
113
                             "Insufficient rights to edit rule %s" %(route_slug))
114
        return HttpResponseRedirect(reverse("group-routes"))
115
#    if route_edit.status == "ADMININACTIVE" :
116
#        messages.add_message(request, messages.WARNING,
117
#                             "Administrator has disabled editing of rule %s" %(route_slug))
118
#        return HttpResponseRedirect(reverse("group-routes"))
119
#    if route_edit.status == "EXPIRED" :
120
#        messages.add_message(request, messages.WARNING,
121
#                             "Cannot edit the expired rule %s. Contact helpdesk to enable it" %(route_slug))
122
#        return HttpResponseRedirect(reverse("group-routes"))
123
    if route_edit.status == "PENDING" :
124
        messages.add_message(request, messages.WARNING,
125
                             "Cannot edit a pending rule: %s." %(route_slug))
126
        return HttpResponseRedirect(reverse("group-routes"))
127
    route_original = deepcopy(route_edit)
128
    if request.POST:
129
        form = RouteForm(request.POST, instance = route_edit)
130
        if form.is_valid():
131
            route=form.save(commit=False)
132
            route.name = route_original.name
133
            route.applier = request.user
134
            route.status = "PENDING"
135
            route.save()
136
            form.save_m2m()
137
            route.commit_edit()
138
            mail_body = render_to_string("rule_edit_mail.txt",
139
                                             {"route": route})
140
            send_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s edit request submitted by %s" %(route.name, route.applier.username),
141
                              mail_body, settings.SERVER_EMAIL,
142
                              get_peer_techc_mails(route.applier), fail_silently=True)
143
            logger.info(mail_body)
144

    
145
            return HttpResponseRedirect(reverse("group-routes"))
146
        else:
147
            return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
148
                                      context_instance=RequestContext(request))
149
    else:
150
        dictionary = model_to_dict(route_edit, fields=[], exclude=[])
151
        #form = RouteForm(instance=route_edit)
152
        form = RouteForm(dictionary)
153
        return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
154
                                  context_instance=RequestContext(request))
155

    
156
@login_required
157
@never_cache
158
def delete_route(request, route_slug):
159
    if request.is_ajax():
160
        route = get_object_or_404(Route, name=route_slug)
161
        applier_peer = route.applier.get_profile().peer
162
        requester_peer = request.user.get_profile().peer
163
        if applier_peer == requester_peer:
164
            route.status = "PENDING"
165
            route.save()
166
            route.commit_delete()
167
            mail_body = render_to_string("rule_delete_mail.txt",
168
                                             {"route": route})
169
            send_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s removal request submitted by %s" %(route.name, route.applier.username),
170
                              mail_body, settings.SERVER_EMAIL,
171
                             get_peer_techc_mails(route.applier), fail_silently=True)            
172
            logger.info(mail_body)
173
        html = "<html><body>Done</body></html>"
174
        return HttpResponse(html)
175
    else:
176
        return HttpResponseRedirect(reverse("group-routes"))
177

    
178
@login_required
179
@never_cache
180
def user_profile(request):
181
    user = request.user
182
    peer = request.user.get_profile().peer
183
    
184
    return render_to_response('profile.html', {'user': user, 'peer':peer},
185
                                  context_instance=RequestContext(request))
186

    
187
@never_cache
188
def user_login(request):
189
    try:
190
        error_username = None
191
        error_orgname = None
192
        error_affiliation = None
193
        error = ''
194
        username = request.META['HTTP_EPPN']
195
        if not username:
196
            error_username = True
197
        firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
198
        lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
199
        mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
200
        organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
201
        affiliation = request.META['HTTP_SHIB_EP_ENTITLEMENT']
202
        if settings.SHIB_AUTH_AFFILIATION in affiliation.split(";"):
203
            has_affiliation = True
204
        if not has_affiliation:
205
            error_affiliation = True
206
        if not organization:
207
            error_orgname = True
208
        if error_username:
209
            error = "Your idP should release the HTTP_EPPN attribute towards this service\n"
210
        if error_orgname:
211
            error = error + "Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service\n"
212
        if error_affiliation:
213
            error = error + "Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service"
214
        if error_username or error_orgname or error_affiliation:
215
            return render_to_response('error.html', {'error': error,},
216
                                  context_instance=RequestContext(request))
217
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, organization=organization, affiliation=affiliation)
218
        if user is not None:
219
            login(request, user)
220
            update_user_attributes(user, firstname=firstname, lastname=lastname, mail=mail)
221
            return HttpResponseRedirect(reverse("group-routes"))
222
                # Redirect to a success page.
223
                # Return a 'disabled account' error message
224
        else:
225
            error = "Something went wrong during user authentication. Contact your administrator"
226
            return render_to_response('error.html', {'error': error,},
227
                                  context_instance=RequestContext(request))
228
    except Exception as e:
229
        error = "Invalid login procedure"
230
        return render_to_response('error.html', {'error': error,},
231
                                  context_instance=RequestContext(request))
232
        # Return an 'invalid login' error message.
233
#    return HttpResponseRedirect(reverse("user-routes"))
234

    
235
@login_required
236
@never_cache
237
def add_rate_limit(request):
238
    if request.method == "GET":
239
        form = ThenPlainForm()
240
        return render_to_response('add_rate_limit.html', {'form': form,},
241
                                  context_instance=RequestContext(request))
242

    
243
    else:
244
        form = ThenPlainForm(request.POST)
245
        if form.is_valid():
246
            then=form.save(commit=False)
247
            then.action_value = "%sk"%then.action_value
248
            then.save()
249
            response_data = {}
250
            response_data['pk'] = "%s" %then.pk
251
            response_data['value'] = "%s:%s" %(then.action, then.action_value)
252
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
253
        else:
254
            return render_to_response('add_rate_limit.html', {'form': form,},
255
                                      context_instance=RequestContext(request))
256
            
257
def update_user_attributes(user, firstname, lastname, mail):
258
    user.first_name = firstname
259
    user.last_name = lastname
260
    user.email = mail
261
    user.save()
262

    
263
@login_required
264
@never_cache
265
def add_port(request):
266
    if request.method == "GET":
267
        form = PortPlainForm()
268
        return render_to_response('add_port.html', {'form': form,},
269
                                  context_instance=RequestContext(request))
270

    
271
    else:
272
        form = PortPlainForm(request.POST)
273
        if form.is_valid():
274
            port=form.save()
275
            response_data = {}
276
            response_data['value'] = "%s" %port.pk
277
            response_data['text'] = "%s" %port.port
278
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
279
        else:
280
            return render_to_response('add_port.html', {'form': form,},
281
                                      context_instance=RequestContext(request))
282

    
283
@login_required
284
@never_cache
285
def user_logout(request):
286
    logout(request)
287
    return HttpResponseRedirect(reverse('group-routes'))
288
    
289
@never_cache
290
def load_jscript(request, file):
291
    long_polling_timeout = int(settings.POLL_SESSION_UPDATE)*1000 + 10000
292
    return render_to_response('%s.js' % file, {'timeout': long_polling_timeout}, context_instance=RequestContext(request), mimetype="text/javascript")
293

    
294

    
295
def get_peer_techc_mails(user):
296
    user_mail = user.email
297
    techmails = user.get_profile().peer.techc()
298
    additional_mail = "%s;%s" %(settings.HELPDESK_MAIL,settings.NOC_MAIL) 
299
    if techmails:
300
        mail = "%s;%s" %(techmails, additional_mail)
301
    else:
302
        mail = additional_mail
303
    mail = "%s;%s" %(user_mail, mail)
304
    mail =  mail.split(';')
305
    return mail