views.py 82.1 KB
Newer Older
1 2
# -*- coding: utf-8 -*- vim:encoding=utf-8:
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
Kroustouris Stauros's avatar
Kroustouris Stauros committed
3 4 5 6
import json
import bz2
import math
import datetime
7
from xml.etree import ElementTree
8
import locale
9

Kroustouris Stauros's avatar
Kroustouris Stauros committed
10
from django.shortcuts import render_to_response, redirect, render
11 12 13 14 15 16
from django.http import (
    HttpResponse,
    HttpResponseRedirect,
    HttpResponseNotFound,
    HttpResponseBadRequest
)
17
from django.template import RequestContext
18
from django.core.urlresolvers import reverse
19
from django.contrib.auth.decorators import login_required
20
from django.contrib.auth import logout
21
from django import forms
22
from django.contrib.contenttypes.generic import generic_inlineformset_factory
23 24 25
from django.core.mail.message import EmailMessage
from django.contrib.sites.models import Site
from django.template.loader import render_to_string
26
from django.conf import settings
27
from django.contrib import messages
28
from django.db.models import Max
29 30 31
from django.views.decorators.cache import never_cache
from django.utils.translation import ugettext as _
from django.contrib.auth import authenticate, login
32
from django.contrib.auth.models import User
33
from django.core.cache import cache
34
from django.contrib.auth import REDIRECT_FIELD_NAME
35

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
from edumanage.models import (
    ServiceLoc,
    InstRealmMon,
    InstitutionDetails,
    Realm,
    InstServer,
    URL_i18n,
    MonLocalAuthnParam,
    Institution,
    CatEnrollment,
    InstitutionContactPool,
    InstRealm,
    Contact,
    Name_i18n,
)
from accounts.models import UserProfile
from edumanage.forms import (
    InstDetailsForm,
    UrlFormSetFactInst,
    InstRealmForm,
    UserProfileForm,
    ContactForm,
    MonLocalAuthnParamForm,
    InstRealmMonForm,
    ServiceLocForm,
    NameFormSetFact,
    UrlFormSetFact,
    InstServerForm
)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
65
from registration.models import RegistrationProfile
66
from edumanage.decorators import social_active_required
67
from utils.cat_helper import CatQuery
68

Kroustouris Stauros's avatar
Kroustouris Stauros committed
69

70
@never_cache
71
def index(request):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
72 73
    return render(
        request,
Kroustouris Stauros's avatar
Kroustouris Stauros committed
74 75 76
        'front/index.html',
    )

77

78 79 80 81 82 83
@never_cache
def manage_login_front(request):
    user = request.user
    try:
        profile = user.get_profile()
    except UserProfile.DoesNotExist:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
84 85 86 87
        return render_to_response(
            'edumanage/welcome_manage.html',
            context_instance=RequestContext(request, base_response(request))
        )
88
    except AttributeError:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
89 90
        return render(
            request,
Kroustouris Stauros's avatar
Kroustouris Stauros committed
91
            'edumanage/welcome_manage.html',
Kroustouris Stauros's avatar
Kroustouris Stauros committed
92
            {}
Kroustouris Stauros's avatar
Kroustouris Stauros committed
93
        )
94 95 96
    if user.is_authenticated() and user.is_active and profile.is_social_active:
        return redirect(reverse('manage'))
    else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
97 98
        return render(
            request,
Kroustouris Stauros's avatar
Kroustouris Stauros committed
99
            'edumanage/welcome_manage.html',
Kroustouris Stauros's avatar
Kroustouris Stauros committed
100
            {}
Kroustouris Stauros's avatar
Kroustouris Stauros committed
101 102
        )

103

104
@login_required
105
@social_active_required
106
@never_cache
107 108 109
def manage(request):
    services_list = []
    servers_list = []
110 111 112 113 114
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
115 116 117 118
        return render_to_response(
            'edumanage/welcome.html',
            context_instance=RequestContext(request, base_response(request))
        )
119 120 121 122
    services = ServiceLoc.objects.filter(institutionid=inst)
    services_list.extend([s for s in services])
    servers = InstServer.objects.filter(instid=inst)
    servers_list.extend([s for s in servers])
Kroustouris Stauros's avatar
Kroustouris Stauros committed
123 124 125 126 127 128 129 130 131 132
    return render_to_response(
        'edumanage/welcome.html',
        {
            'institution': inst,
            'services': services_list,
            'servers': servers_list,
        },
        context_instance=RequestContext(request, base_response(request))
    )

133 134

@login_required
135
@social_active_required
136
@never_cache
137 138
def institutions(request):
    user = request.user
