views.py 81.5 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

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

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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
58
from registration.models import RegistrationProfile
59
from edumanage.decorators import social_active_required
60
from utils.cat_helper import CatQuery
61

Kroustouris Stauros's avatar
Kroustouris Stauros committed
62

63
@never_cache
64
def index(request):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
65 66
    return render(
        request,
Kroustouris Stauros's avatar
Kroustouris Stauros committed
67 68 69
        'front/index.html',
    )

70

71 72 73 74 75 76
@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
77 78 79 80
        return render_to_response(
            'edumanage/welcome_manage.html',
            context_instance=RequestContext(request, base_response(request))
        )
81
    except AttributeError:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
82 83
        return render(
            request,
Kroustouris Stauros's avatar
Kroustouris Stauros committed
84
            'edumanage/welcome_manage.html',
Kroustouris Stauros's avatar
Kroustouris Stauros committed
85
            {}
Kroustouris Stauros's avatar
Kroustouris Stauros committed
86
        )
87 88 89
    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
90 91
        return render(
            request,
Kroustouris Stauros's avatar
Kroustouris Stauros committed
92
            'edumanage/welcome_manage.html',
Kroustouris Stauros's avatar
Kroustouris Stauros committed
93
            {}
Kroustouris Stauros's avatar
Kroustouris Stauros committed
94 95
        )

96

97
@login_required
98
@social_active_required
99
@never_cache
100 101 102
def manage(request):
    services_list = []
    servers_list = []
103 104 105 106 107
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
108 109 110 111
        return render_to_response(
            'edumanage/welcome.html',
            context_instance=RequestContext(request, base_response(request))
        )
112 113 114 115
    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
116 117 118 119 120 121 122 123 124 125
    return render_to_response(
        'edumanage/welcome.html',
        {
            'institution': inst,
            'services': services_list,
            'servers': servers_list,
        },
        context_instance=RequestContext(request, base_response(request))
    )

126 127

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


@login_required
153
@social_active_required
154
@never_cache
155 156
def add_institution_details(request, institution_pk):
    user = request.user
157 158 159
    try:
        profile = user.get_profile()
        inst = profile.institution
160
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
161
    except UserProfile.DoesNotExist:
162
        return HttpResponseRedirect(reverse("manage"))
163

164
    if institution_pk and int(inst.pk) != int(institution_pk):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
165 166 167 168 169
        messages.add_message(
            request,
            messages.ERROR,
            'You have no rights on this Institution'
        )
170
        return HttpResponseRedirect(reverse("institutions"))
171

172
    if request.method == "GET":
173
        try:
174 175
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(instance=inst_details)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
176 177 178 179 180 181 182
            UrlFormSet = generic_inlineformset_factory(
                URL_i18n,
                extra=2,
                formset=UrlFormSetFactInst,
                can_delete=True
            )
            urls_form = UrlFormSet(prefix='urlsform', instance=inst_details)
183 184
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm()
Kroustouris Stauros's avatar
Kroustouris Stauros committed
185 186 187 188 189 190 191 192 193
            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
            )
194
            urls_form = UrlFormSet(prefix='urlsform')
195

Kroustouris Stauros's avatar
Kroustouris Stauros committed
196 197 198 199 200 201 202 203
        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))
        )
204 205
    elif request.method == 'POST':
        request_data = request.POST.copy()
206
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFactInst, can_delete=True)
207
        try:
208 209
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(request_data, instance=inst_details)
210
            urls_form = UrlFormSet(request_data, instance=inst_details, prefix='urlsform')
211 212
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm(request_data)
213 214 215
            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():
216
            instdets = form.save()
217
            urls_form.instance = instdets
Kroustouris Stauros's avatar
Kroustouris Stauros committed
218
            urls_form.save()
219
            return HttpResponseRedirect(reverse("institutions"))
220
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234
            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)
                )
            )
235

236 237

@login_required
238
@social_active_required
239
@never_cache
240
def services(request, service_pk):
241 242 243 244
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
245
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
246
    except UserProfile.DoesNotExist:
247
        return HttpResponseRedirect(reverse("manage"))
248
    try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
249
        inst.institutiondetails
250 251
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
252 253 254 255 256 257 258 259 260 261 262
    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))
        )
263
    try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
264
        services = ServiceLoc.objects.filter(institutionid=inst)
