Statistics
| Branch: | Tag: | Revision:

root / edumanage / views.py @ cca6833d

History | View | Annotate | Download (76.7 kB)

1
# -*- coding: utf-8 -*- vim:encoding=utf-8:
2
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
3

    
4
from django.shortcuts import render_to_response,get_object_or_404,redirect
5
from django.http import HttpResponse,HttpResponseRedirect,Http404
6
from django.template import RequestContext
7
from django.core.urlresolvers import reverse
8
from django.contrib.auth.decorators import login_required
9
from django.contrib.auth import logout
10
from edumanage.models import *
11
from accounts.models import *
12
from edumanage.forms import *
13
from django import forms
14
from django.forms.models import modelformset_factory
15
from django.forms.models import inlineformset_factory
16
from django.contrib.contenttypes.generic import generic_inlineformset_factory
17
from django.core.mail.message import EmailMessage
18
from django.contrib.sites.models import Site
19
from django.template.loader import render_to_string
20
import json, bz2
21
import math, datetime
22
from xml.etree import ElementTree as ET
23

    
24
from django.conf import settings
25
from django.contrib import messages
26

    
27
from django.db.models import Max
28

    
29
from django.views.decorators.cache import never_cache
30
from django.utils.translation import ugettext as _
31
from django.contrib.auth import authenticate, login
32
from registration.models import RegistrationProfile
33
from django.core.cache import cache
34

    
35
from edumanage.decorators import social_active_required
36
from utils.cat_helper import *
37

    
38
@never_cache
39
def index(request):
40
    return render_to_response('front/index.html', context_instance=RequestContext(request))
41

    
42
@never_cache
43
def manage_login_front(request):
44
    user = request.user
45
    try:
46
        profile = user.get_profile()
47
    except UserProfile.DoesNotExist:
48
        return render_to_response('edumanage/welcome_manage.html',
49
                              context_instance=RequestContext(request, base_response(request)))
50
    except AttributeError:
51
        return render_to_response('edumanage/welcome_manage.html',
52
                              context_instance=RequestContext(request, base_response(request)))
53
    if user.is_authenticated() and user.is_active and profile.is_social_active:
54
        return redirect(reverse('manage'))
55
    else:
56
        return render_to_response('edumanage/welcome_manage.html',
57
                              context_instance=RequestContext(request, base_response(request)))
58

    
59
@login_required
60
@social_active_required
61
@never_cache
62
def manage(request):
63
    services_list = []
64
    servers_list = []
65
    user = request.user
66
    try:
67
        profile = user.get_profile()
68
        inst = profile.institution
69
    except UserProfile.DoesNotExist:
70
        return render_to_response('edumanage/welcome.html',
71
                              context_instance=RequestContext(request, base_response(request)))
72
        
73
    services = ServiceLoc.objects.filter(institutionid=inst)
74
    services_list.extend([s for s in services])
75
    servers = InstServer.objects.filter(instid=inst)
76
    servers_list.extend([s for s in servers])
77
    return render_to_response('edumanage/welcome.html', 
78
                              {
79
                               'institution': inst, 
80
                               'services': services_list,
81
                               'servers': servers_list,                               
82
                               },  
83
                              context_instance=RequestContext(request, base_response(request)))
84

    
85
@login_required
86
@social_active_required
87
@never_cache
88
def institutions(request):
89
    user = request.user
90
    dict = {}
91
    try:
92
        profile = user.get_profile()
93
        inst = profile.institution
94
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
95
    except UserProfile.DoesNotExist:
96
        return HttpResponseRedirect(reverse("manage"))
97
    dict['institution'] = inst.pk
98
    form = InstDetailsForm(initial=dict)
99
    form.fields['institution'].widget.attrs['readonly'] = True
100
    return render_to_response('edumanage/institution.html', 
101
                              {
102
                               'institution': inst,
103
                               'form': form, 
104
                               },  
105
                              context_instance=RequestContext(request, base_response(request)))
106

    
107

    
108

    
109
@login_required
110
@social_active_required
111
@never_cache
112
def add_institution_details(request, institution_pk):
113
    user = request.user
114
    try:
115
        profile = user.get_profile()
116
        inst = profile.institution
117
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
118
    except UserProfile.DoesNotExist:
119
        return HttpResponseRedirect(reverse("manage"))
120
    
121
    if institution_pk and int(inst.pk) != int(institution_pk):
122
        messages.add_message(request, messages.ERROR, 'You have no rights on this Institution')
123
        return HttpResponseRedirect(reverse("institutions"))
124
    
125
    if request.method == "GET":
126
        try:         
127
            inst_details = InstitutionDetails.objects.get(institution=inst)
128
            form = InstDetailsForm(instance=inst_details)
129
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
130
            urls_form = UrlFormSet(prefix='urlsform', instance = inst_details) 
131
        except InstitutionDetails.DoesNotExist:
132
            form = InstDetailsForm()
133
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
134
            UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
135
            urls_form = UrlFormSet(prefix='urlsform')
136

    
137
        
138
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
139
        return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form':urls_form},
140
                                  context_instance=RequestContext(request, base_response(request)))
141
    elif request.method == 'POST':
142
        request_data = request.POST.copy()
143
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
144
        try:         
145
            inst_details = InstitutionDetails.objects.get(institution=inst)
146
            form = InstDetailsForm(request_data, instance=inst_details)
147
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
148
        except InstitutionDetails.DoesNotExist:
149
            form = InstDetailsForm(request_data)
150
            urls_form = UrlFormSet(request_data, prefix='urlsform')
151
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
152
        if form.is_valid() and urls_form.is_valid():
153
            instdets = form.save()
154
            urls_form.instance = instdets
155
            urls_inst = urls_form.save()
156
            return HttpResponseRedirect(reverse("institutions"))
157
        else:
158
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
159
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
160
            return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form, 'urls_form': urls_form},
161
                                  context_instance=RequestContext(request, base_response(request)))
162

    
163

    
164
@login_required
165
@social_active_required
166
@never_cache
167
def services(request, service_pk):
168
    user = request.user
169
    dict = {}
170
    try:
171
        profile = user.get_profile()
172
        inst = profile.institution
173
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
174
    except UserProfile.DoesNotExist:
175
        return HttpResponseRedirect(reverse("manage"))
176
    try:
177
        instdetails = inst.institutiondetails
178
    except InstitutionDetails.DoesNotExist:
179
        return HttpResponseRedirect(reverse("manage"))
180
    if inst.ertype not in [2,3]:
181
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Location. Your institution should be either SP or IdP/SP')
182
        return render_to_response('edumanage/services.html', { 'institution': inst },
183
                              context_instance=RequestContext(request, base_response(request)))
184
    try:
185
        services = ServiceLoc.objects.filter(institutionid = inst)
186
    except ServiceLoc.DoesNotExist:
187
        services = False 
188
    
189
    if service_pk:
190
        try:
191
            services = services.get(pk=service_pk)
192
        except:
193
            messages.add_message(request, messages.ERROR, 'You have no rights to view this location')
194
            return HttpResponseRedirect(reverse("services"))
195
        return render_to_response('edumanage/service_details.html', 
196
                              {
197
                               'institution': inst,
198
                               'service': services,
199
                               },  
200
                              context_instance=RequestContext(request, base_response(request)))
201
    
202
    return render_to_response('edumanage/services.html', 
203
                              {
204
                               'institution': inst,
205
                               'services': services, 
206
                               },  
207
                              context_instance=RequestContext(request, base_response(request)))
208

    
209

    
210

    
211
@login_required
212
@social_active_required
213
@never_cache
214
def add_services(request, service_pk):
215
    user = request.user
216
    service = False
217
    edit = False
218
    try:
219
        profile = user.get_profile()
220
        inst = profile.institution
221
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
222
    except UserProfile.DoesNotExist:
223
        return HttpResponseRedirect(reverse("manage"))
224
    try:
225
        instdetails = inst.institutiondetails
226
    except InstitutionDetails.DoesNotExist:
227
        return HttpResponseRedirect(reverse("manage"))
228
    if inst.ertype not in [2,3]:
229
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Service. Your institution should be either SP or IdP/SP')
230
        return render_to_response('edumanage/services_edit.html', { 'edit': edit },
231
                                  context_instance=RequestContext(request, base_response(request)))
232
    if request.method == "GET":
233

    
234
        # Determine add or edit
235
        try:         
236
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
237
            form = ServiceLocForm(instance=service)
238
        except ServiceLoc.DoesNotExist:
239
            form = ServiceLocForm()
240
            if service_pk:
241
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this location')
242
                return HttpResponseRedirect(reverse("services"))
243
        form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
244
        UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
245
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=2, can_delete=True)
246
        urls_form = UrlFormSet(prefix='urlsform')
247
        names_form = NameFormSet(prefix='namesform')
248
        if (service):
249
            NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
250
            names_form = NameFormSet(instance=service, prefix='namesform')
