Statistics
| Branch: | Tag: | Revision:

root / flowspec / views.py @ 357e5b54

History | View | Annotate | Download (16.7 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.contrib.sites.models import Site
12
from django.contrib.auth.models import User
13
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
14
from django.shortcuts import get_object_or_404, render_to_response
15
from django.core.context_processors import request
16
from django.template.context import RequestContext
17
from django.template.loader import get_template, render_to_string
18
from django.utils import simplejson
19
from django.core.urlresolvers import reverse
20
from django.contrib import messages
21
from flowspy.accounts.models import *
22
from ipaddr import *
23

    
24
from django.contrib.auth import authenticate, login
25

    
26
from django.forms.models import model_to_dict
27

    
28
from flowspy.flowspec.forms import * 
29
from flowspy.flowspec.models import *
30
from registration.models import RegistrationProfile
31

    
32
from copy import deepcopy
33
from flowspy.utils.decorators import shib_required
34

    
35
from django.views.decorators.cache import never_cache
36
from django.conf import settings
37
from django.core.mail.message import EmailMessage
38
import datetime
39
import os
40

    
41
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
42
#FORMAT = '%(asctime)s %(levelname)s: %(message)s'
43
#logging.basicConfig(format=FORMAT)
44
formatter = logging.Formatter('%(asctime)s %(levelname)s %(clientip)s %(user)s: %(message)s')
45

    
46
logger = logging.getLogger(__name__)
47
logger.setLevel(logging.DEBUG)
48
handler = logging.FileHandler(LOG_FILENAME)
49
handler.setFormatter(formatter)
50
logger.addHandler(handler)
51

    
52
@login_required
53
def user_routes(request):
54
    user_routes = Route.objects.filter(applier=request.user)
55
    return render_to_response('user_routes.html', {'routes': user_routes},
56
                              context_instance=RequestContext(request))
57

    
58
def welcome(request):
59
    return render_to_response('welcome.html', context_instance=RequestContext(request))
60

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

    
73

    
74
@login_required
75
@never_cache
76
def add_route(request):
77
    applier = request.user.pk
78
    applier_peer_networks = request.user.get_profile().peer.networks.all()
79
    if not applier_peer_networks:
80
         messages.add_message(request, messages.WARNING,
81
                             "Insufficient rights on administrative networks. Cannot add rule. Contact your administrator")
82
         return HttpResponseRedirect(reverse("group-routes"))
83
    if request.method == "GET":
84
        form = RouteForm()
85
        if not request.user.is_superuser:
86
            form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
87
        return render_to_response('apply.html', {'form': form, 'applier': applier},
88
                                  context_instance=RequestContext(request))
89

    
90
    else:
91
        form = RouteForm(request.POST)
92
        if form.is_valid():
93
            route=form.save(commit=False)
94
            route.applier = request.user
95
            route.status = "PENDING"
96
            route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
97
            route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
98
            route.save()
99
            form.save_m2m()
100
            route.commit_add()
101
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
102
            mail_body = render_to_string("rule_add_mail.txt",
103
                                             {"route": route, "address": requesters_address})
104
            user_mail = "%s" %route.applier.email
105
            user_mail = user_mail.split(';')
106
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s creation request submitted by %s" %(route.name, route.applier.username),
107
                              mail_body, settings.SERVER_EMAIL, user_mail,
108
                              get_peer_techc_mails(route.applier))
109
            d = { 'clientip' : "%s"%requesters_address, 'user' : route.applier.username }
110
            logger.info(mail_body, extra=d)
111
            return HttpResponseRedirect(reverse("group-routes"))
112
        else:
113
            return render_to_response('apply.html', {'form': form, 'applier':applier},
114
                                      context_instance=RequestContext(request))
115

    
116
@login_required
117
@never_cache
118
def edit_route(request, route_slug):
119
    applier = request.user.pk
120
    applier_peer = request.user.get_profile().peer
121
    route_edit = get_object_or_404(Route, name=route_slug)
122
    route_edit_applier_peer = route_edit.applier.get_profile().peer
123
    if applier_peer != route_edit_applier_peer:
124
        messages.add_message(request, messages.WARNING,
125
                             "Insufficient rights to edit rule %s" %(route_slug))
126
        return HttpResponseRedirect(reverse("group-routes"))
