views.py 23.9 KB
Newer Older
1
# Create your views here.
2 3
import urllib2
import socket
4
import json
5 6
from django import forms
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 12
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
13 14 15 16
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.core.context_processors import request
from django.template.context import RequestContext
17
from django.template.loader import get_template, render_to_string
18
from django.utils.translation import ugettext as _
19 20
from django.core.urlresolvers import reverse
from django.contrib import messages
21
from flowspy.accounts.models import *
22
from ipaddr import *
23

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

26 27
from django.forms.models import model_to_dict

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

32
from registration.models import RegistrationProfile
33

34
from copy import deepcopy
35
from flowspy.utils.decorators import shib_required
36

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

43
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
44 45
#FORMAT = '%(asctime)s %(levelname)s: %(message)s'
#logging.basicConfig(format=FORMAT)
46
formatter = logging.Formatter('%(asctime)s %(levelname)s %(clientip)s %(user)s: %(message)s')
47 48 49 50 51 52 53

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(formatter)
logger.addHandler(handler)

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

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

63
@login_required
64
@never_cache
65
def group_routes(request):
66
    group_routes = []
67 68 69 70
    try:
        peer = request.user.get_profile().peer
    except UserProfile.DoesNotExist:
        error = "User <strong>%s</strong> does not belong to any peer or organization. It is not possible to create new firewall rules.<br>Please contact Helpdesk to resolve this issue" % request.user.username
71
        return render_to_response('error.html', {'error': error}, context_instance=RequestContext(request))
72 73 74 75
    if peer:
       peer_members = UserProfile.objects.filter(peer=peer)
       users = [prof.user for prof in peer_members]
       group_routes = Route.objects.filter(applier__in=users)
76 77
       if request.user.is_superuser:
           group_routes = Route.objects.all()
78
       return render_to_response('user_routes.html', {'routes': group_routes},
79 80 81
                              context_instance=RequestContext(request))


82
@login_required
83
@never_cache
84
def add_route(request):
85
    applier = request.user.pk
86 87 88
    applier_peer_networks = request.user.get_profile().peer.networks.all()
    if not applier_peer_networks:
         messages.add_message(request, messages.WARNING,
89
                             _("Insufficient rights on administrative networks. Cannot add rule. Contact your administrator"))
90
         return HttpResponseRedirect(reverse("group-routes"))
91
    if request.method == "GET":
92
        form = RouteForm(initial={'applier': applier})
93 94
        if not request.user.is_superuser:
            form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
95
            form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
96
        return render_to_response('apply.html', {'form': form, 'applier': applier},
97 98 99
                                  context_instance=RequestContext(request))

    else:
100 101 102 103
        request_data = request.POST.copy()
        if request.user.is_superuser:
            request_data['issuperuser'] = request.user.username
        else:
104
            request_data['applier'] = applier
105 106 107 108 109
            try:
                del requset_data['issuperuser']
            except:
                pass
        form = RouteForm(request_data)
110 111
        if form.is_valid():
            route=form.save(commit=False)
112 113
            if not request.user.is_superuser:
                route.applier = request.user
114
            route.status = "PENDING"
115
            route.response = "Applying"
116 117
            route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
            route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
118 119 120
            route.save()
            form.save_m2m()
            route.commit_add()
121
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
122 123 124 125
            fqdn = Site.objects.get_current().domain
            admin_url = "https://%s%s" % (fqdn, "/fod/edit/%s"%route.name)
            mail_body = render_to_string("rule_action.txt",
                                             {"route": route, "address": requesters_address, "action": "creation", "url": admin_url})
126 127 128 129 130
            user_mail = "%s" %route.applier.email
            user_mail = user_mail.split(';')
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s creation request submitted by %s" %(route.name, route.applier.username),
                              mail_body, settings.SERVER_EMAIL, user_mail,
                              get_peer_techc_mails(route.applier))
131 132
            d = { 'clientip' : "%s"%requesters_address, 'user' : route.applier.username }
            logger.info(mail_body, extra=d)
133
            return HttpResponseRedirect(reverse("group-routes"))
134
        else:
135 136 137
            if not request.user.is_superuser:
                form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
                form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
138
            return render_to_response('apply.html', {'form': form, 'applier':applier},
139
                                      context_instance=RequestContext(request))
140

141
@login_required
142
@never_cache
143
def edit_route(request, route_slug):
144
    applier = request.user.pk
145
    applier_peer = request.user.get_profile().peer