251
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
252
            urls_form = UrlFormSet(instance=service, prefix='urlsform')
253
        form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
254
        if service:
255
            edit = True
256
        for url_form in urls_form.forms:
257
            url_form.fields['urltype'] = forms.ChoiceField(choices=(('', '----------'),('info', 'Info'),))
258
        return render_to_response('edumanage/services_edit.html', { 'form': form, 'services_form':names_form, 'urls_form': urls_form, "edit": edit},
259
                                  context_instance=RequestContext(request, base_response(request)))
260
    elif request.method == 'POST':
261
        request_data = request.POST.copy()
262
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
263
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
264
        try:         
265
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
266
            form = ServiceLocForm(request_data, instance=service)
267
            names_form = NameFormSet(request_data, instance=service, prefix='namesform')
268
            urls_form = UrlFormSet(request_data, instance=service, prefix='urlsform')
269
        except ServiceLoc.DoesNotExist:
270
            form = ServiceLocForm(request_data)
271
            names_form = NameFormSet(request_data, prefix='namesform')
272
            urls_form = UrlFormSet(request_data, prefix='urlsform')
273
            if service_pk:
274
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this location')
275
                return HttpResponseRedirect(reverse("services"))
276
        
277
        if form.is_valid() and names_form.is_valid() and urls_form.is_valid():
278
            serviceloc = form.save()
279
            service = serviceloc
280
            names_form.instance = service
281
            urls_form.instance = service
282
            names_inst = names_form.save()
283
            urls_inst = urls_form.save()
284
            return HttpResponseRedirect(reverse("services"))
285
        else:
286
            form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
287
            form.fields['contact'] = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(pk__in=getInstContacts(inst)))
288
        if service:
289
            edit = True
290
        for url_form in urls_form.forms:
291
            url_form.fields['urltype'] = forms.ChoiceField(choices=(('', '----------'),('info', 'Info'),))
292
        return render_to_response('edumanage/services_edit.html', { 'institution': inst, 'form': form, 'services_form':names_form, 'urls_form': urls_form, "edit": edit},
293
                                  context_instance=RequestContext(request, base_response(request)))
294

    
295

    
296
@login_required
297
@social_active_required
298
@never_cache
299
def del_service(request):
300
    if request.method == 'GET':
301
        user = request.user
302
        req_data = request.GET.copy()
303
        service_pk = req_data['service_pk']
304
        try:
305
            profile = user.get_profile()
306
            institution = profile.institution
307
        except UserProfile.DoesNotExist:
308
            resp['error'] = "Could not delete service. Not enough rights"
309
            return HttpResponse(json.dumps(resp), mimetype='application/json')
310
        resp = {}
311
        try:
312
            service = ServiceLoc.objects.get(institutionid=institution, pk=service_pk)
313
        except ServiceLoc.DoesNotExist:
314
            resp['error'] = "Could not get service or you have no rights to delete"
315
            return HttpResponse(json.dumps(resp), mimetype='application/json')
316
        try:
317
            service.delete()
318
        except:
319
            resp['error'] = "Could not delete service"
320
            return HttpResponse(json.dumps(resp), mimetype='application/json')
321
        resp['success'] = "Service successfully deleted"
322
        return HttpResponse(json.dumps(resp), mimetype='application/json')
323

    
324

    
325
@login_required
326
@social_active_required
327
@never_cache
328
def servers(request, server_pk):
329
    user = request.user
330
    servers = False
331
    try:
332
        profile = user.get_profile()
333
        inst = profile.institution
334
    except UserProfile.DoesNotExist:
335
        inst = False
336
        return HttpResponseRedirect(reverse("manage"))
337
    if inst:
338
        servers = InstServer.objects.filter(instid=inst)
339
    if server_pk:
340
        servers = servers.get(pk=server_pk)
341
        return render_to_response('edumanage/server_details.html', 
342
                              {
343
                               'institution': inst,
344
                               'server': servers,
345
                               },  
346
                              context_instance=RequestContext(request, base_response(request)))
347
    return render_to_response('edumanage/servers.html', { 'servers': servers},
348
                                  context_instance=RequestContext(request, base_response(request)))
349

    
350

    
351
@login_required
352
@social_active_required
353
@never_cache
354
def add_server(request, server_pk):
355
    user = request.user
356
    server = False
357
    edit = False
358
    try:
359
        profile = user.get_profile()
360
        inst = profile.institution
361
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
362
    except UserProfile.DoesNotExist:
363
        return HttpResponseRedirect(reverse("manage"))
364
    try:
365
        instdetails = inst.institutiondetails
366
    except InstitutionDetails.DoesNotExist:
367
        return HttpResponseRedirect(reverse("manage"))
368
    if request.method == "GET":
369
        # Determine add or edit
370
        try:         
371
            server = InstServer.objects.get(instid=inst, pk=server_pk)
372
            form = InstServerForm(instance=server)
373
        except InstServer.DoesNotExist:
374
            form = InstServerForm()
375
            if server_pk:
376
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this server')
377
                return HttpResponseRedirect(reverse("servers"))  
378
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
379
        if server:
380
            edit = True
381
                      
382
        return render_to_response('edumanage/servers_edit.html', { 'form': form, 'edit': edit },
383
                                  context_instance=RequestContext(request, base_response(request)))
384
    elif request.method == 'POST':
385
        request_data = request.POST.copy()
386
        try:         
387
            server = InstServer.objects.get(instid=inst, pk=server_pk)
388
            form = InstServerForm(request_data, instance=server)
389
        except InstServer.DoesNotExist:
390
            form = InstServerForm(request_data)
391
            if server_pk:
392
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this server')
393
                return HttpResponseRedirect(reverse("servers")) 
394
        
395
        if form.is_valid():
396
            instserverf = form.save()
397
            return HttpResponseRedirect(reverse("servers"))
398
        else:
399
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
400
        if server:
401
            edit = True
402
        return render_to_response('edumanage/servers_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
403
                                  context_instance=RequestContext(request, base_response(request)))
404

    
405

    
406
@login_required
407
@social_active_required
408
@never_cache
409
def cat_enroll(request):
410
    user = request.user
411
    edit = False
412
    cat_url = None
413
    inst_uid = None
414
    try:
415
        profile = user.get_profile()
416
        inst = profile.institution
417
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
418
    except UserProfile.DoesNotExist:
419
        return HttpResponseRedirect(reverse("manage"))
420
    try:
421
        instdetails = inst.institutiondetails
422
    except InstitutionDetails.DoesNotExist:
423
        return HttpResponseRedirect(reverse("manage"))
424
    if inst.ertype not in [1,3]:
425
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP')
426
        return render_to_response('edumanage/catenroll.html', { 'status':False },
427
                                  context_instance=RequestContext(request, base_response(request)))
428
    if request.method == "GET":
429
        current_enrollments = inst.catenrollment_set.all()
430
        current_enrollments_list = current_enrollments.values_list('cat_instance', flat=True)
431
        available_enrollments = [(x[0], x[1]) for x in settings.CAT_INSTANCES if x[0] not in current_enrollments_list]
432
        if len(available_enrollments) == 0:
433
            messages.add_message(request, messages.ERROR, 'There are no available CAT instances for your institution enrollment')
434
            return render_to_response('edumanage/catenroll.html', { 'status': False, 'cat_instances': available_enrollments},
435
                                  context_instance=RequestContext(request, base_response(request)))
436
        return render_to_response('edumanage/catenroll.html', { 'status': True, 'current_enrollments': current_enrollments, 'cat_instances': available_enrollments},
437
                                  context_instance=RequestContext(request, base_response(request)))
438
    elif request.method == 'POST':
439
        request_data = request.POST.copy()
440
        instance = request_data['catinstance']
441
        #Check if cat enrollment exists. It should not! 
442
        if inst.catenrollment_set.filter(cat_instance=instance):
443
            messages.add_message(request, messages.ERROR, 'There is already and enrollment for this CAT instance')
444
            return HttpResponseRedirect(reverse("catenroll"))
445
        try:
446
            cat_instance = settings.CAT_AUTH[instance]
447
        except:
448
            messages.add_message(request, messages.ERROR, 'Invalid CAT instance')
449
            return HttpResponseRedirect(reverse("catenroll"))
450
        cat_api_key = cat_instance['CAT_API_KEY']
451
        cat_api_url = cat_instance['CAT_API_URL']
452
       
453
        enroll = CatQuery(cat_api_key, cat_api_url)
454
        params = {'NEWINST_PRIMARYADMIN': u"%s"%user.email,
455
                    'option[S1]': 'general:instname',
456
                    'value[S1-0]': u"%s"%inst.get_name('en'),
457
                    'value[S1-lang]': 'en'}
458
        newinst = enroll.newinst(params)
459
        cat_url = None
460
        inst_uid = None
461
        if newinst:
462
            # this should be True only for successful postings
463
            status = enroll.status
464
            response = enroll.response