265
    except ServiceLoc.DoesNotExist:
266 267
        services = False

268
    if service_pk:
269 270 271
        try:
            services = services.get(pk=service_pk)
        except:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
272 273 274 275 276
            messages.add_message(
                request,
                messages.ERROR,
                'You have no rights to view this location'
            )
277
            return HttpResponseRedirect(reverse("services"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        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))
    )
295 296 297


@login_required
298
@social_active_required
299
@never_cache
300 301
def add_services(request, service_pk):
    user = request.user
302
    service = False
303
    edit = False
304 305 306
    try:
        profile = user.get_profile()
        inst = profile.institution
307
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
308
    except UserProfile.DoesNotExist:
309
        return HttpResponseRedirect(reverse("manage"))
310
    try:
311
        inst.institutiondetails
312 313
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
314 315 316 317 318 319 320 321 322 323 324
    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))
        )
325 326 327
    if request.method == "GET":

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

461

462
@login_required
463
@social_active_required
464
@never_cache
465 466
def del_service(request):
    if request.method == 'GET':
467
        user = request.user
468 469
        req_data = request.GET.copy()
        service_pk = req_data['service_pk']
470
        resp = {}
471 472
        try:
            profile = user.get_profile()
473
            institution = profile.institution
474
        except UserProfile.DoesNotExist:
475 476 477
            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
478 479 480 481
            service = ServiceLoc.objects.get(
                institutionid=institution,
                pk=service_pk
            )
482 483 484 485 486 487 488 489 490 491
        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')
492

493

494
@login_required
495
@social_active_required
496
@never_cache
497
def servers(request, server_pk):
498 499 500 501 502 503 504
    user = request.user
    servers = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
505
        return HttpResponseRedirect(reverse("manage"))
506 507
    if inst:
        servers = InstServer.objects.filter(instid=inst)
508 509
    if server_pk:
        servers = servers.get(pk=server_pk)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        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))
    )
525

526

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

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

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

608

609 610 611 612 613 614 615 616 617 618 619 620 621 622
@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:
623
        inst.institutiondetails
624 625
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
626 627 628 629 630 631 632 633 634 635 636
    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))
        )
637 638
    if request.method == "GET":
        current_enrollments = inst.catenrollment_set.all()
Kroustouris Stauros's avatar
Kroustouris Stauros committed
639 640 641 642 643 644 645
        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
        ]
646
        if len(available_enrollments) == 0:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
            messages.add_message(
                request,
                messages.ERROR,
                'There are no available CAT instances for your institution enrollment'
            )
            return render_to_response(
                'edumanage/catenroll.html',
                {'status': False, 'cat_instances': available_enrollments},
                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))
        )
666 667 668
    elif request.method == 'POST':
        request_data = request.POST.copy()
        instance = request_data['catinstance']
669
        # Check if cat enrollment exists. It should not!
670
        if inst.catenrollment_set.filter(cat_instance=instance):
Kroustouris Stauros's avatar
Kroustouris Stauros committed
671 672 673 674 675
            messages.add_message(
                request,
                messages.ERROR,
                'There is already and enrollment for this CAT instance'
            )
676 677 678 679
            return HttpResponseRedirect(reverse("catenroll"))
        try:
            cat_instance = settings.CAT_AUTH[instance]
        except:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
680 681 682 683 684
            messages.add_message(
                request,
                messages.ERROR,
                'Invalid CAT instance'
            )
685 686 687
            return HttpResponseRedirect(reverse("catenroll"))
        cat_api_key = cat_instance['CAT_API_KEY']
        cat_api_url = cat_instance['CAT_API_URL']
688

689
        enroll = CatQuery(cat_api_key, cat_api_url)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
690 691 692 693 694 695
        params = {
            'NEWINST_PRIMARYADMIN': u"%s" % user.email,
            'option[S1]': 'general:instname',
            'value[S1-0]': u"%s" % inst.get_name('en'),
            'value[S1-lang]': 'en'
        }
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        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
716 717 718 719 720 721 722 723 724 725 726
        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))
        )
727 728


729
@login_required
730
@social_active_required
731
@never_cache
732 733 734 735 736
def del_server(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        server_pk = req_data['server_pk']
737
        resp = {}
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
        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')


758
@login_required
759
@social_active_required
760
@never_cache
761 762 763 764 765 766
def realms(request):
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
767
        return HttpResponseRedirect(reverse("manage"))
768 769
    if inst:
        realms = InstRealm.objects.filter(instid=inst)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
770 771 772 773 774 775 776 777 778 779 780
    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))
    )