146
    route_edit = get_object_or_404(Route, name=route_slug)
147
    route_edit_applier_peer = route_edit.applier.get_profile().peer
148
    if applier_peer != route_edit_applier_peer and (not request.user.is_superuser):
149
        messages.add_message(request, messages.WARNING,
150
                             _("Insufficient rights to edit rule %s") %(route_slug))
151
        return HttpResponseRedirect(reverse("group-routes"))
152 153 154 155 156 157 158 159
#    if route_edit.status == "ADMININACTIVE" :
#        messages.add_message(request, messages.WARNING,
#                             "Administrator has disabled editing of rule %s" %(route_slug))
#        return HttpResponseRedirect(reverse("group-routes"))
#    if route_edit.status == "EXPIRED" :
#        messages.add_message(request, messages.WARNING,
#                             "Cannot edit the expired rule %s. Contact helpdesk to enable it" %(route_slug))
#        return HttpResponseRedirect(reverse("group-routes"))
160 161
    if route_edit.status == "PENDING" :
        messages.add_message(request, messages.WARNING,
162
                             _("Cannot edit a pending rule: %s.") %(route_slug))
163
        return HttpResponseRedirect(reverse("group-routes"))
164 165
    route_original = deepcopy(route_edit)
    if request.POST:
166 167 168 169
        request_data = request.POST.copy()
        if request.user.is_superuser:
            request_data['issuperuser'] = request.user.username
        else:
170
            request_data['applier'] = applier
171 172 173 174 175
            try:
                del request_data['issuperuser']
            except:
                pass
        form = RouteForm(request_data, instance = route_edit)
176
        critical_changed_values = ['source', 'destination', 'sourceport', 'destinationport', 'port', 'protocol', 'then']
177
        if form.is_valid():
178
            changed_data = form.changed_data
179 180
            route=form.save(commit=False)
            route.name = route_original.name
181 182
            route.status = route_original.status
            route.response = route_original.response
183 184
            if not request.user.is_superuser:
                route.applier = request.user
185 186
            if bool(set(changed_data) & set(critical_changed_values)) or (not route_original.status == 'ACTIVE'):
                route.status = "PENDING"
187
                route.response = "Applying"
188 189
                route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
                route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
190
            route.save()
191 192 193 194
            if bool(set(changed_data) & set(critical_changed_values)) or (not route_original.status == 'ACTIVE'):
                form.save_m2m()
                route.commit_edit()
                requesters_address = request.META['HTTP_X_FORWARDED_FOR']
195 196 197 198
                fqdn = Site.objects.get_current().domain
                admin_url = "https://%s%s" % (fqdn, "/fod/edit/%s"%route.name)
                mail_body = render_to_string("rule_action.txt",
                                             {"route": route, "address": requesters_address, "action": "edit", "url": admin_url})
199 200 201
                user_mail = "%s" %route.applier.email
                user_mail = user_mail.split(';')
                send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s edit request submitted by %s" %(route.name, route.applier.username),
202 203
                              mail_body, settings.SERVER_EMAIL, user_mail,
                              get_peer_techc_mails(route.applier))
204 205
                d = { 'clientip' : requesters_address, 'user' : route.applier.username }
                logger.info(mail_body, extra=d)
206
            return HttpResponseRedirect(reverse("group-routes"))
207
        else:
208 209 210
            if not request.user.is_superuser:
                form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
                form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
211
            return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
212 213
                                      context_instance=RequestContext(request))
    else:
214 215
        if (not route_original.status == 'ACTIVE'):
            route_edit.expires = datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
216
        dictionary = model_to_dict(route_edit, fields=[], exclude=[])
217 218 219 220 221 222 223
        if request.user.is_superuser:
            dictionary['issuperuser'] = request.user.username
        else:
            try:
                del dictionary['issuperuser']
            except:
                pass
224
        form = RouteForm(dictionary)
225 226
        if not request.user.is_superuser:
            form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
227
            form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
228
        return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
229 230 231
                                  context_instance=RequestContext(request))

@login_required
232
@never_cache
233 234 235
def delete_route(request, route_slug):
    if request.is_ajax():
        route = get_object_or_404(Route, name=route_slug)
236 237
        applier_peer = route.applier.get_profile().peer
        requester_peer = request.user.get_profile().peer
238
        if applier_peer == requester_peer or request.user.is_superuser:
239
            route.status = "PENDING"
240
            route.expires = datetime.date.today()
241 242
            if not request.user.is_superuser:
                route.applier = request.user
243
            route.response = "Suspending"
244
            route.save()
245
            route.commit_delete()
246
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
247 248 249 250
            fqdn = Site.objects.get_current().domain
            admin_url = "https://%s%s" % (fqdn, "/fod/edit/%s"%route.name)
            mail_body = render_to_string("rule_action.txt",
                                             {"route": route, "address": requesters_address, "action": "removal", "url": admin_url})
251 252 253 254 255
            user_mail = "%s" %route.applier.email
            user_mail = user_mail.split(';')
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s removal request submitted by %s" %(route.name, route.applier.username), 
                              mail_body, settings.SERVER_EMAIL, user_mail,
                             get_peer_techc_mails(route.applier))
256
            d = { 'clientip' : requesters_address, 'user' : route.applier.username }
257
            logger.info(mail_body, extra=d)
258 259 260 261 262 263
        html = "<html><body>Done</body></html>"
        return HttpResponse(html)
    else:
        return HttpResponseRedirect(reverse("group-routes"))

@login_required
264
@never_cache
265 266
def user_profile(request):
    user = request.user
267 268
    try:
        peer = request.user.get_profile().peer
269 270 271
        peers = Peer.objects.filter(pk=peer.pk)
        if user.is_superuser:
            peers = Peer.objects.all()
272 273
    except UserProfile.DoesNotExist:
        error = "User <strong>%s</strong> does not belong to any peer or organization. It is not possible to create new firewall rules.<br>Please contact Helpdesk to resolve this issue" % user.username
274
        return render_to_response('error.html', {'error': error}, context_instance=RequestContext(request))
275
    return render_to_response('profile.html', {'user': user, 'peers':peers},
276 277
                                  context_instance=RequestContext(request))

278
@never_cache
279 280
def user_login(request):
    try:
281 282
        error_username = False
        error_orgname = False
283
        error_entitlement = False
284
        error_mail = False
285
        has_entitlement = False
286
        error = ''
287 288 289
        username = request.META['HTTP_EPPN']
        if not username:
            error_username = True
290 291 292 293
        firstname = lookupShibAttr(settings.SHIB_FIRSTNAME, request.META)
        lastname = lookupShibAttr(settings.SHIB_LASTNAME, request.META)
        mail = lookupShibAttr(settings.SHIB_MAIL, request.META)
        entitlement = lookupShibAttr(settings.SHIB_ENTITLEMENT, request.META)
294
        #organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
295
        
296 297 298 299
        if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
            has_entitlement = True
        if not has_entitlement:
            error_entitlement = True
300 301
#        if not organization:
#            error_orgname = True
302 303
        if not mail:
            error_mail = True
304
        if error_username:
305
            error = _("Your idP should release the HTTP_EPPN attribute towards this service<br>")
306 307
#        if error_orgname:
#            error = error + _("Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service<br>")
308
        if error_entitlement:
309
            error = error + _("Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service<br>")
310
        if error_mail:
311
            error = error + _("Your idP should release the HTTP_SHIB_INETORGPERSON_MAIL attribute towards this service")
312
        if error_username or error_orgname or error_entitlement or error_mail:
313
            return render_to_response('error.html', {'error': error, "missing_attributes": True},
314
                                  context_instance=RequestContext(request))
315 316
        try:
            user = User.objects.get(username__exact=username)
317 318 319 320
            user.email = mail
            user.first_name = firstname
            user.last_name = lastname
            user.save()
321 322 323
            user_exists = True
        except:
            user_exists = False
324
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
325
        
326
        if user is not None:
327
            try:
328 329 330
                peer = user.get_profile().peer
#                peer = Peer.objects.get(domain_name=organization)
#                up = UserProfile.objects.get_or_create(user=user,peer=peer)
331
            except:
332 333 334 335
                form = UserProfileForm()
                form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
                form.fields['peer'] = forms.ModelChoiceField(queryset=Peer.objects.all(), empty_label=None)
                return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
336 337 338 339 340 341
            if not user_exists:
                user_activation_notify(user)
            if user.is_active:
               login(request, user)
               return HttpResponseRedirect(reverse("group-routes"))
            else:
342
                error = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %user.username
343 344
                return render_to_response('error.html', {'error': error, 'inactive': True},
                                  context_instance=RequestContext(request))
345
        else:
346
            error = _("Something went wrong during user authentication. Contact your administrator")
347 348
            return render_to_response('error.html', {'error': error,},
                                  context_instance=RequestContext(request))
349
    except User.DoesNotExist as e:
350
        error = _("Invalid login procedure. Error: %s" %e)
351 352
        return render_to_response('error.html', {'error': error,},
                                  context_instance=RequestContext(request))
353 354 355
        # Return an 'invalid login' error message.
#    return HttpResponseRedirect(reverse("user-routes"))

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
def user_activation_notify(user):
    current_site = Site.objects.get_current()
    subject = render_to_string('registration/activation_email_subject.txt',
                                   { 'site': current_site })
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    registration_profile = RegistrationProfile.objects.create_profile(user)
    message = render_to_string('registration/activation_email.txt',
                                   { 'activation_key': registration_profile.activation_key,
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                     'site': current_site,
                                     'user': user })
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
                              message, settings.SERVER_EMAIL,
                             get_peer_techc_mails(user), [])
371

372
@login_required
373
@never_cache
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
def add_rate_limit(request):
    if request.method == "GET":
        form = ThenPlainForm()
        return render_to_response('add_rate_limit.html', {'form': form,},
                                  context_instance=RequestContext(request))

    else:
        form = ThenPlainForm(request.POST)
        if form.is_valid():
            then=form.save(commit=False)
            then.action_value = "%sk"%then.action_value
            then.save()
            response_data = {}
            response_data['pk'] = "%s" %then.pk
            response_data['value'] = "%s:%s" %(then.action, then.action_value)
389
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
390 391 392 393 394
        else:
            return render_to_response('add_rate_limit.html', {'form': form,},
                                      context_instance=RequestContext(request))

@login_required
395
@never_cache
396 397 398 399 400 401 402 403 404 405 406 407 408
def add_port(request):
    if request.method == "GET":
        form = PortPlainForm()
        return render_to_response('add_port.html', {'form': form,},
                                  context_instance=RequestContext(request))

    else:
        form = PortPlainForm(request.POST)
        if form.is_valid():
            port=form.save()
            response_data = {}
            response_data['value'] = "%s" %port.pk
            response_data['text'] = "%s" %port.port
409
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
410 411 412 413
        else:
            return render_to_response('add_port.html', {'form': form,},
                                      context_instance=RequestContext(request))

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
@never_cache
def selectinst(request):
    if request.method == 'POST':
        request_data = request.POST.copy()
        user = request_data['user']
        try:
            existingProfile = UserProfile.objects.get(user=user)
            error = _("Violation warning: User account is already associated with an institution.The event has been logged and our administrators will be notified about it")
            return render_to_response('error.html', {'error': error, 'inactive': True},
                                  context_instance=RequestContext(request))
        except UserProfile.DoesNotExist:
            pass
            
        form = UserProfileForm(request_data)
        if form.is_valid():
            userprofile = form.save()
            user_activation_notify(userprofile.user)
            error = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %userprofile.user.username
            return render_to_response('error.html', {'error': error, 'inactive': True},
                                  context_instance=RequestContext(request))
        else:
            form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
            form.fields['institution'] = forms.ModelChoiceField(queryset=Peer.objects.all(), empty_label=None)
            return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))

439
@login_required
440
@never_cache
441
def user_logout(request):
442 443
    logout(request)
    return HttpResponseRedirect(reverse('group-routes'))
444
    
445
@never_cache
446
def load_jscript(request, file):
447 448
    long_polling_timeout = int(settings.POLL_SESSION_UPDATE)*1000 + 10000
    return render_to_response('%s.js' % file, {'timeout': long_polling_timeout}, context_instance=RequestContext(request), mimetype="text/javascript")
449 450 451


def get_peer_techc_mails(user):
452 453 454 455 456
    mail = []
    additional_mail = []
    techmails_list = []
    user_mail = "%s" %user.email
    user_mail = user_mail.split(';')
457
    techmails = user.get_profile().peer.techc_emails.all()
458
    if techmails:
459 460
        for techmail in techmails:
            techmails_list.append(techmail.email)
461 462
    if settings.NOTIFY_ADMIN_MAILS:
        additional_mail = settings.NOTIFY_ADMIN_MAILS
463
#    mail.extend(user_mail)
464 465
    mail.extend(additional_mail)
    mail.extend(techmails_list)
466
    return mail
467 468 469 470

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

471 472 473

def lookupShibAttr(attrmap, requestMeta):
    for attr in attrmap:
474
        if (attr in requestMeta) & (len(requestMeta[attr]) > 0):
475 476
            return requestMeta[attr]
    return ''