465
            inst_uid = response['inst_unique_id']
466
            cat_url = response['enrollment_URL']
467
            catentry = CatEnrollment()
468
            catentry.cat_inst_id = inst_uid
469
            catentry.inst = inst
470
            catentry.url = cat_url
471
            catentry.applier = user
472
            catentry.cat_instance = instance
473
            catentry.save()
474
            # We should notify the user
475
        else:
476
            status = enroll.status
477
            response = enroll.response
478
        return render_to_response('edumanage/catenroll.html', { 'status': True, 'response_status': status, 'response': response, 'cat_url':cat_url, 'inst_uid': inst_uid},
479
                                  context_instance=RequestContext(request, base_response(request)))
480

    
481

    
482

    
483

    
484
@login_required
485
@social_active_required
486
@never_cache
487
def del_server(request):
488
    if request.method == 'GET':
489
        user = request.user
490
        req_data = request.GET.copy()
491
        server_pk = req_data['server_pk']
492
        try:
493
            profile = user.get_profile()
494
            institution = profile.institution
495
        except UserProfile.DoesNotExist:
496
            resp['error'] = "Could not delete server. Not enough rights"
497
            return HttpResponse(json.dumps(resp), mimetype='application/json')
498
        resp = {}
499
        try:
500
            server = InstServer.objects.get(instid=institution, pk=server_pk)
501
        except InstServer.DoesNotExist:
502
            resp['error'] = "Could not get server or you have no rights to delete"
503
            return HttpResponse(json.dumps(resp), mimetype='application/json')
504
        try:
505
            server.delete()
506
        except:
507
            resp['error'] = "Could not delete server"
508
            return HttpResponse(json.dumps(resp), mimetype='application/json')
509
        resp['success'] = "Server successfully deleted"
510
        return HttpResponse(json.dumps(resp), mimetype='application/json')
511

    
512

    
513
@login_required
514
@social_active_required
515
@never_cache
516
def realms(request):
517
    user = request.user
518
    servers = False
519
    try:
520
        profile = user.get_profile()
521
        inst = profile.institution
522
    except UserProfile.DoesNotExist:
523
        return HttpResponseRedirect(reverse("manage"))
524
    if inst:
525
        realms = InstRealm.objects.filter(instid=inst)
526
    if inst.ertype not in [1,3]:
527
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP')
528
    return render_to_response('edumanage/realms.html', { 'realms': realms },
529
                                  context_instance=RequestContext(request, base_response(request)))
530

    
531

    
532
@login_required
533
@social_active_required
534
@never_cache
535
def add_realm(request, realm_pk):
536
    user = request.user
537
    server = False
538
    realm = False
539
    edit = False
540
    try:
541
        profile = user.get_profile()
542
        inst = profile.institution
543
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
544
    except UserProfile.DoesNotExist:
545
        return HttpResponseRedirect(reverse("manage"))
546
    try:
547
        instdetails = inst.institutiondetails
548
    except InstitutionDetails.DoesNotExist:
549
        return HttpResponseRedirect(reverse("manage"))
550
    if inst.ertype not in [1,3]:
551
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realm. Your institution should be either IdP or IdP/SP')
552
        return render_to_response('edumanage/realms_edit.html', { 'edit': edit },
553
                                  context_instance=RequestContext(request, base_response(request)))
554
    if request.method == "GET":
555

    
556
        # Determine add or edit
557
        try:         
558
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
559
            form = InstRealmForm(instance=realm)
560
        except InstRealm.DoesNotExist:
561
            form = InstRealmForm()
562
            if realm_pk:
563
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this realm')
564
                return HttpResponseRedirect(reverse("realms"))
565
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
566
        form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst, True)))
567
        if realm:
568
            edit = True
569
        return render_to_response('edumanage/realms_edit.html', { 'form': form, 'edit': edit },
570
                                  context_instance=RequestContext(request, base_response(request)))
571
    elif request.method == 'POST':
572
        request_data = request.POST.copy()
573
        try:         
574
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
575
            form = InstRealmForm(request_data, instance=realm)
576
        except InstRealm.DoesNotExist:
577
            form = InstRealmForm(request_data)
578
            if realm_pk:
579
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this realm')
580
                return HttpResponseRedirect(reverse("realms")) 
581
        if form.is_valid():
582
            instserverf = form.save()
583
            return HttpResponseRedirect(reverse("realms"))
584
        else:
585
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
586
            form.fields['proxyto'] = forms.ModelMultipleChoiceField(queryset=InstServer.objects.filter(pk__in=getInstServers(inst, True)))
587
        if realm:
588
            edit = True
589
        return render_to_response('edumanage/realms_edit.html', { 'institution': inst, 'form': form, 'edit': edit },
590
                                  context_instance=RequestContext(request, base_response(request)))
591

    
592

    
593
@login_required
594
@social_active_required
595
@never_cache
596
def del_realm(request):
597
    if request.method == 'GET':
598
        user = request.user
599
        req_data = request.GET.copy()
600
        realm_pk = req_data['realm_pk']
601
        try:
602
            profile = user.get_profile()
603
            institution = profile.institution
604
        except UserProfile.DoesNotExist:
605
            resp['error'] = "Not enough rights"
606
            return HttpResponse(json.dumps(resp), mimetype='application/json')
607
        resp = {}
608
        try:
609
            realm = InstRealm.objects.get(instid=institution, pk=realm_pk)
610
        except InstRealm.DoesNotExist:
611
            resp['error'] = "Could not get realm or you have no rights to delete"
612
            return HttpResponse(json.dumps(resp), mimetype='application/json')
613
        try:
614
            realm.delete()
615
        except:
616
            resp['error'] = "Could not delete realm"
617
            return HttpResponse(json.dumps(resp), mimetype='application/json')
618
        resp['success'] = "Realm successfully deleted"
619
        return HttpResponse(json.dumps(resp), mimetype='application/json')
620

    
621

    
622
@login_required
623
@social_active_required
624
@never_cache
625
def contacts(request):
626
    user = request.user
627
    servers = False
628
    instcontacts = []
629
    try:
630
        profile = user.get_profile()
631
        inst = profile.institution
632
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
633
    except UserProfile.DoesNotExist:
634
        return HttpResponseRedirect(reverse("manage"))
635
    try:
636
        instdetails = inst.institutiondetails
637
    except InstitutionDetails.DoesNotExist:
638
        return HttpResponseRedirect(reverse("manage"))
639
    if inst:
640
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=inst)])
641
        contacts = Contact.objects.filter(pk__in=instcontacts)
642
    return render_to_response('edumanage/contacts.html', { 'contacts': contacts},
643
                                  context_instance=RequestContext(request, base_response(request)))
644

    
645

    
646
@login_required
647
@social_active_required
648
@never_cache
649
def add_contact(request, contact_pk):
650
    user = request.user
651
    server = False
652
    edit = False
653
    contact = False
654
    try:
655
        profile = user.get_profile()
656
        inst = profile.institution
657
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
658
    except UserProfile.DoesNotExist:
659
        return HttpResponseRedirect(reverse("manage"))
660
    try:
661
        instdetails = inst.institutiondetails
662
    except InstitutionDetails.DoesNotExist:
663
        return HttpResponseRedirect(reverse("manage"))
664
    if request.method == "GET":
665

    
666
        # Determine add or edit
667
        try:         
668
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
669
            contact = contactinst.contact
670
            form = ContactForm(instance=contact)
671
        except InstitutionContactPool.DoesNotExist:
672
            form = ContactForm()
673
            if contact_pk:
674
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this contact')
675
                return HttpResponseRedirect(reverse("contacts"))
676
        if contact:
677
            edit = True
678
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit" : edit},
679
                                  context_instance=RequestContext(request, base_response(request)))
680
    elif request.method == 'POST':
681
        request_data = request.POST.copy()
682
        try:         
683
            contactinst = InstitutionContactPool.objects.get(institution=inst, contact__pk=contact_pk)
684
            contact = contactinst.contact
685
            form = ContactForm(request_data, instance=contact)
686
        except InstitutionContactPool.DoesNotExist:
687
            form = ContactForm(request_data)
688
            if contact_pk:
689
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this contact')
690
                return HttpResponseRedirect(reverse("contacts"))
691
        
692
        if form.is_valid():
693
            contact = form.save()
694
            instContPool, created = InstitutionContactPool.objects.get_or_create(contact=contact, institution=inst)
695
            instContPool.save()
696
            return HttpResponseRedirect(reverse("contacts"))
697
        if contact:
698
            edit = True
699
        return render_to_response('edumanage/contacts_edit.html', { 'form': form, "edit": edit},
700
                                  context_instance=RequestContext(request, base_response(request)))
701

    
702

    
703
@login_required
704
@social_active_required
705
@never_cache
706
def del_contact(request):
707
    if request.method == 'GET':
708
        user = request.user
709
        req_data = request.GET.copy()
710
        contact_pk = req_data['contact_pk']
711
        try:
712
            profile = user.get_profile()
713
            institution = profile.institution
714
        except UserProfile.DoesNotExist:
715
            resp['error'] = "Could not delete contact. Not enough rights"
716
            return HttpResponse(json.dumps(resp), mimetype='application/json')
717
        resp = {}
718
        try:
719
            contactinst = InstitutionContactPool.objects.get(institution=institution, contact__pk=contact_pk)
720
            contact = contactinst.contact
721
        except InstitutionContactPool.DoesNotExist:
722
            resp['error'] = "Could not get contact or you have no rights to delete"
723
            return HttpResponse(json.dumps(resp), mimetype='application/json')
724
        try:
725
            for service in ServiceLoc.objects.filter(institutionid=institution):
726
                if (contact in service.contact.all() and len(service.contact.all()) == 1):
727
                    resp['error'] = "Could not delete contact. It is the only contact in service <b>%s</b>.<br>Fix it and try again" %service.get_name(lang="en")
728
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
729
            if (contact in institution.institutiondetails.contact.all() and len(institution.institutiondetails.contact.all()) == 1):
730
                    resp['error'] = "Could not delete contact. It is the only contact your institution.<br>Fix it and try again"
731
                    return HttpResponse(json.dumps(resp), mimetype='application/json')
732
            contact.delete()
733
        except Exception:
734
            resp['error'] = "Could not delete contact"
735
            return HttpResponse(json.dumps(resp), mimetype='application/json')
736
        resp['success'] = "Contact successfully deleted"
737
        return HttpResponse(json.dumps(resp), mimetype='application/json')
738

    
739

    
740
@login_required
741
@social_active_required
742
@never_cache
743
def instrealmmon(request):
744
    user = request.user
745
    servers = False
746
    instcontacts = []
747
    try:
748
        profile = user.get_profile()
749
        inst = profile.institution
750
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
751
    except UserProfile.DoesNotExist:
752
        return HttpResponseRedirect(reverse("manage"))
753
    try:
754
        instdetails = inst.institutiondetails
755
    except InstitutionDetails.DoesNotExist:
756
        return HttpResponseRedirect(reverse("manage"))
757
    if inst:
758
        instrealmmons = InstRealmMon.objects.filter(realm__instid=inst)
759
    return render_to_response('edumanage/instrealmmons.html', { 'realms': instrealmmons},
760
                                  context_instance=RequestContext(request, base_response(request)))
761

    
762
@login_required
763
@social_active_required
764
@never_cache
765
def add_instrealmmon(request, instrealmmon_pk):
766
    user = request.user
767
    instrealmmon = False
768
    edit = False
769
    try:
770
        profile = user.get_profile()
771
        inst = profile.institution
772
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
773
    except UserProfile.DoesNotExist:
774
        return HttpResponseRedirect(reverse("manage"))
775
    try:
776
        instdetails = inst.institutiondetails
777
    except InstitutionDetails.DoesNotExist:
778
        return HttpResponseRedirect(reverse("manage"))
779
    if request.method == "GET":
780
        # Determine add or edit
781
        try:         
782
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
783
            form = InstRealmMonForm(instance=instrealmmon)
784
        except InstRealmMon.DoesNotExist:
785
            form = InstRealmMonForm()
786
            if instrealmmon_pk:
787
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm')
788
                return HttpResponseRedirect(reverse("instrealmmon"))
789
        if instrealmmon:
790
            edit = True
791
        form.fields['realm'] = forms.ModelChoiceField(queryset=InstRealm.objects.filter(instid=inst.pk).exclude(realm__startswith="*"), empty_label=None)
792
        return render_to_response('edumanage/instrealmmon_edit.html', { 'form': form, "edit" : edit},
793
                                  context_instance=RequestContext(request, base_response(request)))
794
    elif request.method == 'POST':
795
        request_data = request.POST.copy()
796
        try:         
797
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
798
            form = InstRealmMonForm(request_data, instance=instrealmmon)
799
        except InstRealmMon.DoesNotExist:
800
            form = InstRealmMonForm(request_data)
801
            if instrealmmon_pk:
802
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm')
803
                return HttpResponseRedirect(reverse("instrealmmon"))
804
        if form.is_valid():
805
            instrealmmonobj = form.save()
806
            return HttpResponseRedirect(reverse("instrealmmon"))
807
        if instrealmmon:
808
            edit = True
809
        form.fields['realm'] = forms.ModelChoiceField(queryset=InstRealm.objects.filter(instid=inst.pk).exclude(realm__startswith="*"), empty_label=None)
810
        return render_to_response('edumanage/instrealmmon_edit.html', { 'form': form, "edit": edit},
811
                                  context_instance=RequestContext(request, base_response(request)))
812

    
813
@login_required
814
@social_active_required
815
@never_cache
816
def del_instrealmmon(request):
817
    if request.method == 'GET':
818
        user = request.user
819
        req_data = request.GET.copy()
820
        instrealmmon_pk = req_data['instrealmmon_pk']
821
        try:
822
            profile = user.get_profile()
823
            institution = profile.institution
824
        except UserProfile.DoesNotExist:
825
            resp['error'] = "Could not delete monitored realm. Not enough rights"
826
            return HttpResponse(json.dumps(resp), mimetype='application/json')
827
        resp = {}
828
        try:
829
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=institution)
830
            instrealmmon.delete()
831
        except InstRealmMon.DoesNotExist:
832
            resp['error'] = "Could not get monitored realm or you have no rights to delete"
833
            return HttpResponse(json.dumps(resp), mimetype='application/json')
834
        resp['success'] = "Contact successfully deleted"
835
        return HttpResponse(json.dumps(resp), mimetype='application/json')
836

    
837
@login_required
838
@social_active_required
839
@never_cache
840
def add_monlocauthpar(request, instrealmmon_pk, monlocauthpar_pk):
841
    user = request.user
842
    monlocauthpar = False
843
    edit = False
844
    try:
845
        profile = user.get_profile()
846
        inst = profile.institution
847
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
848
    except UserProfile.DoesNotExist:
849
        return HttpResponseRedirect(reverse("manage"))
850
    try:
851
        instdetails = inst.institutiondetails
852
    except InstitutionDetails.DoesNotExist:
853
        return HttpResponseRedirect(reverse("manage"))
854
    if request.method == "GET":
855
        # Determine add or edit
856
        try:
857
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
858
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=inst)
859
            form = MonLocalAuthnParamForm(instance=monlocauthpar)
860
        except MonLocalAuthnParam.DoesNotExist:
861
            form = MonLocalAuthnParamForm()
862
            if monlocauthpar_pk:
863
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
864
                return HttpResponseRedirect(reverse("instrealmmon"))
865
        except InstRealmMon.DoesNotExist:
866
            if instrealmmon_pk:
867
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
868
            return HttpResponseRedirect(reverse("instrealmmon"))
869
        if monlocauthpar:
870
            edit = True
871
        form.fields['instrealmmonid'] = forms.ModelChoiceField(queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk), empty_label=None)
872
        return render_to_response('edumanage/monlocauthpar_edit.html', { 'form': form, "edit" : edit, "realm":instrealmmon },
873
                                  context_instance=RequestContext(request, base_response(request)))
874
    elif request.method == 'POST':
875
        request_data = request.POST.copy()
876
        try:         
877
            instrealmmon = InstRealmMon.objects.get(pk=instrealmmon_pk, realm__instid=inst)
878
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=inst)
879
            form = MonLocalAuthnParamForm(request_data, instance=monlocauthpar)
880
        except MonLocalAuthnParam.DoesNotExist:
881
            form = MonLocalAuthnParamForm(request_data)
882
            if monlocauthpar_pk:
883
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
884
                return HttpResponseRedirect(reverse("instrealmmon"))
885
        except InstRealmMon.DoesNotExist:
886
            if instrealmmon_pk:
887
                messages.add_message(request, messages.ERROR, 'You have no rights to edit this Monitoring Realm Parameters')
888
            return HttpResponseRedirect(reverse("instrealmmon"))
889
        if form.is_valid():
890
            monlocauthparobj = form.save()
891
            return HttpResponseRedirect(reverse("instrealmmon"))
892
        if monlocauthpar:
893
            edit = True
894
        form.fields['instrealmmonid'] = forms.ModelChoiceField(queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk), empty_label=None)
895
        return render_to_response('edumanage/monlocauthpar_edit.html', { 'form': form, "edit": edit, "realm":instrealmmon},
896
                                  context_instance=RequestContext(request, base_response(request)))
897

    
898
@login_required
899
@social_active_required
900
@never_cache
901
def del_monlocauthpar(request):
902
    if request.method == 'GET':
903
        user = request.user
904
        req_data = request.GET.copy()
905
        monlocauthpar_pk = req_data['monlocauthpar_pk']
906
        try:
907
            profile = user.get_profile()
908
            institution = profile.institution
909
        except UserProfile.DoesNotExist:
910
            resp['error'] = "Could not delete realm monitoring parameters. Not enough rights"
911
            return HttpResponse(json.dumps(resp), mimetype='application/json')
912
        resp = {}
913
        try:
914
            monlocauthpar = MonLocalAuthnParam.objects.get(pk=monlocauthpar_pk, instrealmmonid__realm__instid=institution)
915
            monlocauthpar.delete()
916
        except MonLocalAuthnParam.DoesNotExist:
917
            resp['error'] = "Could not get realm monitoring parameters or you have no rights to delete"
918
            return HttpResponse(json.dumps(resp), mimetype='application/json')
919
        resp['success'] = "Contact successfully deleted"
920
        return HttpResponse(json.dumps(resp), mimetype='application/json')
921

    
922
@login_required
923
@social_active_required
924
@never_cache
925
def adduser(request):
926
    user = request.user
927
    try:
928
        profile = user.get_profile()
929
        inst = profile.institution
930
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
931
    except UserProfile.DoesNotExist:
932
        return HttpResponseRedirect(reverse("manage"))
933

    
934
    if request.method == "GET":
935
        form = ContactForm()
936
        return render_to_response('edumanage/add_user.html', { 'form' : form },
937
                                  context_instance=RequestContext(request, base_response(request)))
938
    elif request.method == 'POST':
939
        request_data = request.POST.copy()
940
        form = ContactForm(request_data)
941
        if form.is_valid():
942
            contact = form.save()
943
            instContPool = InstitutionContactPool(contact=contact, institution=inst)
944
            instContPool.save()
945
            response_data = {}
946
            response_data['value'] = "%s" %contact.pk
947
            response_data['text'] = "%s" %contact
948
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
949
        else:
950
            return render_to_response('edumanage/add_user.html', {'form': form,},
951
                                      context_instance=RequestContext(request, base_response(request)))
952

    
953

    
954
@login_required
955
@social_active_required
956
def base_response(request):
957
    user = request.user
958
    inst = []
959
    server = []
960
    services = []
961
    instrealms = []
962
    instcontacts = []
963
    contacts = []
964
    institution = False
965
    institution_exists = False
966
    try:
967
        profile = user.get_profile()
968
        institution = profile.institution
969
        institution_exists = True
970
    except UserProfile.DoesNotExist:
971
        institution_exists = False
972
    try:
973
        inst.append(institution)
974
        server = InstServer.objects.filter(instid=institution)
975
        services = ServiceLoc.objects.filter(institutionid=institution)
976
        instrealms = InstRealm.objects.filter(instid=institution)
977
        instcontacts.extend([x.contact.pk for x in InstitutionContactPool.objects.filter(institution=institution)])
978
        contacts = Contact.objects.filter(pk__in=instcontacts)
979
        instrealmmons = InstRealmMon.objects.filter(realm__instid=institution)
980
    except:
981
        pass
982
    try:
983
        instututiondetails = institution.institutiondetails
984
    except:
985
        instututiondetails = False
986
    return { 
987
            'inst_num': len(inst),
988
            'servers_num': len(server),
989
            'services_num': len(services),
990
            'realms_num': len(instrealms),
991
            'contacts_num': len(contacts),
992
            'monrealms_num': len(instrealmmons),
993
            'institution': institution,
994
            'institutiondetails': instututiondetails,
995
            'institution_exists': institution_exists,
996
            
997
        }
998

    
999

    
1000
@login_required
1001
@social_active_required
1002
@never_cache
1003
def get_service_points(request):
1004
    if request.method == "GET":
1005
        user = request.user
1006
        try:
1007
            profile = user.get_profile()
1008
            inst = profile.institution
1009
        except UserProfile.DoesNotExist:
1010
            inst = False
1011
            return HttpResponseNotFound('<h1>Something went really wrong</h1>')
1012
        servicelocs = ServiceLoc.objects.filter(institutionid=inst)
1013
        
1014
        locs = []
1015
        for sl in servicelocs:
1016
            response_location = {}
1017
            response_location['lat'] = u"%s"%sl.latitude
1018
            response_location['lng'] = u"%s"%sl.longitude
1019
            response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
1020
            if len(sl.enc_level[0]) != 0:
1021
                response_location['enc'] = u"%s"%(','.join(sl.enc_level))
1022
            else:
1023
                response_location['enc'] = u"-"
1024
            response_location['AP_no'] = u"%s"%(sl.AP_no)
1025
            response_location['name'] = sl.loc_name.get(lang='en').name
1026
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
1027
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
1028
            response_location['IPv6'] = u"%s"%(sl.IPv6)
1029
            response_location['NAT'] = u"%s"%(sl.NAT)
1030
            response_location['wired'] = u"%s"%(sl.wired)
1031
            response_location['SSID'] = u"%s"%(sl.SSID)
1032
            response_location['key'] = u"%s"%sl.pk
1033
            locs.append(response_location)
1034
        return HttpResponse(json.dumps(locs), mimetype='application/json')
1035
    else:
1036
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
1037

    
1038
@never_cache
1039
def overview(request):
1040
    user = request.user
1041
    if user.is_authenticated():
1042
        if user.has_perm('accounts.overview'):
1043
            users = User.objects.all()
1044
            institutions = Institution.objects.all()
1045
            return render_to_response('overview/index.html', {'users': users, 'institutions': institutions},
1046
                                  context_instance=RequestContext(request))
1047
        else:
1048
            violation=True
1049
            return render_to_response('overview/index.html', {'violation': violation},
1050
                                  context_instance=RequestContext(request))
1051
    else:
1052
        return HttpResponseRedirect(reverse("altlogin"))
1053
    
1054

    
1055

    
1056
@never_cache
1057
def get_all_services(request):
1058
    lang = request.LANGUAGE_CODE
1059
    servicelocs = ServiceLoc.objects.all()
1060
    locs = []
1061
    for sl in servicelocs:
1062
        response_location = {}
1063
        response_location['lat'] = u"%s"%sl.latitude
1064
        response_location['lng'] = u"%s"%sl.longitude
1065
        response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
1066
        if len(sl.enc_level[0]) != 0:
1067
            response_location['enc'] = u"%s"%(','.join(sl.enc_level))
1068
        else:
1069
            response_location['enc'] = u"-"
1070
        response_location['AP_no'] = u"%s"%(sl.AP_no)
1071
        try:
1072
            response_location['inst'] = sl.institutionid.org_name.get(lang=lang).name
1073
        except Name_i18n.DoesNotExist:
1074
            response_location['inst'] = sl.institutionid.org_name.get(lang='en').name
1075
        try:
1076
            response_location['name'] = sl.loc_name.get(lang=lang).name
1077
        except Name_i18n.DoesNotExist:
1078
            response_location['name'] = sl.loc_name.get(lang='en').name
1079
        response_location['port_restrict'] = u"%s"%(sl.port_restrict)
1080
        response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
1081
        response_location['IPv6'] = u"%s"%(sl.IPv6)
1082
        response_location['NAT'] = u"%s"%(sl.NAT)
1083
        response_location['wired'] = u"%s"%(sl.wired)
1084
        response_location['SSID'] = u"%s"%(sl.SSID)
1085
        response_location['key'] = u"%s"%sl.pk
1086
        locs.append(response_location)
1087
    return HttpResponse(json.dumps(locs), mimetype='application/json')
1088

    
1089
@never_cache
1090
def manage_login(request,backend):
1091
    logout(request)
1092
    qs = request.GET.urlencode()
1093
    qs = '?%s' % qs if qs else ''
1094
    if backend == 'shibboleth':
1095
        return redirect(reverse('login'))
1096
    return redirect(reverse('socialauth_begin', args=[backend])+qs)
1097

    
1098
@never_cache
1099
def user_login(request):
1100
    try:
1101
        error_username = False
1102
        error_orgname = False
1103
        error_entitlement = False
1104
        error_mail = False
1105
        has_entitlement = False
1106
        error = ''
1107
        username = request.META['HTTP_EPPN']
1108
        if not username:
1109
            error_username = True
1110
        firstname = lookupShibAttr(settings.SHIB_FIRSTNAME, request.META)
1111
        lastname = lookupShibAttr(settings.SHIB_LASTNAME, request.META)
1112
        mail = lookupShibAttr(settings.SHIB_MAIL, request.META)
1113
        entitlement = lookupShibAttr(settings.SHIB_ENTITLEMENT, request.META)
1114

    
1115
        #organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
1116
        entitlement = request.META['HTTP_SHIB_EP_ENTITLEMENT']
1117
        if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
1118
            has_entitlement = True
1119
        if not has_entitlement:
1120
            error_entitlement = True
1121
#        if not organization:
1122
#            error_orgname = True
1123
        if not mail:
1124
            error_mail = True
1125
        if error_username:
1126
            error = _("Your idP should release the eduPersonPrincipalName attribute towards this service<br>")
1127
        if error_entitlement:
1128
            error = error + _("Your idP should release an appropriate eduPersonEntitlement attribute towards this service<br>")
1129
        if error_mail:
1130
            error = error + _("Your idP should release the mail attribute towards this service")
1131
        if error_username or error_orgname or error_entitlement or error_mail:
1132
            return render_to_response('status.html', {'error': error, "missing_attributes": True},
1133
                                  context_instance=RequestContext(request))
1134
        try:
1135
            user = User.objects.get(username__exact=username)
1136
            user.email = mail
1137
            user.first_name = firstname
1138
            user.last_name = lastname
1139
            user.save()
1140
            user_exists = True
1141
        except User.DoesNotExist:
1142
            user_exists = False
1143
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
1144
        if user is not None:
1145
            try:
1146
                profile = user.get_profile()
1147
                inst = profile.institution
1148
            except UserProfile.DoesNotExist:
1149
                form = UserProfileForm()
1150
                form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1151
                form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1152
                form.fields['email'] = forms.CharField(initial = user.email)
1153
                return render_to_response('registration/select_institution.html', {'form': form}, context_instance=RequestContext(request))
1154
            if user.is_active:
1155
               login(request, user)
1156
               return HttpResponseRedirect(reverse("manage"))
1157
            else:
1158
                status = _("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
1159
                return render_to_response('status.html', {'status': status, 'inactive': True},
1160
                                  context_instance=RequestContext(request))
1161
        else:
1162
            error = _("Something went wrong during user authentication. Contact your administrator %s" %user)
1163
            return render_to_response('status.html', {'error': error,},
1164
                                  context_instance=RequestContext(request))
1165
    except Exception as e:
1166
        error = _("Invalid login procedure. Error: %s"%e)
1167
        return render_to_response('status.html', {'error': error,},
1168
                                  context_instance=RequestContext(request))
1169

    
1170
@never_cache
1171
def check_user_inst(request):
1172
    u = request.user.__dict__
1173
    s = request.session.keys()
1174
    raise Exception
1175
    try:
1176
        profile = user.get_profile()
1177
        inst = profile.institution
1178
        if user.is_active:
1179
            return HttpResponseRedirect(reverse("manage"))
1180
        else:
1181
           status = _("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
1182
           return render_to_response('status.html', {'status': status, 'inactive': True},
1183
                                  context_instance=RequestContext(request))
1184
    except UserProfile.DoesNotExist:
1185
        form = UserProfileForm()
1186
        form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
1187
        nomail = False
1188
        if not user.email:
1189
            nomail = True
1190
            form.fields['email'] = forms.CharField()
1191
        else:
1192
            form.fields['email'] = forms.CharField(initial = user.email)
1193
        form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1194
        return render_to_response('registration/select_institution.html', {'form': form, 'nomail': nomail}, context_instance=RequestContext(request))
1195

    
1196

    
1197
@never_cache
1198
def geolocate(request):
1199
    return render_to_response('front/geolocate.html', context_instance=RequestContext(request))
1200
@never_cache
1201
def participants(request):
1202
    institutions = Institution.objects.all().select_related('institutiondetails')
1203
    dets = []
1204
    for i in institutions:
1205
        try:
1206
            dets.append(i.institutiondetails)
1207
        except InstitutionDetails.DoesNotExist:
1208
            pass
1209
    return render_to_response('front/participants.html', { 'institutions': dets } ,
1210
                                  context_instance=RequestContext(request))
1211
@never_cache
1212
def selectinst(request):
1213
    if request.method == 'POST':
1214
        request_data = request.POST.copy()
1215
        user = request_data['user']
1216
        try:
1217
            existingProfile = UserProfile.objects.get(user=user)
1218
            error = _("Violation warning: User account is already associated with an institution.The event has been logged and our administrators will be notified about it")
1219
            return render_to_response('status.html', {'error': error, 'inactive': True},
1220
                                  context_instance=RequestContext(request))
1221
        except UserProfile.DoesNotExist:
1222
            pass
1223
            
1224
        form = UserProfileForm(request_data)
1225
        if form.is_valid():
1226
            mailField = form.cleaned_data.pop('email')
1227
            userprofile = form.save()
1228
            useradded = userprofile.user
1229
            useradded.email = mailField
1230
            useradded.save()
1231
            user_activation_notify(userprofile)
1232
            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
1233
            return render_to_response('status.html', {'status': error, 'inactive': True},
1234
                                  context_instance=RequestContext(request))
1235
        else:
1236
            form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user), empty_label=None)
1237
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
1238
            nomail = False
1239
            userObj = User.objects.get(pk=user)
1240
            if not userObj.email:
1241
                nomail = True
1242
                form.fields['email'] = forms.CharField()
1243
            else:
1244
                form.fields['email'] = forms.CharField(initial = userObj.email)
1245
            return render_to_response('registration/select_institution.html', {'form': form, 'nomail': nomail}, context_instance=RequestContext(request))
1246

    
1247

    
1248
def user_activation_notify(userprofile):
1249
    current_site = Site.objects.get_current()
1250
    subject = render_to_string('registration/activation_email_subject.txt',
1251
                                   { 'site': current_site })
1252
    # Email subject *must not* contain newlines
1253
    subject = ''.join(subject.splitlines())
1254
    registration_profile = RegistrationProfile.objects.create_profile(userprofile.user)
1255
    message = render_to_string('registration/activation_email.txt',
1256
                                   { 'activation_key': registration_profile.activation_key,
1257
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
1258
                                     'site': current_site,
1259
                                     'user': userprofile.user,
1260
                                     'institution': userprofile.institution })
1261
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
1262
                              message, settings.SERVER_EMAIL,
1263
                             settings.NOTIFY_ADMIN_MAILS, [])
1264
@never_cache
1265
def closest(request):
1266
    if request.method == 'GET':
1267
        locs = []
1268
        request_data = request.GET.copy()
1269
        response_location = {}
1270
        if 'lat' in request.GET and 'lng' in request.GET:
1271
            response_location["lat"] = request_data['lat']
1272
            response_location["lng"] = request_data['lng']
1273
        else:
1274
            response = {"status":"Cannot parse a request without longitude or latitude. Use ?lng=<langitude>&lat=<latitude>&_=<random_num> in your query"}
1275
            return HttpResponse(json.dumps(response), mimetype='application/json')
1276
        lat = float(request_data['lat'])
1277
        lng = float(request_data['lng'])
1278
        R = 6371
1279
        distances = {}
1280
        closestMarker = {}
1281
        closest = -1
1282
        points = getPoints()
1283
        for (counter, i) in enumerate(points):
1284
            pointname = i['text']
1285
            pointlng = i['lng'] 
1286
            pointlat = i['lat']
1287
            pointtext = i['text']
1288
            plainname = i['name']
1289
            dLat = rad(float(pointlat)-float(lat))
1290
            dLong = rad(float(pointlng)-float(lng))
1291
            a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(rad(lat)) * math.cos(rad(float(pointlat))) * math.sin(dLong/2) * math.sin(dLong/2) 
1292
            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
1293
            d = R * c
1294
            distances[counter] = d
1295
            if (closest == -1 or d < distances[closest]):
1296
                closest = counter
1297
                closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": pointtext, 'plainname':plainname}
1298
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
1299
    else:
1300
        response = {"status":"Use a GET method for your request"}
1301
        return HttpResponse(json.dumps(response), mimetype='application/json')
1302

    
1303
@never_cache
1304
def worldPoints(request):
1305
    if request.method == 'GET':
1306
        points = getPoints()
1307
        return HttpResponse(json.dumps(points), mimetype='application/json')
1308

    
1309
@never_cache
1310
def world(request):
1311
        return render_to_response('front/world.html', context_instance=RequestContext(request))
1312

    
1313

    
1314
@never_cache
1315
def managementPage(request):
1316
    return render_to_response('front/management.html',
1317
                                  context_instance=RequestContext(request))
1318

    
1319
def getPoints():
1320
    points = cache.get('points')
1321
    if points:
1322
        points = bz2.decompress(points)
1323
        return json.loads(points)
1324
    else:
1325
        point_list = []
1326
        doc = ET.parse(settings.KML_FILE)
1327
        root = doc.getroot()
1328
        r = root.getchildren()[0]
1329
        for (counter, i) in enumerate(r.getchildren()):
1330
            if "id" in i.keys():
1331
                j = i.getchildren()
1332
                pointname = j[0].text
1333
                point = j[2].getchildren()[0].text
1334
                pointlng, pointlat, pointele = point.split(',')
1335
                Marker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
1336
                point_list.append(Marker);
1337
        points = json.dumps(point_list)
1338
        cache.set('points', bz2.compress(points), 60 * 3600 * 24)
1339
        return json.loads(points)
1340

    
1341

    
1342
@never_cache
1343
def instxml(request):
1344
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1345
    root = ET.Element("institutions")
1346
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1347
    root.set(NS_XSI + "noNamespaceSchemaLocation", "institution.xsd")