127
#    if route_edit.status == "ADMININACTIVE" :
128
#        messages.add_message(request, messages.WARNING,
129
#                             "Administrator has disabled editing of rule %s" %(route_slug))
130
#        return HttpResponseRedirect(reverse("group-routes"))
131
#    if route_edit.status == "EXPIRED" :
132
#        messages.add_message(request, messages.WARNING,
133
#                             "Cannot edit the expired rule %s. Contact helpdesk to enable it" %(route_slug))
134
#        return HttpResponseRedirect(reverse("group-routes"))
135
    if route_edit.status == "PENDING" :
136
        messages.add_message(request, messages.WARNING,
137
                             "Cannot edit a pending rule: %s." %(route_slug))
138
        return HttpResponseRedirect(reverse("group-routes"))
139
    route_original = deepcopy(route_edit)
140
    if request.POST:
141
        form = RouteForm(request.POST, instance = route_edit)
142
        if form.is_valid():
143
            route=form.save(commit=False)
144
            route.name = route_original.name
145
            route.applier = request.user
146
            route.status = "PENDING"
147
            route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
148
            route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
149
            route.save()
150
            form.save_m2m()
151
            route.commit_edit()
152
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
153
            mail_body = render_to_string("rule_edit_mail.txt",
154
                                             {"route": route, "address": requesters_address})
155
            user_mail = "%s" %route.applier.email
156
            user_mail = user_mail.split(';')
157
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s edit request submitted by %s" %(route.name, route.applier.username),
158
                              mail_body, settings.SERVER_EMAIL, user_mail,
159
                              get_peer_techc_mails(route.applier))
160
            d = { 'clientip' : requesters_address, 'user' : route.applier.username }
161
            logger.info(mail_body, extra=d)
162
            return HttpResponseRedirect(reverse("group-routes"))
163
        else:
164
            return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
165
                                      context_instance=RequestContext(request))
166
    else:
167
        dictionary = model_to_dict(route_edit, fields=[], exclude=[])
168
        #form = RouteForm(instance=route_edit)
169
        form = RouteForm(dictionary)
170
        if not request.user.is_superuser:
171
            form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
172
        return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
173
                                  context_instance=RequestContext(request))
174

    
175
@login_required
176
@never_cache
177
def delete_route(request, route_slug):
178
    if request.is_ajax():
179
        route = get_object_or_404(Route, name=route_slug)
180
        applier_peer = route.applier.get_profile().peer
181
        requester_peer = request.user.get_profile().peer
182
        if applier_peer == requester_peer:
183
            route.status = "PENDING"
184
            route.expires = datetime.date.today()
185
            route.save()
186
            route.commit_delete()
187
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
188
            mail_body = render_to_string("rule_delete_mail.txt",
189
                                             {"route": route, "address": requesters_address})
190
            user_mail = "%s" %route.applier.email
191
            user_mail = user_mail.split(';')
192
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s removal request submitted by %s" %(route.name, route.applier.username), 
193
                              mail_body, settings.SERVER_EMAIL, user_mail,
194
                             get_peer_techc_mails(route.applier))
195
            d = { 'clientip' : requesters_address, 'user' : route.applier.username }
196
            logger.info(mail_body, extra=d)            
197
        html = "<html><body>Done</body></html>"
198
        return HttpResponse(html)
199
    else:
200
        return HttpResponseRedirect(reverse("group-routes"))
201

    
202
@login_required
203
@never_cache
204
def user_profile(request):
205
    user = request.user
206
    peer = request.user.get_profile().peer
207
    
208
    return render_to_response('profile.html', {'user': user, 'peer':peer},
209
                                  context_instance=RequestContext(request))
210

    
211
@never_cache
212
def user_login(request):
213
    try:
214
        error_username = False
215
        error_orgname = False
216
        error_affiliation = False
217
        error_mail = False
218
        has_affiliation = False
219
        error = ''
220
        username = request.META['HTTP_EPPN']
221
        if not username:
222
            error_username = True
223
        firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
224
        lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
225
        mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
226
        organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
227
        affiliation = request.META['HTTP_SHIB_EP_ENTITLEMENT']
228
        if settings.SHIB_AUTH_AFFILIATION in affiliation.split(";"):
229
            has_affiliation = True
230
        if not has_affiliation:
231
            error_affiliation = True
232
        if not organization:
233
            error_orgname = True
234
        if not mail:
235
            error_mail = True
236
        if error_username:
237
            error = "Your idP should release the HTTP_EPPN attribute towards this service<br>"
238
        if error_orgname:
239
            error = error + "Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service<br>"
240
        if error_affiliation:
241
            error = error + "Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service<br>"
242
        if error_mail:
243
            error = error + "Your idP should release the HTTP_SHIB_INETORGPERSON_MAIL attribute towards this service"