139 140 141 142 143 144
    dict = {}
    try:
        profile = user.get_profile()
        inst = profile.institution
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
    except UserProfile.DoesNotExist:
145
        return HttpResponseRedirect(reverse("manage"))
146 147 148
    dict['institution'] = inst.pk
    form = InstDetailsForm(initial=dict)
    form.fields['institution'].widget.attrs['readonly'] = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
149 150 151 152 153 154 155 156
    return render_to_response(
        'edumanage/institution.html',
        {
            'institution': inst,
            'form': form,
        },
        context_instance=RequestContext(request, base_response(request))
    )
157 158 159


@login_required
160
@social_active_required
161
@never_cache
162 163
def add_institution_details(request, institution_pk):
    user = request.user
164 165 166
    try:
        profile = user.get_profile()
        inst = profile.institution
167
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
168
    except UserProfile.DoesNotExist:
169
        return HttpResponseRedirect(reverse("manage"))
Culley Angus's avatar
Culley Angus committed
170

171
    if institution_pk and int(inst.pk) != int(institution_pk):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
172 173 174 175 176
        messages.add_message(
            request,
            messages.ERROR,
            'You have no rights on this Institution'
        )
177
        return HttpResponseRedirect(reverse("institutions"))
Culley Angus's avatar
Culley Angus committed
178

179
    if request.method == "GET":
Culley Angus's avatar
Culley Angus committed
180
        try:
181 182
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(instance=inst_details)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
183 184 185 186 187 188 189
            UrlFormSet = generic_inlineformset_factory(
                URL_i18n,
                extra=2,
                formset=UrlFormSetFactInst,
                can_delete=True
            )
            urls_form = UrlFormSet(prefix='urlsform', instance=inst_details)
190 191
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm()
Kroustouris Stauros's avatar
Kroustouris Stauros committed
192 193 194 195 196 197 198 199 200
            form.fields['institution'] = forms.ModelChoiceField(
                queryset=Institution.objects.filter(pk=institution_pk),
                empty_label=None
            )
            UrlFormSet = generic_inlineformset_factory(
                URL_i18n,
                extra=2,
                can_delete=True
            )
201
            urls_form = UrlFormSet(prefix='urlsform')
202

Kroustouris Stauros's avatar
Kroustouris Stauros committed
203 204 205 206 207 208 209 210
        form.fields['contact'] = forms.ModelMultipleChoiceField(
            queryset=Contact.objects.filter(pk__in=getInstContacts(inst))
        )
        return render_to_response(
            'edumanage/institution_edit.html',
            {'institution': inst, 'form': form, 'urls_form': urls_form},
            context_instance=RequestContext(request, base_response(request))
        )
211 212
    elif request.method == 'POST':
        request_data = request.POST.copy()
213
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
Culley Angus's avatar
Culley Angus committed
214
        try:
215 216
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(request_data, instance=inst_details)
217
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
218 219
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm(request_data)
220 221 222
            urls_form = UrlFormSet(request_data, prefix='urlsform')
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
        if form.is_valid() and urls_form.is_valid():
223
            instdets = form.save()
224
            urls_form.instance = instdets
Kroustouris Stauros's avatar
fix  
Kroustouris Stauros committed
225
            urls_form.save()
226
            return HttpResponseRedirect(reverse("institutions"))
227
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241
            form.fields['institution'] = forms.ModelChoiceField(
                queryset=Institution.objects.filter(pk=institution_pk),
                empty_label=None
            )
            form.fields['contact'] = forms.ModelMultipleChoiceField(
                queryset=Contact.objects.filter(pk__in=getInstContacts(inst))
            )
            return render_to_response(
                'edumanage/institution_edit.html',
                {'institution': inst, 'form': form, 'urls_form': urls_form},
                context_instance=RequestContext(
                    request, base_response(request)
                )
            )
242

243 244

@login_required
245
@social_active_required
246
@never_cache
247
def services(request, service_pk):
248 249 250 251
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
252
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
253
    except UserProfile.DoesNotExist:
254
        return HttpResponseRedirect(reverse("manage"))
255
    try:
Kroustouris Stauros's avatar
fix  
Kroustouris Stauros committed
256
        inst.institutiondetails
257 258
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
259 260 261 262 263 264 265 266 267 268 269
    if inst.ertype not in [2, 3]:
        messages.add_message(
            request,
            messages.ERROR,
            'Cannot add/edit Location. Your institution should be either SP or IdP/SP'
        )
        return render_to_response(
            'edumanage/services.html',
            {'institution': inst},
            context_instance=RequestContext(request, base_response(request))
        )