1348
    institutions = Institution.objects.all()
1349
    for institution in institutions:
1350
        try:
1351
            inst = institution.institutiondetails
1352
            if not inst:
1353
                pass
1354
        except InstitutionDetails.DoesNotExist:
1355
            pass
1356
        
1357
        instElement = ET.SubElement(root, "institution")
1358
        
1359
        instCountry = ET.SubElement(instElement, "country")
1360
        instCountry.text = ("%s" %inst.institution.realmid.country).upper()
1361
        
1362
        instType = ET.SubElement(instElement, "type")
1363
        instType.text = "%s" %inst.institution.ertype
1364
        
1365
        for realm in institution.instrealm_set.all():
1366
            instRealm = ET.SubElement(instElement, "inst_realm")
1367
            instRealm.text = realm.realm
1368
        
1369
        for name in inst.institution.org_name.all():
1370
            instOrgName = ET.SubElement(instElement, "org_name")
1371
            instOrgName.attrib["lang"] = name.lang
1372
            instOrgName.text = u"%s" %name.name
1373
        
1374
        instAddress = ET.SubElement(instElement, "address")
1375
        
1376
        instAddrStreet = ET.SubElement(instAddress, "street")
1377
        instAddrStreet.text = inst.address_street
1378
        
1379
        instAddrCity = ET.SubElement(instAddress, "city")
1380
        instAddrCity.text = inst.address_city
1381
        
1382
        for contact in inst.contact.all():
1383
            instContact = ET.SubElement(instElement, "contact")
1384
            
1385
            instContactName = ET.SubElement(instContact, "name")
1386
            instContactName.text = "%s" %(contact.name)
1387
            
1388
            instContactEmail = ET.SubElement(instContact, "email")
1389
            instContactEmail.text = contact.email
1390
            
1391
            instContactPhone = ET.SubElement(instContact, "phone")
1392
            instContactPhone.text = contact.phone
1393
        
1394
        urltypes = []
1395
        for url in inst.url.all():
1396
            instUrl = ET.SubElement(instElement, "%s_URL"%(url.urltype))
1397
            instUrl.attrib["lang"] = url.lang
1398
            instUrl.text = url.url
1399
            urltypes.append(url.urltype)
1400

    
1401
        if 'policy' not in urltypes:
1402
            instUrl = ET.SubElement(instElement, "policy_URL")
1403
            instUrl.attrib["lang"] = 'en'
1404
            instUrl.text = '-'
1405
        
1406
        instTs = ET.SubElement(instElement, "ts")
1407
        instTs.text = "%s" %inst.ts.isoformat()
1408
        #Let's go to Institution Service Locations
1409

    
1410
        for serviceloc in inst.institution.serviceloc_set.all():
1411
            instLocation = ET.SubElement(instElement, "location")
1412
            
1413
            instLong = ET.SubElement(instLocation, "longitude")
1414
            instLong.text = "%s" %serviceloc.longitude
1415
            
1416
            instLat = ET.SubElement(instLocation, "latitude")
1417
            instLat.text = "%s" %serviceloc.latitude
1418
            
1419
            for instlocname in serviceloc.loc_name.all():
1420
                instLocName = ET.SubElement(instLocation, "loc_name")
1421
                instLocName.attrib["lang"] = instlocname.lang
1422
                instLocName.text = instlocname.name
1423
            
1424
            instLocAddress = ET.SubElement(instLocation, "address")
1425
        
1426
            instLocAddrStreet = ET.SubElement(instLocAddress, "street")
1427
            instLocAddrStreet.text = serviceloc.address_street
1428
        
1429
            instLocAddrCity = ET.SubElement(instLocAddress, "city")
1430
            instLocAddrCity.text = serviceloc.address_city
1431
            
1432
            for contact in serviceloc.contact.all():
1433
                instLocContact = ET.SubElement(instLocation, "contact")
1434
                
1435
                instLocContactName = ET.SubElement(instLocContact, "name")
1436
                instLocContactName.text = "%s" %(contact.name)
1437
                
1438
                instLocContactEmail = ET.SubElement(instLocContact, "email")
1439
                instLocContactEmail.text = contact.email
1440
                
1441
                instLocContactPhone = ET.SubElement(instLocContact, "phone")
1442
                instLocContactPhone.text = contact.phone
1443
            
1444
            instLocSSID = ET.SubElement(instLocation, "SSID")
1445
            instLocSSID.text = serviceloc.SSID
1446
            
1447
            instLocEncLevel = ET.SubElement(instLocation, "enc_level")
1448
            instLocEncLevel.text = ', '.join(serviceloc.enc_level)
1449
            
1450
            instLocPortRestrict = ET.SubElement(instLocation, "port_restrict")
1451
            instLocPortRestrict.text = ("%s" %serviceloc.port_restrict).lower()
1452
            
1453
            instLocTransProxy = ET.SubElement(instLocation, "transp_proxy")
1454
            instLocTransProxy.text = ("%s" %serviceloc.transp_proxy).lower()
1455
            
1456
            instLocIpv6 = ET.SubElement(instLocation, "IPv6")
1457
            instLocIpv6.text = ("%s" %serviceloc.IPv6).lower()
1458
            
1459
            instLocNAT = ET.SubElement(instLocation, "NAT")
1460
            instLocNAT.text = ("%s" %serviceloc.NAT).lower()
1461
            
1462
            instLocAP_no = ET.SubElement(instLocation, "AP_no")
1463
            instLocAP_no.text = "%s" %int(serviceloc.AP_no)
1464
            
1465
            instLocWired = ET.SubElement(instLocation, "wired")
1466
            instLocWired.text = ("%s" %serviceloc.wired).lower()
1467
            
1468
            for url in serviceloc.url.all():
1469
                instLocUrl = ET.SubElement(instLocation, "%s_URL"%(url.urltype))
1470
                instLocUrl.attrib["lang"] = url.lang
1471
                instLocUrl.text = url.url
1472
            
1473
    return render_to_response("general/institution.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1474
        
1475
@never_cache
1476
def realmxml(request):
1477
    realm = Realm.objects.all()[0]
1478
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1479
    root = ET.Element("realms")
1480
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1481
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm.xsd")
1482
    realmElement = ET.SubElement(root, "realm")
1483
    
1484
    realmCountry = ET.SubElement(realmElement, "country")
1485
    realmCountry.text = realm.country.upper()
1486
        
1487
    realmStype = ET.SubElement(realmElement, "stype")
1488
    realmStype.text = "%s" %realm.stype
1489
    
1490
    for name in realm.org_name.all():
1491
        realmOrgName = ET.SubElement(realmElement, "org_name")
1492
        realmOrgName.attrib["lang"] = name.lang
1493
        realmOrgName.text = u"%s" %name.name
1494
    
1495
    realmAddress = ET.SubElement(realmElement, "address")
1496
        
1497
    realmAddrStreet = ET.SubElement(realmAddress, "street")
1498
    realmAddrStreet.text = realm.address_street
1499
    
1500
    realmAddrCity = ET.SubElement(realmAddress, "city")
1501
    realmAddrCity.text = realm.address_city
1502
    
1503
    for contact in realm.contact.all():
1504
        realmContact = ET.SubElement(realmElement, "contact")
1505
        
1506
        realmContactName = ET.SubElement(realmContact, "name")
1507
        realmContactName.text = "%s" %(contact.name)
1508
        
1509
        realmContactEmail = ET.SubElement(realmContact, "email")
1510
        realmContactEmail.text = contact.email
1511
        
1512
        realmContactPhone = ET.SubElement(realmContact, "phone")
1513
        realmContactPhone.text = contact.phone
1514
    
1515
    for url in realm.url.all():
1516
        realmUrl = ET.SubElement(realmElement, "%s_URL"%(url.urltype))
1517
        realmUrl.attrib["lang"] = url.lang
1518
        realmUrl.text = url.url
1519
    
1520
    instTs = ET.SubElement(realmElement, "ts")
1521
    instTs.text = "%s" %realm.ts.isoformat()
1522
    
1523
    return render_to_response("general/realm.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1524

    
1525
@never_cache
1526
def realmdataxml(request):
1527
    realm = Realm.objects.all()[0]
1528
    ET._namespace_map["http://www.w3.org/2001/XMLSchema-instance"] = 'xsi'
1529
    root = ET.Element("realm_data_root")
1530
    NS_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1531
    root.set(NS_XSI + "noNamespaceSchemaLocation", "realm_data.xsd")
1532
    
1533
    realmdataElement = ET.SubElement(root, "realm_data")
1534
    
1535
    realmCountry = ET.SubElement(realmdataElement, "country")
1536
    realmCountry.text = realm.country.upper()
1537
    
1538
    nIdpCountry = ET.SubElement(realmdataElement, "number_IdP")
1539
    nIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=1))
1540
    
1541
    nSPCountry = ET.SubElement(realmdataElement, "number_SP")
1542
    nSPCountry.text = "%s" %len(realm.institution_set.filter(ertype=2))
1543
    
1544
    nSPIdpCountry = ET.SubElement(realmdataElement, "number_SPIdP")
1545
    nSPIdpCountry.text = "%s" %len(realm.institution_set.filter(ertype=3))
1546
    
1547
    ninstCountry = ET.SubElement(realmdataElement, "number_inst")
1548
    ninstCountry.text = "%s" %len(realm.institution_set.all())
1549
    
1550
    nuserCountry = ET.SubElement(realmdataElement, "number_user")
1551
    insts = realm.institution_set.all()
1552
    users = 0
1553
    for inst in insts:
1554
        try:
1555
            if inst.institutiondetails.number_user:
1556
                users = users + inst.institutiondetails.number_user
1557
        except InstitutionDetails.DoesNotExist:
1558
            pass
1559
    nuserCountry.text = "%s" %users
1560
    
1561
    nIdCountry = ET.SubElement(realmdataElement, "number_id")
1562
    insts = realm.institution_set.all()
1563
    ids = 0
1564
    for inst in insts:
1565
        try:
1566
            if inst.institutiondetails.number_id:
1567
                ids = ids + inst.institutiondetails.number_id
1568
        except InstitutionDetails.DoesNotExist:
1569
            pass
1570
    nIdCountry.text = "%s" %ids
1571
    
1572
    # Get the latest ts from all tables...
1573
    datetimes = []
1574
    if InstitutionDetails.objects.aggregate(Max('ts'))['ts__max']:
1575
        datetimes.append(InstitutionDetails.objects.aggregate(Max('ts'))['ts__max'])
1576
    if Realm.objects.aggregate(Max('ts'))['ts__max']:
1577
        datetimes.append(Realm.objects.aggregate(Max('ts'))['ts__max'])
1578
    if InstServer.objects.aggregate(Max('ts'))['ts__max']:
1579
        datetimes.append(InstServer.objects.aggregate(Max('ts'))['ts__max'])
1580
    if ServiceLoc.objects.aggregate(Max('ts'))['ts__max']:
1581
        datetimes.append(ServiceLoc.objects.aggregate(Max('ts'))['ts__max'])
1582
    if len(datetimes) == 0:
1583
        datetimes.append(datetime.datetime.now())
1584
    instTs = ET.SubElement(realmdataElement, "ts")
1585
    instTs.text = "%s" %max(datetimes).isoformat()
1586
    
1587
    
1588
    return render_to_response("general/realm_data.xml", {"xml":to_xml(root)},context_instance=RequestContext(request,), mimetype="application/xml")
1589

    
1590
@never_cache
1591
def servdata(request):
1592
    root = {}
1593
    hosts = InstServer.objects.all()
1594
    insts = Institution.objects.all()
1595

    
1596
    clients = hosts.filter(ertype__in=[2,3])
1597
    if clients:
1598
        root['clients'] = {}
1599
    for srv in clients:
1600
        srv_id = getSrvIdentifier(srv, "client_")
1601
        srv_dict = {}
1602
        srv_dict['host'] = srv.host
1603
        if srv.name:
1604
            srv_dict['label'] = srv.name
1605
        srv_dict['secret'] = srv.secret
1606
        root['clients'].update({srv_id: srv_dict})
1607

    
1608
    servers = hosts.filter(ertype__in=[1,3])
1609
    if servers:
1610
        root['servers'] = {}
1611
    for srv in servers:
1612
        srv_id = getSrvIdentifier(srv, "server_")
1613
        srv_dict = {}
1614
        srv_dict['rad_pkt_type'] = srv.rad_pkt_type
1615
        if srv.rad_pkt_type.find("auth") != -1:
1616
            srv_dict['auth_port'] = srv.auth_port
1617
        if srv.rad_pkt_type.find("acct") != -1:
1618
            srv_dict['acct_port'] = srv.acct_port
1619
        srv_dict['host'] = srv.host
1620
        if srv.name:
1621
            srv_dict['label'] = srv.name
1622
        srv_dict['secret'] = srv.secret
1623
        srv_dict['status_server'] = bool(srv.status_server)
1624
        root['servers'].update({srv_id: srv_dict})
1625

    
1626
    if insts:
1627
        root['institutions'] = []
1628
    for inst in insts:
1629
        inst_dict = {}
1630
        if not hasattr(inst, "institutiondetails"):
1631
            continue
1632
        if hasattr(inst.institutiondetails, "oper_name") and \
1633
                inst.institutiondetails.oper_name:
1634
            inst_dict['id'] = inst.institutiondetails.oper_name
1635
        inst_dict['type'] = inst.ertype
1636
        if inst.ertype in (2, 3):
1637
            inst_clients = inst.instserver_set.filter(ertype__in=[2, 3])
1638
            if inst_clients:
1639
                inst_dict['clients'] = [getSrvIdentifier(srv, "client_") for
1640
                                        srv in inst_clients]
1641
        if inst.ertype in (1, 3):
1642
            inst_realms = inst.instrealm_set.all()
1643
            if inst_realms:
1644
                inst_dict['realms'] = {}
1645
            for realm in inst_realms:
1646
                rdict = {}
1647
                rdict[realm.realm] = {}
1648
                rdict[realm.realm]['proxy_to'] = [getSrvIdentifier(proxy, "server_") for
1649
                                                  proxy in realm.proxyto.all()]
1650
                inst_dict['realms'].update(rdict)
1651
        root['institutions'].append(inst_dict)
1652

    
1653

    
1654
    if 'HTTP_ACCEPT' in request.META:
1655
        ret_mimetype = request.META.get('HTTP_ACCEPT')
1656
    else:
1657
        ret_mimetype = "text/yaml"
1658

    
1659
    if ret_mimetype.find("json") != -1:
1660
        return HttpResponse(json.dumps(root),
1661
                            mimetype=ret_mimetype)
1662
    else:
1663
        if ret_mimetype.find("yaml") == -1:
1664
            ret_mimetype = "text/yaml"
1665
        from yaml import dump
1666
        try:
1667
            from yaml import CDumper as Dumper, \
1668
                CSafeDumper as SafeDumper
1669
        except ImportError:
1670
            from yaml import Dumper, SafeDumper
1671
        return HttpResponse(dump(root,
1672
                                 Dumper=SafeDumper,
1673
                                 default_flow_style=False),
1674
                            mimetype=ret_mimetype)
1675

    
1676
@never_cache
1677
def adminlist(request):
1678
    users = User.objects.all()
1679
    data = [
1680
        (u.get_profile().institution.get_name('el'),
1681
         u.first_name + " " + u.last_name,
1682
         m)
1683
        for u in users if
1684
        len(u.registrationprofile_set.all()) > 0 and
1685
        u.registrationprofile_set.all()[0].activation_key == "ALREADY_ACTIVATED"
1686
        for m in u.email.split(';')
1687
        ]
1688
    data.sort(key=lambda d: unicode(d[0]))
1689
    resp_body = ""
1690
    for (foreas, onoma, email) in data:
1691
        resp_body += u'{email}\t{onoma}'.format(
1692
            email=email,
1693
            onoma=onoma
1694
            ) \
1695
            + "\n"
1696
    return HttpResponse(resp_body,
1697
                        mimetype="text/plain")
1698

    
1699

    
1700
def to_xml(ele, encoding="UTF-8"):
1701
    "Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*."
1702
    xml = ET.tostring(ele, encoding)
1703
    return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
1704
    
1705
def getSrvIdentifier(srv, prefix):
1706
    if not hasattr(srv, "id"):
1707
        return None
1708
    retid = "{0}{1:d}".format(prefix,
1709
                              srv.id)
1710
    if hasattr(srv, "name") and srv.name:
1711
        from django.template.defaultfilters import slugify
1712
        retid = "{0}_{1}".format(retid,
1713
                                 slugify(srv.name))
1714
    return retid
1715

    
1716

    
1717
def getInstContacts(inst):
1718
    contacts = InstitutionContactPool.objects.filter(institution=inst)
1719
    contact_pks = []
1720
    for contact in contacts:
1721
        contact_pks.append(contact.contact.pk)
1722
    return list(set(contact_pks))
1723

    
1724
def getInstServers(inst, idpsp=False):
1725
    servers = InstServer.objects.filter(instid=inst)
1726
    if idpsp:
1727
        servers = servers.filter(ertype__in=[1,3])
1728
    server_pks = []
1729
    for server in servers:
1730
        server_pks.append(server.pk)
1731
    return list(set(server_pks))
1732

    
1733

    
1734
def rad(x):
1735
    return x*math.pi/180
1736

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

    
1740
def lookupShibAttr(attrmap, requestMeta):
1741
    for attr in attrmap:
1742
        if (attr in requestMeta.keys()):
1743
            if len(requestMeta[attr]) > 0:
1744
                return requestMeta[attr]
1745
    return ''
1746

    
1747

    
1748

    
1749