244
        if error_username or error_orgname or error_affiliation or error_mail:
245
            return render_to_response('error.html', {'error': error},
246
                                  context_instance=RequestContext(request))
247
        try:
248
            user = User.objects.get(username__exact=username)
249
            user_exists = True
250
        except:
251
            user_exists = False
252
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, organization=organization, affiliation=affiliation)
253
        if user is not None:
254
            if not user_exists:
255
                user_activation_notify(user)
256
            if user.is_active:
257
               login(request, user)
258
               return HttpResponseRedirect(reverse("group-routes"))
259
            else:
260
                error = "User <strong>%s</strong> is not active yet. Administrators have been notified and will soon activate this account. <br>If your problem persists contact Helpdesk" %user.username
261
                return render_to_response('error.html', {'error': error, 'inactive': True},
262
                                  context_instance=RequestContext(request))
263
        else:
264
            error = "Something went wrong during user authentication. Contact your administrator"
265
            return render_to_response('error.html', {'error': error,},
266
                                  context_instance=RequestContext(request))
267
    except Exception:
268
        error = "Invalid login procedure"
269
        return render_to_response('error.html', {'error': error,},
270
                                  context_instance=RequestContext(request))
271
        # Return an 'invalid login' error message.
272
#    return HttpResponseRedirect(reverse("user-routes"))
273

    
274
def user_activation_notify(user):
275
    current_site = Site.objects.get_current()
276
    subject = render_to_string('registration/activation_email_subject.txt',
277
                                   { 'site': current_site })
278
    # Email subject *must not* contain newlines
279
    subject = ''.join(subject.splitlines())
280
    registration_profile = RegistrationProfile.objects.create_profile(user)
281
    message = render_to_string('registration/activation_email.txt',
282
                                   { 'activation_key': registration_profile.activation_key,
283
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
284
                                     'site': current_site,
285
                                     'user': user })
286
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
287
                              message, settings.SERVER_EMAIL,
288
                             get_peer_techc_mails(user), [])
289
    
290
@login_required
291
@never_cache
292
def add_rate_limit(request):
293
    if request.method == "GET":
294
        form = ThenPlainForm()
295
        return render_to_response('add_rate_limit.html', {'form': form,},
296
                                  context_instance=RequestContext(request))
297

    
298
    else:
299
        form = ThenPlainForm(request.POST)
300
        if form.is_valid():
301
            then=form.save(commit=False)
302
            then.action_value = "%sk"%then.action_value
303
            then.save()
304
            response_data = {}
305
            response_data['pk'] = "%s" %then.pk
306
            response_data['value'] = "%s:%s" %(then.action, then.action_value)
307
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
308
        else:
309
            return render_to_response('add_rate_limit.html', {'form': form,},
310
                                      context_instance=RequestContext(request))
311

    
312
@login_required
313
@never_cache
314
def add_port(request):
315
    if request.method == "GET":
316
        form = PortPlainForm()
317
        return render_to_response('add_port.html', {'form': form,},
318
                                  context_instance=RequestContext(request))
319

    
320
    else:
321
        form = PortPlainForm(request.POST)
322
        if form.is_valid():
323
            port=form.save()
324
            response_data = {}
325
            response_data['value'] = "%s" %port.pk
326
            response_data['text'] = "%s" %port.port
327
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
328
        else:
329
            return render_to_response('add_port.html', {'form': form,},
330
                                      context_instance=RequestContext(request))
331

    
332
@login_required
333
@never_cache
334
def user_logout(request):
335
    logout(request)
336
    return HttpResponseRedirect(reverse('group-routes'))
337
    
338
@never_cache
339
def load_jscript(request, file):
340
    long_polling_timeout = int(settings.POLL_SESSION_UPDATE)*1000 + 10000
341
    return render_to_response('%s.js' % file, {'timeout': long_polling_timeout}, context_instance=RequestContext(request), mimetype="text/javascript")
342

    
343

    
344
def get_peer_techc_mails(user):
345
    mail = []
346
    additional_mail = []
347
    techmails_list = []
348
    user_mail = "%s" %user.email
349
    user_mail = user_mail.split(';')
350
    techmails = user.get_profile().peer.techc()
351
    if techmails:
352
        techmails_list = techmails.split(';')
353
    if settings.NOTIFY_ADMIN_MAILS:
354
        additional_mail = settings.NOTIFY_ADMIN_MAILS
355
#    mail.extend(user_mail)
356
    mail.extend(additional_mail)
357
    mail.extend(techmails_list)
358
    return mail
359

    
360

    
361
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
362
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
363