270
    try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
271
        services = ServiceLoc.objects.filter(institutionid=inst)
272
    except ServiceLoc.DoesNotExist:
Culley Angus's avatar
Culley Angus committed
273 274
        services = False

275
    if service_pk:
276 277 278
        try:
            services = services.get(pk=service_pk)
        except:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
279 280 281 282 283
            messages.add_message(
                request,
                messages.ERROR,
                'You have no rights to view this location'
            )
284
            return HttpResponseRedirect(reverse("services"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        return render_to_response(
            'edumanage/service_details.html',
            {
                'institution': inst,
                'service': services,
            },
            context_instance=RequestContext(request, base_response(request))
        )

    return render_to_response(
        'edumanage/services.html',
        {
            'institution': inst,
            'services': services,
        },
        context_instance=RequestContext(request, base_response(request))
    )
302 303 304


@login_required
305
@social_active_required
306
@never_cache
307 308
def add_services(request, service_pk):
    user = request.user
309
    service = False
310
    edit = False
311 312 313
    try:
        profile = user.get_profile()
        inst = profile.institution
314
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
315
    except UserProfile.DoesNotExist:
316
        return HttpResponseRedirect(reverse("manage"))
317
    try:
318
        inst.institutiondetails
319 320
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
321 322 323 324 325 326 327 328 329 330 331
    if inst.ertype not in [2, 3]:
        messages.add_message(
            request,
            messages.ERROR,
            'Cannot add/edit Service. Your institution should be either SP or IdP/SP'
        )
        return render_to_response(
            'edumanage/services_edit.html',
            {'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
332 333 334
    if request.method == "GET":

        # Determine add or edit
Culley Angus's avatar
Culley Angus committed
335
        try:
336 337 338 339
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
            form = ServiceLocForm(instance=service)
        except ServiceLoc.DoesNotExist:
            form = ServiceLocForm()
340
            if service_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
341 342 343 344 345
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this location'
                )
346
                return HttpResponseRedirect(reverse("services"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360
        form.fields['institutionid'] = forms.ModelChoiceField(
            queryset=Institution.objects.filter(pk=inst.pk),
            empty_label=None
        )
        UrlFormSet = generic_inlineformset_factory(
            URL_i18n,
            extra=2,
            can_delete=True
        )
        NameFormSet = generic_inlineformset_factory(
            Name_i18n,
            extra=2,
            can_delete=True
        )
361
        urls_form = UrlFormSet(prefix='urlsform')
362
        names_form = NameFormSet(prefix='namesform')
363
        if (service):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
364 365 366 367 368
            NameFormSet = generic_inlineformset_factory(
                Name_i18n,
                extra=1,
                formset=NameFormSetFact, can_delete=True
            )
369
            names_form = NameFormSet(instance=service, prefix='namesform')
Kroustouris Stauros's avatar
Kroustouris Stauros committed
370 371 372 373 374 375
            UrlFormSet = generic_inlineformset_factory(
                URL_i18n,
                extra=2,
                formset=UrlFormSetFact,
                can_delete=True
            )
376
            urls_form = UrlFormSet(instance=service, prefix='urlsform')
Kroustouris Stauros's avatar
Kroustouris Stauros committed
377 378 379
        form.fields['contact'] = forms.ModelMultipleChoiceField(
            queryset=Contact.objects.filter(pk__in=getInstContacts(inst))
        )
380 381
        if service:
            edit = True
382
        for url_form in urls_form.forms:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
383 384 385 386 387 388 389 390 391 392 393 394 395
            url_form.fields['urltype'] = forms.ChoiceField(
                choices=(('', '----------'), ('info', 'Info'),)
            )
        return render_to_response(
            'edumanage/services_edit.html',
            {
                'form': form,
                'services_form': names_form,
                'urls_form': urls_form,
                "edit": edit
            },
            context_instance=RequestContext(request, base_response(request))
        )
396 397
    elif request.method == 'POST':
        request_data = request.POST.copy()
Kroustouris Stauros's avatar
Kroustouris Stauros committed
398 399 400 401 402 403 404 405 406 407 408 409
        NameFormSet = generic_inlineformset_factory(
            Name_i18n,
            extra=1,
            formset=NameFormSetFact,
            can_delete=True
        )
        UrlFormSet = generic_inlineformset_factory(
            URL_i18n,
            extra=2,
            formset=UrlFormSetFact,
            can_delete=True
        )
Culley Angus's avatar
Culley Angus committed
410
        try:
411 412
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
            form = ServiceLocForm(request_data, instance=service)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
413 414 415 416 417 418 419 420 421 422
            names_form = NameFormSet(
                request_data,
                instance=service,
                prefix='namesform'
            )
            urls_form = UrlFormSet(
                request_data,
                instance=service,
                prefix='urlsform'
            )
423 424
        except ServiceLoc.DoesNotExist:
            form = ServiceLocForm(request_data)
425 426
            names_form = NameFormSet(request_data, prefix='namesform')
            urls_form = UrlFormSet(request_data, prefix='urlsform')
427
            if service_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
428 429 430 431 432
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this location'
                )
433
                return HttpResponseRedirect(reverse("services"))
434
        if form.is_valid() and names_form.is_valid() and urls_form.is_valid():
435
            serviceloc = form.save()
436 437 438
            service = serviceloc
            names_form.instance = service
            urls_form.instance = service
439 440
            names_form.save()
            urls_form.save()
441 442
            return HttpResponseRedirect(reverse("services"))
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
443 444 445 446 447 448 449
            form.fields['institutionid'] = forms.ModelChoiceField(
                queryset=Institution.objects.filter(pk=inst.pk),
                empty_label=None
            )
            form.fields['contact'] = forms.ModelMultipleChoiceField(
                queryset=Contact.objects.filter(pk__in=getInstContacts(inst))
            )
450 451
        if service:
            edit = True
452
        for url_form in urls_form.forms:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466
            url_form.fields['urltype'] = forms.ChoiceField(
                choices=(('', '----------'), ('info', 'Info'),)
            )
        return render_to_response(
            'edumanage/services_edit.html',
            {
                'institution': inst,
                'form': form,
                'services_form': names_form,
                'urls_form': urls_form,
                'edit': edit
            },
            context_instance=RequestContext(request, base_response(request))
        )
467

468

469
@login_required
470
@social_active_required
471
@never_cache
472 473
def del_service(request):
    if request.method == 'GET':
474
        user = request.user
475 476
        req_data = request.GET.copy()
        service_pk = req_data['service_pk']
477
        resp = {}
478 479
        try:
            profile = user.get_profile()
480
            institution = profile.institution
481
        except UserProfile.DoesNotExist:
482 483 484
            resp['error'] = "Could not delete service. Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
485 486 487 488
            service = ServiceLoc.objects.get(
                institutionid=institution,
                pk=service_pk
            )
489 490 491 492 493 494 495 496 497 498
        except ServiceLoc.DoesNotExist:
            resp['error'] = "Could not get service or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            service.delete()
        except:
            resp['error'] = "Could not delete service"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Service successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')
499

500

501
@login_required
502
@social_active_required
503
@never_cache
504
def servers(request, server_pk):
505 506 507 508 509 510 511
    user = request.user
    servers = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
512
        return HttpResponseRedirect(reverse("manage"))
513 514
    if inst:
        servers = InstServer.objects.filter(instid=inst)
515 516
    if server_pk:
        servers = servers.get(pk=server_pk)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
        return render_to_response(
            'edumanage/server_details.html',
            {
                'institution': inst,
                'server': servers,
            },
            context_instance=RequestContext(request, base_response(request))
        )
    return render_to_response(
        'edumanage/servers.html',
        {
            'servers': servers
        },
        context_instance=RequestContext(request, base_response(request))
    )
532

533

534
@login_required
535
@social_active_required
536
@never_cache
537 538 539
def add_server(request, server_pk):
    user = request.user
    server = False
540
    edit = False
541 542 543
    try:
        profile = user.get_profile()
        inst = profile.institution
544
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
545
    except UserProfile.DoesNotExist:
546
        return HttpResponseRedirect(reverse("manage"))
547
    try:
548
        inst.institutiondetails
549 550
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
551 552
    if request.method == "GET":
        # Determine add or edit
Culley Angus's avatar
Culley Angus committed
553
        try:
554 555 556 557
            server = InstServer.objects.get(instid=inst, pk=server_pk)
            form = InstServerForm(instance=server)
        except InstServer.DoesNotExist:
            form = InstServerForm()
558
            if server_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
559 560 561 562 563
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this server'
                )
Culley Angus's avatar
Culley Angus committed
564
                return HttpResponseRedirect(reverse("servers"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
565 566 567 568
        form.fields['instid'] = forms.ModelChoiceField(
            queryset=Institution.objects.filter(pk=inst.pk),
            empty_label=None
        )
569 570
        if server:
            edit = True
Culley Angus's avatar
Culley Angus committed
571

Kroustouris Stauros's avatar
Kroustouris Stauros committed
572 573 574 575 576 577 578 579
        return render_to_response(
            'edumanage/servers_edit.html',
            {
                'form': form,
                'edit': edit
            },
            context_instance=RequestContext(request, base_response(request))
        )
580 581
    elif request.method == 'POST':
        request_data = request.POST.copy()
Culley Angus's avatar
Culley Angus committed
582
        try:
583 584 585 586
            server = InstServer.objects.get(instid=inst, pk=server_pk)
            form = InstServerForm(request_data, instance=server)
        except InstServer.DoesNotExist:
            form = InstServerForm(request_data)
587
            if server_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
588 589 590 591 592
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this server'
                )
Culley Angus's avatar
Culley Angus committed
593 594
                return HttpResponseRedirect(reverse("servers"))

595
        if form.is_valid():
596
            form.save()
597 598
            return HttpResponseRedirect(reverse("servers"))
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
599 600 601 602
            form.fields['instid'] = forms.ModelChoiceField(
                queryset=Institution.objects.filter(pk=inst.pk),
                empty_label=None
            )
603 604
        if server:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
605 606 607 608 609 610 611 612 613
        return render_to_response(
            'edumanage/servers_edit.html',
            {
                'institution': inst,
                'form': form,
                'edit': edit
            },
            context_instance=RequestContext(request, base_response(request))
        )
614

615

616 617 618 619 620 621 622 623 624 625 626 627 628 629
@login_required
@social_active_required
@never_cache
def cat_enroll(request):
    user = request.user
    cat_url = None
    inst_uid = None
    try:
        profile = user.get_profile()
        inst = profile.institution
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
    except UserProfile.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    try:
630
        inst.institutiondetails
631 632
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
633 634 635 636 637 638 639 640 641 642 643
    if inst.ertype not in [1, 3]:
        messages.add_message(
            request,
            messages.ERROR,
            'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP'
        )
        return render_to_response(
            'edumanage/catenroll.html',
            {'status': False},
            context_instance=RequestContext(request, base_response(request))
        )
644 645
    if request.method == "GET":
        current_enrollments = inst.catenrollment_set.all()
Kroustouris Stauros's avatar
Kroustouris Stauros committed
646 647 648 649 650 651 652
        current_enrollments_list = current_enrollments.values_list(
            'cat_instance',
            flat=True
        )
        available_enrollments = [
            (x[0], x[1]) for x in settings.CAT_INSTANCES if x[0] not in current_enrollments_list
        ]
653
        if len(available_enrollments) == 0 and len(current_enrollments_list) == 0:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
654 655 656 657 658 659 660
            messages.add_message(
                request,
                messages.ERROR,
                'There are no available CAT instances for your institution enrollment'
            )
            return render_to_response(
                'edumanage/catenroll.html',
661
                {'status': False},
Kroustouris Stauros's avatar
Kroustouris Stauros committed
662 663 664 665 666 667 668 669 670 671 672
                context_instance=RequestContext(request, base_response(request))
            )
        return render_to_response(
            'edumanage/catenroll.html',
            {
                'status': True,
                'current_enrollments': current_enrollments,
                'cat_instances': available_enrollments
            },
            context_instance=RequestContext(request, base_response(request))
        )
673 674 675
    elif request.method == 'POST':
        request_data = request.POST.copy()
        instance = request_data['catinstance']
676
        # Check if cat enrollment exists. It should not!
677
        if inst.catenrollment_set.filter(cat_instance=instance):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
678 679 680 681 682
            messages.add_message(
                request,
                messages.ERROR,
                'There is already and enrollment for this CAT instance'
            )
683 684 685 686
            return HttpResponseRedirect(reverse("catenroll"))
        try:
            cat_instance = settings.CAT_AUTH[instance]
        except:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
687 688 689 690 691
            messages.add_message(
                request,
                messages.ERROR,
                'Invalid CAT instance'
            )
692 693 694
            return HttpResponseRedirect(reverse("catenroll"))
        cat_api_key = cat_instance['CAT_API_KEY']
        cat_api_url = cat_instance['CAT_API_URL']
695

696
        enroll = CatQuery(cat_api_key, cat_api_url)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
697 698 699 700 701 702
        params = {
            'NEWINST_PRIMARYADMIN': u"%s" % user.email,
            'option[S1]': 'general:instname',
            'value[S1-0]': u"%s" % inst.get_name('en'),
            'value[S1-lang]': 'en'
        }
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
        newinst = enroll.newinst(params)
        cat_url = None
        inst_uid = None
        if newinst:
            # this should be True only for successful postings
            status = enroll.status
            response = enroll.response
            inst_uid = response['inst_unique_id']
            cat_url = response['enrollment_URL']
            catentry = CatEnrollment()
            catentry.cat_inst_id = inst_uid
            catentry.inst = inst
            catentry.url = cat_url
            catentry.applier = user
            catentry.cat_instance = instance
            catentry.save()
            # We should notify the user
        else:
            status = enroll.status
            response = enroll.response
Kroustouris Stauros's avatar
Kroustouris Stauros committed
723 724 725 726 727 728 729 730 731 732 733
        return render_to_response(
            'edumanage/catenroll.html',
            {
                'status': True,
                'response_status': status,
                'response': response,
                'cat_url': cat_url,
                'inst_uid': inst_uid
            },
            context_instance=RequestContext(request, base_response(request))
        )
734 735


736
@login_required
737
@social_active_required
738
@never_cache
739 740 741 742 743
def del_server(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        server_pk = req_data['server_pk']
744
        resp = {}
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
        try:
            profile = user.get_profile()
            institution = profile.institution
        except UserProfile.DoesNotExist:
            resp['error'] = "Could not delete server. Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            server = InstServer.objects.get(instid=institution, pk=server_pk)
        except InstServer.DoesNotExist:
            resp['error'] = "Could not get server or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            server.delete()
        except:
            resp['error'] = "Could not delete server"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Server successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')


765
@login_required
766
@social_active_required
767
@never_cache
768 769 770 771 772 773
def realms(request):
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
774
        return HttpResponseRedirect(reverse("manage"))
775 776
    if inst:
        realms = InstRealm.objects.filter(instid=inst)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
777 778 779 780 781 782 783 784 785 786 787
    if inst.ertype not in [1, 3]:
        messages.add_message(
            request,
            messages.ERROR,
            'Cannot add/edit Realms. Your institution should be either IdP or IdP/SP'
        )
    return render_to_response(
        'edumanage/realms.html',
        {'realms': realms},
        context_instance=RequestContext(request, base_response(request))
    )
788

789

790
@login_required
791
@social_active_required
792
@never_cache
793 794
def add_realm(request, realm_pk):
    user = request.user
795 796
    realm = False
    edit = False
797 798 799
    try:
        profile = user.get_profile()
        inst = profile.institution
800
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
801
    except UserProfile.DoesNotExist:
802
        return HttpResponseRedirect(reverse("manage"))
803
    try:
804
        inst.institutiondetails
805 806
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
807
    if inst.ertype not in [1, 3]:
808
        messages.add_message(request, messages.ERROR, 'Cannot add/edit Realm. Your institution should be either IdP or IdP/SP')
Kroustouris Stauros's avatar
Kroustouris Stauros committed
809 810 811 812 813
        return render_to_response(
            'edumanage/realms_edit.html',
            {'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
814 815 816
    if request.method == "GET":

        # Determine add or edit
Culley Angus's avatar
Culley Angus committed
817
        try:
818 819 820 821
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
            form = InstRealmForm(instance=realm)
        except InstRealm.DoesNotExist:
            form = InstRealmForm()
822
            if realm_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
823 824 825 826 827
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this realm'
                )
828
                return HttpResponseRedirect(reverse("realms"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
829 830 831 832 833 834 835 836 837
        form.fields['instid'] = forms.ModelChoiceField(
            queryset=Institution.objects.filter(pk=inst.pk),
            empty_label=None
        )
        form.fields['proxyto'] = forms.ModelMultipleChoiceField(
            queryset=InstServer.objects.filter(
                pk__in=getInstServers(inst, True)
            )
        )
838 839
        if realm:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
840 841 842 843 844
        return render_to_response(
            'edumanage/realms_edit.html',
            {'form': form, 'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
845 846
    elif request.method == 'POST':
        request_data = request.POST.copy()
Culley Angus's avatar
Culley Angus committed
847
        try:
848 849 850 851
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
            form = InstRealmForm(request_data, instance=realm)
        except InstRealm.DoesNotExist:
            form = InstRealmForm(request_data)
852
            if realm_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
853 854 855 856 857
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this realm'
                )
Culley Angus's avatar
Culley Angus committed
858
                return HttpResponseRedirect(reverse("realms"))
859
        if form.is_valid():
860
            form.save()
861 862
            return HttpResponseRedirect(reverse("realms"))
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
863 864 865 866 867 868 869 870 871
            form.fields['instid'] = forms.ModelChoiceField(
                queryset=Institution.objects.filter(pk=inst.pk),
                empty_label=None
            )
            form.fields['proxyto'] = forms.ModelMultipleChoiceField(
                queryset=InstServer.objects.filter(
                    pk__in=getInstServers(inst, True)
                )
            )
872 873
        if realm:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
874 875 876 877 878
        return render_to_response(
            'edumanage/realms_edit.html',
            {'institution': inst, 'form': form, 'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
879 880 881


@login_required
882
@social_active_required
883
@never_cache
884 885 886 887 888
def del_realm(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        realm_pk = req_data['realm_pk']
889
        resp = {}
890 891 892 893 894 895
        try:
            profile = user.get_profile()
            institution = profile.institution
        except UserProfile.DoesNotExist:
            resp['error'] = "Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
896 897 898 899 900 901 902 903 904 905 906 907 908 909
        try:
            realm = InstRealm.objects.get(instid=institution, pk=realm_pk)
        except InstRealm.DoesNotExist:
            resp['error'] = "Could not get realm or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            realm.delete()
        except:
            resp['error'] = "Could not delete realm"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Realm successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')


910
@login_required
911
@social_active_required
912
@never_cache
913 914 915 916 917 918
def contacts(request):
    user = request.user
    instcontacts = []
    try:
        profile = user.get_profile()
        inst = profile.institution
919
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
920
    except UserProfile.DoesNotExist:
921
        return HttpResponseRedirect(reverse("manage"))
922
    try:
923
        inst.institutiondetails
924 925
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
926
    if inst:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
927 928 929 930 931
        instcontacts.extend([
            x.contact.pk for x in InstitutionContactPool.objects.filter(
                institution=inst
            )
        ])
932
        contacts = Contact.objects.filter(pk__in=instcontacts)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
933 934 935 936 937
    return render_to_response(
        'edumanage/contacts.html',
        {'contacts': contacts},
        context_instance=RequestContext(request, base_response(request))
    )
938

939

940
@login_required
941
@social_active_required
942
@never_cache
943 944
def add_contact(request, contact_pk):
    user = request.user
945 946
    edit = False
    contact = False
947 948 949
    try:
        profile = user.get_profile()
        inst = profile.institution
950
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
951
    except UserProfile.DoesNotExist:
952 953
        return HttpResponseRedirect(reverse("manage"))
    try:
954
        inst.institutiondetails
955
    except InstitutionDetails.DoesNotExist:
956
        return HttpResponseRedirect(reverse("manage"))
957 958 959
    if request.method == "GET":

        # Determine add or edit
Culley Angus's avatar
Culley Angus committed
960
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
961 962 963 964
            contactinst = InstitutionContactPool.objects.get(
                institution=inst,
                contact__pk=contact_pk
            )
965 966 967 968
            contact = contactinst.contact
            form = ContactForm(instance=contact)
        except InstitutionContactPool.DoesNotExist:
            form = ContactForm()
969
            if contact_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
970 971 972 973 974
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this contact'
                )
975
                return HttpResponseRedirect(reverse("contacts"))
976 977
        if contact:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
978 979 980 981 982 983 984 985
        return render_to_response(
            'edumanage/contacts_edit.html',
            {
                'form': form,
                'edit': edit
            },
            context_instance=RequestContext(request, base_response(request))
        )
986 987
    elif request.method == 'POST':
        request_data = request.POST.copy()
Culley Angus's avatar
Culley Angus committed
988
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
989 990 991 992
            contactinst = InstitutionContactPool.objects.get(
                institution=inst,
                contact__pk=contact_pk
            )
993 994 995 996
            contact = contactinst.contact
            form = ContactForm(request_data, instance=contact)
        except InstitutionContactPool.DoesNotExist:
            form = ContactForm(request_data)
997
            if contact_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
998 999 1000 1001 1002
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this contact'
                )
1003
                return HttpResponseRedirect(reverse("contacts"))
Culley Angus's avatar
Culley Angus committed
1004

1005 1006
        if form.is_valid():
            contact = form.save()
1007
            inst_cont_pool, created = InstitutionContactPool.objects.get_or_create(
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1008 1009 1010
                contact=contact,
                institution=inst
            )
1011
            inst_cont_pool.save()
1012
            return HttpResponseRedirect(reverse("contacts"))
1013 1014
        if contact:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1015 1016 1017 1018 1019
        return render_to_response(
            'edumanage/contacts_edit.html',
            {'form': form, "edit": edit},
            context_instance=RequestContext(request, base_response(request))
        )
1020 1021 1022


@login_required
1023
@social_active_required
1024
@never_cache
1025 1026 1027 1028 1029
def del_contact(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        contact_pk = req_data['contact_pk']
1030
        resp = {}
1031 1032 1033 1034 1035 1036
        try:
            profile = user.get_profile()
            institution = profile.institution
        except UserProfile.DoesNotExist:
            resp['error'] = "Could not delete contact. Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
1037
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1038 1039 1040 1041
            contactinst = InstitutionContactPool.objects.get(
                institution=institution,
                contact__pk=contact_pk
            )
1042 1043 1044 1045 1046 1047
            contact = contactinst.contact
        except InstitutionContactPool.DoesNotExist:
            resp['error'] = "Could not get contact or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
            for service in ServiceLoc.objects.filter(institutionid=institution):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
                if (
                    contact in service.contact.all() and
                    len(service.contact.all()) == 1
                ):
                    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")
                    return HttpResponse(
                        json.dumps(resp),
                        mimetype='application/json'
                    )
            if (
                contact in institution.institutiondetails.contact.all() and
                len(institution.institutiondetails.contact.all()) == 1
            ):
                resp['error'] = "Could not delete contact. It is the" \
                    " only contact your institution.<br>Fix it and try again"
                return HttpResponse(
                    json.dumps(resp),
                    mimetype='application/json'
                )
1070 1071 1072 1073 1074 1075
            contact.delete()
        except Exception:
            resp['error'] = "Could not delete contact"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Contact successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')
1076 1077


1078
@login_required
1079
@social_active_required
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
@never_cache
def instrealmmon(request):
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
    except UserProfile.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    try:
1090
        inst.institutiondetails
1091 1092 1093 1094
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    if inst:
        instrealmmons = InstRealmMon.objects.filter(realm__instid=inst)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1095 1096 1097 1098 1099 1100
    return render_to_response(
        'edumanage/instrealmmons.html',
        {'realms': instrealmmons},
        context_instance=RequestContext(request, base_response(request))
    )

1101 1102

@login_required
1103
@social_active_required
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
@never_cache
def add_instrealmmon(request, instrealmmon_pk):
    user = request.user
    instrealmmon = False
    edit = False
    try:
        profile = user.get_profile()
        inst = profile.institution
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
    except UserProfile.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    try:
1116
        inst.institutiondetails
1117 1118 1119 1120
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    if request.method == "GET":
        # Determine add or edit
Culley Angus's avatar
Culley Angus committed
1121
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1122 1123 1124 1125
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=inst
            )
1126 1127 1128
            form = InstRealmMonForm(instance=instrealmmon)
        except InstRealmMon.DoesNotExist:
            form = InstRealmMonForm()
1129
            if instrealmmon_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1130 1131 1132 1133 1134
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm'
                )
1135
                return HttpResponseRedirect(reverse("instrealmmon"))
1136 1137
        if instrealmmon:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        form.fields['realm'] = forms.ModelChoiceField(
            queryset=InstRealm.objects.filter(instid=inst.pk).exclude(
                realm__startswith="*"
            ),
            empty_label=None
        )
        return render_to_response(
            'edumanage/instrealmmon_edit.html',
            {'form': form, 'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
1149 1150
    elif request.method == 'POST':
        request_data = request.POST.copy()
Culley Angus's avatar
Culley Angus committed
1151
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1152 1153 1154 1155
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=inst
            )
1156 1157 1158
            form = InstRealmMonForm(request_data, instance=instrealmmon)
        except InstRealmMon.DoesNotExist:
            form = InstRealmMonForm(request_data)
1159
            if instrealmmon_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1160 1161 1162 1163 1164
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm'
                )
1165
                return HttpResponseRedirect(reverse("instrealmmon"))
1166
        if form.is_valid():
1167
            form.save()
1168 1169 1170
            return HttpResponseRedirect(reverse("instrealmmon"))
        if instrealmmon:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        form.fields['realm'] = forms.ModelChoiceField(
            queryset=InstRealm.objects.filter(instid=inst.pk).exclude(
                realm__startswith="*"
            ),
            empty_label=None
        )
        return render_to_response(
            'edumanage/instrealmmon_edit.html',
            {'form': form, "edit": edit},
            context_instance=RequestContext(request, base_response(request))
        )

1183

1184
@login_required
1185
@social_active_required
1186 1187 1188 1189 1190 1191
@never_cache
def del_instrealmmon(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        instrealmmon_pk = req_data['instrealmmon_pk']
1192
        resp = {}
1193 1194 1195 1196 1197 1198 1199
        try:
            profile = user.get_profile()
            institution = profile.institution
        except UserProfile.DoesNotExist:
            resp['error'] = "Could not delete monitored realm. Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try: