Statistics
| Branch: | Tag: | Revision:

root / flowspec / views.py @ c1509909

History | View | Annotate | Download (9.1 kB)

1
# Create your views here.
2
import urllib2
3
import re
4
import socket
5
import json
6
from django import forms
7
from django.views.decorators.csrf import csrf_exempt
8
from django.core import urlresolvers
9
from django.core import serializers
10
from django.contrib.auth.decorators import login_required
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
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
def days_offset(): return datetime.now() + timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
32

    
33
@login_required
34
def user_routes(request):
35
    user_routes = Route.objects.filter(applier=request.user)
36
    return render_to_response('user_routes.html', {'routes': user_routes},
37
                              context_instance=RequestContext(request))
38

    
39
@login_required
40
def group_routes(request):
41
    group_routes = []
42
    peer = request.user.get_profile().peer
43
    if peer:
44
       peer_members = UserProfile.objects.filter(peer=peer)
45
       users = [prof.user for prof in peer_members]
46
       group_routes = Route.objects.filter(applier__in=users)
47
    return render_to_response('user_routes.html', {'routes': group_routes},
48
                              context_instance=RequestContext(request))
49

    
50

    
51
@login_required
52
def add_route(request):
53
    applier = request.user.pk
54
    if request.method == "GET":
55
        form = RouteForm()
56
        return render_to_response('apply.html', {'form': form, 'applier': applier},
57
                                  context_instance=RequestContext(request))
58

    
59
    else:
60
        form = RouteForm(request.POST)
61
        if form.is_valid():
62
            route=form.save(commit=False)
63
            route.applier = request.user
64
            route.expires = days_offset()
65
            route.status = "PENDING"
66
            route.save()
67
            form.save_m2m()
68
            route.commit_add()
69
            return HttpResponseRedirect(reverse("group-routes"))
70
        else:
71
            return render_to_response('apply.html', {'form': form, 'applier':applier},
72
                                      context_instance=RequestContext(request))
73

    
74
@login_required
75
def add_then(request):
76
    applier = request.user.pk
77
    if request.method == "GET":
78
        form = RouteForm()
79
        return render_to_response('apply.html', {'form': form, 'applier': applier},
80
                                  context_instance=RequestContext(request))
81

    
82
    else:
83
        form = RouteForm(request.POST)
84
        if form.is_valid():
85
            route=form.save(commit=False)
86
            route.applier = request.user
87
            route.expires = days_offset()
88
            route.save()
89
            form.save_m2m()
90
            route.commit_add()
91
            return HttpResponseRedirect(reverse("group-routes"))
92
        else:
93
            return render_to_response('apply.html', {'form': form, 'applier':applier},
94
                                      context_instance=RequestContext(request))
95

    
96
@login_required
97
def edit_route(request, route_slug):
98
    applier = request.user.pk
99
    applier_peer = request.user.get_profile().peer
100
    route_edit = get_object_or_404(Route, name=route_slug)
101
    route_edit_applier_peer = route_edit.applier.get_profile().peer
102
    if applier_peer != route_edit_applier_peer:
103
        messages.add_message(request, messages.WARNING,
104
                             "Insufficient rights to edit route %s" %(route_slug))
105
        return HttpResponseRedirect(reverse("group-routes"))
106
    route_original = deepcopy(route_edit)
107
    if request.POST:
108
        form = RouteForm(request.POST, instance = route_edit)
109
        if form.is_valid():
110
            route=form.save(commit=False)
111
            route.name = route_original.name
112
            route.applier = request.user
113
            route.expires = route_original.expires
114
            route.status = "PENDING"
115
            route.save()
116
            form.save_m2m()
117
            route.commit_edit()
118
            return HttpResponseRedirect(reverse("group-routes"))
119
        else:
120
            return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
121
                                      context_instance=RequestContext(request))
122
    else:
123
        dictionary = model_to_dict(route_edit, fields=[], exclude=[])