781

782

783
@login_required
784
@social_active_required
785
@never_cache
786 787
def add_realm(request, realm_pk):
    user = request.user
788 789
    realm = False
    edit = False
790 791 792
    try:
        profile = user.get_profile()
        inst = profile.institution
793
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
794
    except UserProfile.DoesNotExist:
795
        return HttpResponseRedirect(reverse("manage"))
796
    try:
797
        inst.institutiondetails
798 799
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
800
    if inst.ertype not in [1, 3]:
801
        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
802 803 804 805 806
        return render_to_response(
            'edumanage/realms_edit.html',
            {'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
807 808 809
    if request.method == "GET":

        # Determine add or edit
810
        try:
811 812 813 814
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
            form = InstRealmForm(instance=realm)
        except InstRealm.DoesNotExist:
            form = InstRealmForm()
815
            if realm_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
816 817 818 819 820
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this realm'
                )
821
                return HttpResponseRedirect(reverse("realms"))
Kroustouris Stauros's avatar
Kroustouris Stauros committed
822 823 824 825 826 827 828 829 830
        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)
            )
        )
831 832
        if realm:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
833 834 835 836 837
        return render_to_response(
            'edumanage/realms_edit.html',
            {'form': form, 'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
838 839
    elif request.method == 'POST':
        request_data = request.POST.copy()
840
        try:
841 842 843 844
            realm = InstRealm.objects.get(instid=inst, pk=realm_pk)
            form = InstRealmForm(request_data, instance=realm)
        except InstRealm.DoesNotExist:
            form = InstRealmForm(request_data)
845
            if realm_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
846 847 848 849 850
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this realm'
                )
851
                return HttpResponseRedirect(reverse("realms"))
852
        if form.is_valid():
853
            form.save()
854 855
            return HttpResponseRedirect(reverse("realms"))
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
856 857 858 859 860 861 862 863 864
            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)
                )
            )
865 866
        if realm:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
867 868 869 870 871
        return render_to_response(
            'edumanage/realms_edit.html',
            {'institution': inst, 'form': form, 'edit': edit},
            context_instance=RequestContext(request, base_response(request))
        )
872 873 874


@login_required
875
@social_active_required
876
@never_cache
877 878 879 880 881
def del_realm(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        realm_pk = req_data['realm_pk']
882
        resp = {}
883 884 885 886 887 888
        try:
            profile = user.get_profile()
            institution = profile.institution
        except UserProfile.DoesNotExist:
            resp['error'] = "Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
889 890 891 892 893 894 895 896 897 898 899 900 901 902
        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')


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

932

933
@login_required
934
@social_active_required
935
@never_cache
936 937
def add_contact(request, contact_pk):
    user = request.user
938 939
    edit = False
    contact = False
940 941 942
    try:
        profile = user.get_profile()
        inst = profile.institution
943
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
944
    except UserProfile.DoesNotExist:
945 946
        return HttpResponseRedirect(reverse("manage"))
    try:
947
        inst.institutiondetails
948
    except InstitutionDetails.DoesNotExist:
949
        return HttpResponseRedirect(reverse("manage"))
950 951 952
    if request.method == "GET":

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

998 999
        if form.is_valid():
            contact = form.save()
1000
            inst_cont_pool, created = InstitutionContactPool.objects.get_or_create(
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1001 1002 1003
                contact=contact,
                institution=inst
            )
1004
            inst_cont_pool.save()
1005
            return HttpResponseRedirect(reverse("contacts"))
1006 1007
        if contact:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1008 1009 1010 1011 1012
        return render_to_response(
            'edumanage/contacts_edit.html',
            {'form': form, "edit": edit},
            context_instance=RequestContext(request, base_response(request))
        )
1013 1014 1015


@login_required
1016
@social_active_required
1017
@never_cache
1018 1019 1020 1021 1022
def del_contact(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        contact_pk = req_data['contact_pk']
1023
        resp = {}
1024 1025 1026 1027 1028 1029
        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')
1030
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1031 1032 1033 1034
            contactinst = InstitutionContactPool.objects.get(
                institution=institution,
                contact__pk=contact_pk
            )
1035 1036 1037 1038 1039 1040
            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
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
                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'
                )
1063 1064 1065 1066 1067 1068
            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')
1069 1070


1071
@login_required
1072
@social_active_required
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
@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:
1083
        inst.institutiondetails
1084 1085 1086 1087
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    if inst:
        instrealmmons = InstRealmMon.objects.filter(realm__instid=inst)
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1088 1089 1090 1091 1092 1093
    return render_to_response(
        'edumanage/instrealmmons.html',
        {'realms': instrealmmons},
        context_instance=RequestContext(request, base_response(request))
    )

1094 1095

@login_required
1096
@social_active_required
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
@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:
1109
        inst.institutiondetails
1110 1111 1112 1113
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    if request.method == "GET":
        # Determine add or edit
1114
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1115 1116 1117 1118
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=inst
            )
1119 1120 1121
            form = InstRealmMonForm(instance=instrealmmon)
        except InstRealmMon.DoesNotExist:
            form = InstRealmMonForm()
1122
            if instrealmmon_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1123 1124 1125 1126 1127
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm'
                )
1128
                return HttpResponseRedirect(reverse("instrealmmon"))
1129 1130
        if instrealmmon:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        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))
        )
1142 1143
    elif request.method == 'POST':
        request_data = request.POST.copy()
1144
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1145 1146 1147 1148
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=inst
            )
1149 1150 1151
            form = InstRealmMonForm(request_data, instance=instrealmmon)
        except InstRealmMon.DoesNotExist:
            form = InstRealmMonForm(request_data)
1152
            if instrealmmon_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1153 1154 1155 1156 1157
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm'
                )
1158
                return HttpResponseRedirect(reverse("instrealmmon"))
1159
        if form.is_valid():
1160
            form.save()
1161 1162 1163
            return HttpResponseRedirect(reverse("instrealmmon"))
        if instrealmmon:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
        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))
        )

1176

1177
@login_required
1178
@social_active_required
1179 1180 1181 1182 1183 1184
@never_cache
def del_instrealmmon(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        instrealmmon_pk = req_data['instrealmmon_pk']
1185
        resp = {}
1186 1187 1188 1189 1190 1191 1192
        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:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1193 1194 1195 1196
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=institution
            )
1197 1198 1199 1200 1201 1202
            instrealmmon.delete()
        except InstRealmMon.DoesNotExist:
            resp['error'] = "Could not get monitored realm or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Contact successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')
1203

Kroustouris Stauros's avatar
Kroustouris Stauros committed
1204

1205
@login_required
1206
@social_active_required
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
@never_cache
def add_monlocauthpar(request, instrealmmon_pk, monlocauthpar_pk):
    user = request.user
    monlocauthpar = 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:
1219
        inst.institutiondetails
1220 1221 1222 1223 1224
    except InstitutionDetails.DoesNotExist:
        return HttpResponseRedirect(reverse("manage"))
    if request.method == "GET":
        # Determine add or edit
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1225 1226 1227 1228 1229 1230 1231 1232
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=inst
            )
            monlocauthpar = MonLocalAuthnParam.objects.get(
                pk=monlocauthpar_pk,
                instrealmmonid__realm__instid=inst
            )
1233 1234 1235
            form = MonLocalAuthnParamForm(instance=monlocauthpar)
        except MonLocalAuthnParam.DoesNotExist:
            form = MonLocalAuthnParamForm()
1236
            if monlocauthpar_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1237 1238 1239 1240 1241
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm Parameters'
                )
1242
                return HttpResponseRedirect(reverse("instrealmmon"))
1243
        except InstRealmMon.DoesNotExist:
1244
            if instrealmmon_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1245 1246 1247 1248 1249
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm Parameters'
                )
1250
            return HttpResponseRedirect(reverse("instrealmmon"))
1251 1252
        if monlocauthpar:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1253 1254 1255 1256 1257 1258 1259 1260 1261
        form.fields['instrealmmonid'] = forms.ModelChoiceField(
            queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk),
            empty_label=None
        )
        return render_to_response(
            'edumanage/monlocauthpar_edit.html',
            {'form': form,"edit" : edit, "realm":instrealmmon},
            context_instance=RequestContext(request, base_response(request))
        )