124
        #form = RouteForm(instance=route_edit)
125
        form = RouteForm(dictionary)
126
        return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
127
                                  context_instance=RequestContext(request))
128

    
129
@login_required
130
def delete_route(request, route_slug):
131
    if request.is_ajax():
132
        route = get_object_or_404(Route, name=route_slug)
133
        applier_peer = route.applier.get_profile().peer
134
        requester_peer = request.user.get_profile().peer
135
        if applier_peer == requester_peer:
136
            route.deactivate()
137
            route.commit_delete()
138
        html = "<html><body>Done</body></html>"
139
        return HttpResponse(html)
140
    else:
141
        return HttpResponseRedirect(reverse("group-routes"))
142

    
143
@login_required
144
def user_profile(request):
145
    user = request.user
146
    peer = request.user.get_profile().peer
147
    
148
    return render_to_response('profile.html', {'user': user, 'peer':peer},
149
                                  context_instance=RequestContext(request))
150

    
151

    
152
def user_login(request):
153
    try:
154
        error_username = None
155
        error_orgname = None
156
        username = request.META['HTTP_EPPN']
157
        if not username:
158
            error_username = True
159
        firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
160
        lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
161
        mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
162
        organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
163
        if not organization:
164
            error_orgname = True
165

    
166
        if error_orgname or error_username:
167
            error = "Your idP should release the HTTP_EPPN, HTTP_SHIB_HOMEORGANIZATION attributes towards this service" 
168
            return render_to_response('error.html', {'error': error,},
169
                                  context_instance=RequestContext(request))
170
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, organization=organization, affiliation=None)
171
        if user is not None:
172
            login(request, user)
173
            return HttpResponseRedirect(reverse("group-routes"))
174
                # Redirect to a success page.
175
                # Return a 'disabled account' error message
176
        else:
177
            html = "<html><body>Invalid User</body></html>"
178
            return HttpResponse(html)
179
    except Exception as e:
180
        html = "<html><body>Invalid Login Procedure %s </body></html>" %e
181
        return HttpResponse(html)
182
        # Return an 'invalid login' error message.
183
#    return HttpResponseRedirect(reverse("user-routes"))
184

    
185
@login_required
186
def add_rate_limit(request):
187
    if request.method == "GET":
188
        form = ThenPlainForm()
189
        return render_to_response('add_rate_limit.html', {'form': form,},
190
                                  context_instance=RequestContext(request))
191

    
192
    else:
193
        form = ThenPlainForm(request.POST)
194
        if form.is_valid():
195
            then=form.save(commit=False)
196
            then.action_value = "%sk"%then.action_value
197
            then.save()
198
            response_data = {}
199
            response_data['pk'] = "%s" %then.pk
200
            response_data['value'] = "%s:%s" %(then.action, then.action_value)
201
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
202
        else:
203
            return render_to_response('add_rate_limit.html', {'form': form,},
204
                                      context_instance=RequestContext(request))
205

    
206
@login_required
207
def add_port(request):
208
    if request.method == "GET":
209
        form = PortPlainForm()
210
        return render_to_response('add_port.html', {'form': form,},
211
                                  context_instance=RequestContext(request))
212

    
213
    else:
214
        form = PortPlainForm(request.POST)
215
        if form.is_valid():
216
            port=form.save()
217
            response_data = {}
218
            response_data['value'] = "%s" %port.pk
219
            response_data['text'] = "%s" %port.port
220
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
221
        else:
222
            return render_to_response('add_port.html', {'form': form,},
223
                                      context_instance=RequestContext(request))
224

    
225
@login_required
226
def user_logout(request):
227
    return HttpResponseRedirect(settings.SHIB_LOGOUT_URL)
228
    
229
    
230
def load_jscript(request, file):
231
    return render_to_response('%s.js' % file, context_instance=RequestContext(request), mimetype="text/javascript")