1262 1263
    elif request.method == 'POST':
        request_data = request.POST.copy()
1264
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1265 1266 1267 1268 1269 1270 1271 1272
            instrealmmon = InstRealmMon.objects.get(
                pk=instrealmmon_pk,
                realm__instid=inst
            )
            monlocauthpar = MonLocalAuthnParam.objects.get(
                pk=monlocauthpar_pk,
                instrealmmonid__realm__instid=inst
            )
1273 1274 1275
            form = MonLocalAuthnParamForm(request_data, instance=monlocauthpar)
        except MonLocalAuthnParam.DoesNotExist:
            form = MonLocalAuthnParamForm(request_data)
1276
            if monlocauthpar_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1277 1278 1279 1280 1281
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm Parameters'
                )
1282
                return HttpResponseRedirect(reverse("instrealmmon"))
1283
        except InstRealmMon.DoesNotExist:
1284
            if instrealmmon_pk:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1285 1286 1287 1288 1289
                messages.add_message(
                    request,
                    messages.ERROR,
                    'You have no rights to edit this Monitoring Realm Parameters'
                )
1290
            return HttpResponseRedirect(reverse("instrealmmon"))
1291
        if form.is_valid():
1292
            form.save()
1293 1294 1295
            return HttpResponseRedirect(reverse("instrealmmon"))
        if monlocauthpar:
            edit = True
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
        form.fields['instrealmmonid'] = forms.ModelChoiceField(
            queryset=InstRealmMon.objects.filter(pk=instrealmmon.pk),
            empty_label=None
        )
        return render_to_response(
            'edumanage/monlocauthpar_edit.html',
            {'form': form, "edit": edit, "realm":instrealmmon},
            context_instance=RequestContext(request, base_response(request))
        )

1306

1307
@login_required
1308
@social_active_required
1309 1310 1311 1312 1313 1314
@never_cache
def del_monlocauthpar(request):
    if request.method == 'GET':
        user = request.user
        req_data = request.GET.copy()
        monlocauthpar_pk = req_data['monlocauthpar_pk']
1315
        resp = {}
1316 1317 1318 1319 1320 1321 1322
        try:
            profile = user.get_profile()
            institution = profile.institution
        except UserProfile.DoesNotExist:
            resp['error'] = "Could not delete realm monitoring parameters. Not enough rights"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        try:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1323 1324 1325 1326
            monlocauthpar = MonLocalAuthnParam.objects.get(
                pk=monlocauthpar_pk,
                instrealmmonid__realm__instid=institution
            )
1327 1328 1329 1330 1331 1332 1333
            monlocauthpar.delete()
        except MonLocalAuthnParam.DoesNotExist:
            resp['error'] = "Could not get realm monitoring parameters or you have no rights to delete"
            return HttpResponse(json.dumps(resp), mimetype='application/json')
        resp['success'] = "Contact successfully deleted"
        return HttpResponse(json.dumps(resp), mimetype='application/json')

Kroustouris Stauros's avatar
Kroustouris Stauros committed
1334

1335
@login_required
1336
@social_active_required
1337
@never_cache
1338 1339 1340 1341 1342 1343 1344 1345
def adduser(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"))
1346

1347 1348
    if request.method == "GET":
        form = ContactForm()
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1349 1350 1351 1352 1353
        return render_to_response(
            'edumanage/add_user.html',
            {'form': form},
            context_instance=RequestContext(request, base_response(request))
        )
1354 1355 1356 1357 1358
    elif request.method == 'POST':
        request_data = request.POST.copy()
        form = ContactForm(request_data)
        if form.is_valid():
            contact = form.save()
1359
            inst_cont_pool = InstitutionContactPool(
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1360 1361 1362
                contact=contact,
                institution=inst
            )
1363
            inst_cont_pool.save()
1364
            response_data = {}
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1365 1366 1367 1368 1369 1370
            response_data['value'] = "%s" % contact.pk
            response_data['text'] = "%s" % contact
            return HttpResponse(
                json.dumps(response_data),
                mimetype='application/json'
            )
1371
        else:
Kroustouris Stauros's avatar
Kroustouris Stauros committed
1372 1373 1374 1375 1376 1377 1378 1379
            return render_to_response(
                'edumanage/add_user.html',
                {'form': form},
                context_instance=RequestContext(
                    request,
                    base_response(request)
                )
            )