Commit 1a53a4d7 authored by Kroustouris Stauros's avatar Kroustouris Stauros

add packages from pip and clean lint errors

parent 05544abb
from django.contrib import admin
from accounts.models import *
from django.contrib.auth.models import User
from django.conf import settings
from edumanage.models import *
from accounts.models import UserProfile
class UserPrAdmin(admin.ModelAdmin):
list_display = ('user', 'institution')
admin.site.register(UserProfile, UserPrAdmin)
\ No newline at end of file
admin.site.register(UserProfile, UserPrAdmin)
from django.db import models
from django.contrib.auth.models import User
from edumanage.models import *
from edumanage.models import Institution
class UserProfile(models.Model):
user = models.OneToOneField(User)
institution = models.ForeignKey(Institution)
is_social_active = models.BooleanField(default=False)
class Meta:
permissions = (
("overview", "Can see registered user and respective institutions"),
)
def __unicode__(self):
return "%s:%s" %(self.user.username, self.institution)
permissions = (
("overview", "Can see registered user and respective institutions"),
)
def __unicode__(self):
return "%s:%s" % (self.user.username, self.institution)
import logging
from django.conf import settings
from django.core.mail import send_mail
from django.contrib.sites.models import Site
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.views.decorators.cache import never_cache
from django import forms
from registration.models import RegistrationProfile
from accounts.models import *
from edumanage.forms import *
import logging
import os
from accounts.models import UserProfile
from edumanage.forms import UserProfileForm
from edumanage.models import Institution
logger = logging.getLogger(__name__)
from django.views.decorators.cache import never_cache
@never_cache
def activate(request, activation_key):
account = None
if request.method == "GET":
activation_key = activation_key.lower() # Normalize before trying anything with it.
context = RequestContext(request)
# Normalize before trying anything with it.
activation_key = activation_key.lower()
try:
rp = RegistrationProfile.objects.get(activation_key=activation_key)
except RegistrationProfile.DoesNotExist:
return render_to_response("registration/activate.html",
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
return render(
request,
'registration/activate.html',
{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
}
)
try:
userProfile = rp.user.get_profile()
user_profile = rp.user.get_profile()
except UserProfile.DoesNotExist:
return render_to_response("registration/activate.html",
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
form = UserProfileForm(instance=userProfile)
form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=rp.user.pk), empty_label=None)
form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
return render_to_response("registration/activate_edit.html",
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'form': form },
context_instance=context)
return render(
request,
'registration/activate.html',
{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
}
)
form = UserProfileForm(instance=user_profile)
form.fields['user'] = forms.ModelChoiceField(
queryset=User.objects.filter(pk=rp.user.pk), empty_label=None
)
form.fields['institution'] = forms.ModelChoiceField(
queryset=Institution.objects.all(), empty_label=None
)
return render(
request,
'registration/activate_edit.html',
{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'form': form
}
)
if request.method == "POST":
context = RequestContext(request)
request_data = request.POST.copy()
try:
user = User.objects.get(pk=request_data['user'])
up = user.get_profile()
up.institution = Institution.objects.get(pk=request_data['institution'])
up.institution = Institution.objects.get(
pk=request_data['institution']
)
up.save()
except:
return render_to_response("registration/activate_edit.html",
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
},
context_instance=context)
activation_key = activation_key.lower() # Normalize before trying anything with it.
return render(
request,
'registration/activate_edit.html',
{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
}
)
# Normalize before trying anything with it.
activation_key = activation_key.lower()
try:
rp = RegistrationProfile.objects.get(activation_key=activation_key)
account = RegistrationProfile.objects.activate_user(activation_key)
up.is_social_active = True
up.save()
logger.info("Activating user %s" %rp.user.username)
logger.info('Activating user %s' % rp.user.username)
except Exception as e:
logger.info("An error occured: %s" %e)
logger.info('An error occured: %s' % e)
pass
if account:
# A user has been activated
email = render_to_string("registration/activation_complete.txt",
{"site": Site.objects.get_current(),
"user": account})
send_mail(_("%sUser account activated") % settings.EMAIL_SUBJECT_PREFIX,
email, settings.SERVER_EMAIL, account.email.split(';'))
context = RequestContext(request)
return render_to_response("registration/activate.html",
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
email = render_to_string(
'registration/activation_complete.txt',
{
'site': Site.objects.get_current(),
'user': account
}
)
send_mail(
_('%sUser account activated') % settings.EMAIL_SUBJECT_PREFIX,
email,
settings.SERVER_EMAIL,
account.email.split(';')
)
return render(
request,
'registration/activate.html',
{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
}
)
# -*- coding: utf-8 -*-.
from django.contrib import admin
from edumanage.models import *
from edumanage.models import (
Name_i18n,
URL_i18n,
Contact,
InstitutionContactPool,
InstRealm,
InstServer,
InstRealmMon,
MonProxybackClient,
MonLocalAuthnParam,
ServiceLoc,
Institution,
InstitutionDetails,
Realm,
RealmData,
CatEnrollment
)
from django.contrib.contenttypes import generic
class NameInline(generic.GenericTabularInline):
model = Name_i18n
class UrlInline(generic.GenericTabularInline):
model = URL_i18n
class InstitutionAdmin(admin.ModelAdmin):
inlines = [
NameInline,
NameInline,
]
class InstitutionDetailsAdmin(admin.ModelAdmin):
inlines = [
UrlInline,
]
class ServiceLocAdmin(admin.ModelAdmin):
list_display = ('get_name', 'institutionid')
inlines = [
NameInline,
]
class RealmInLine(admin.ModelAdmin):
inlines = [
UrlInline, NameInline
]
class InstRealmAdmin(admin.ModelAdmin):
list_display = ('realm', 'instid')
class CatEnrollmentAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'cat_active')
......@@ -73,4 +95,4 @@ class TinyMCEFlatPageAdmin(FlatPageAdmin):
from django.contrib import admin
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, TinyMCEFlatPageAdmin)
\ No newline at end of file
admin.site.register(FlatPage, TinyMCEFlatPageAdmin)
from django.conf import settings
def country_code(context):
# return the value you want as a dictionnary. you may add multiple values in there.
return {
'COUNTRY_NAME': settings.NRO_COUNTRY_NAME,
'COUNTRY_CODE': settings.NRO_COUNTRY_CODE,
'DOMAIN_MAIN_URL': settings.NRO_DOMAIN_MAIN_URL,
'DOMAIN_HELPDESK_DICT': settings.NRO_DOMAIN_HELPDESK_DICT,
'MAP_CENTER': settings.MAP_CENTER,
'PROV_TEAM': settings.NRO_PROV_BY_DICT,
'SOCIAL_MEDIA_LIST': settings.NRO_PROV_SOCIAL_MEDIA_CONTACT,
'VERSION': settings.SW_VERSION
}
'COUNTRY_NAME': settings.NRO_COUNTRY_NAME,
'COUNTRY_CODE': settings.NRO_COUNTRY_CODE,
'DOMAIN_MAIN_URL': settings.NRO_DOMAIN_MAIN_URL,
'DOMAIN_HELPDESK_DICT': settings.NRO_DOMAIN_HELPDESK_DICT,
'MAP_CENTER': settings.MAP_CENTER,
'PROV_TEAM': settings.NRO_PROV_BY_DICT,
'SOCIAL_MEDIA_LIST': settings.NRO_PROV_SOCIAL_MEDIA_CONTACT,
'VERSION': settings.SW_VERSION
}
def cat_instances(context):
......
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django import forms
from accounts.models import *
from edumanage.forms import *
from edumanage.models import *
from accounts.models import UserProfile
from edumanage.forms import UserProfileForm
from edumanage.models import Institution
def social_active_required(function):
def wrap(request, *args, **kw):
user=request.user
user = request.user
try:
profile = request.user.get_profile()
if profile.is_social_active == True:
if profile.is_social_active is True:
return function(request, *args, **kw)
else:
status = _("User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk") %user.username
return render_to_response('status.html', {'status': status, 'inactive': True},
context_instance=RequestContext(request))
return render(
request,
'status.html',
{
'status': status,
'inactive': True
},
)
except UserProfile.DoesNotExist:
form = UserProfileForm()
form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=user.pk), empty_label=None)
form.fields['user'] = forms.ModelChoiceField(
queryset=User.objects.filter(pk=user.pk), empty_label=None
)
nomail = False
if not user.email:
nomail = True
form.fields['email'] = forms.CharField()
else:
form.fields['email'] = forms.CharField(initial = user.email)
form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label=None)
return render_to_response('registration/select_institution.html', {'form': form, 'nomail': nomail}, context_instance=RequestContext(request))
return wrap
\ No newline at end of file
form.fields['email'] = forms.CharField(initial=user.email)
form.fields['institution'] = forms.ModelChoiceField(
queryset=Institution.objects.all(),
empty_label=None
)
return render(
request,
'registration/select_institution.html',
{
'form': form,
'nomail': nomail
}
)
return wrap
from django import forms
from django.core.validators import email_re
class MultipleEmailsField(forms.Field):
def clean(self, value):
"""
......@@ -15,4 +16,4 @@ class MultipleEmailsField(forms.Field):
raise forms.ValidationError('%s is not a valid e-mail address.' % email)
# Always return the cleaned data.
return ';'.join(emails)
\ No newline at end of file
return ';'.join(emails)
from django import forms
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from edumanage.models import *
from accounts.models import *
from django.conf import settings
from edumanage.models import (
MonLocalAuthnParam,
InstRealmMon,
InstitutionDetails,
InstServer,
Contact,
InstRealm,
ServiceLoc
)
from accounts.models import UserProfile
from edumanage.fields import MultipleEmailsField
from django.contrib.contenttypes.generic import BaseGenericInlineFormSet
import ipaddr
import pprint
import re
FQDN_RE = r'(^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$)'
......@@ -17,31 +21,34 @@ DN_RE = r'(^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)([A-Za-z]|[A-Za-z][A
class MonLocalAuthnParamForm(forms.ModelForm):
class Meta:
model = MonLocalAuthnParam
class InstRealmMonForm(forms.ModelForm):
class Meta:
model = InstRealmMon
class UserProfileForm(forms.ModelForm):
email = MultipleEmailsField(required=True)
class Meta:
model = UserProfile
class InstDetailsForm(forms.ModelForm):
class Meta:
model = InstitutionDetails
def clean_oper_name(self):
oper_name = self.cleaned_data['oper_name']
institution = self.cleaned_data['institution']
if institution.ertype in [2,3]:
if institution.ertype in [2, 3]:
if oper_name:
match = re.match(FQDN_RE, oper_name)
if not match:
......@@ -50,11 +57,12 @@ class InstDetailsForm(forms.ModelForm):
else:
raise forms.ValidationError('This field is required.')
class InstServerForm(forms.ModelForm):
class Meta:
model = InstServer
def clean_ertype(self):
ertype = self.cleaned_data['ertype']
institution = self.cleaned_data['instid']
......@@ -68,7 +76,7 @@ class InstServerForm(forms.ModelForm):
return self.cleaned_data["ertype"]
else:
raise forms.ValidationError('This field is required.')
def clean_auth_port(self):
auth_port = self.cleaned_data['auth_port']
institution = self.cleaned_data['instid']
......@@ -77,7 +85,7 @@ class InstServerForm(forms.ModelForm):
return self.cleaned_data["auth_port"]
else:
raise forms.ValidationError(_('This field is required.'))
def clean_acct_port(self):
acct_port = self.cleaned_data['acct_port']
institution = self.cleaned_data['instid']
......@@ -86,7 +94,7 @@ class InstServerForm(forms.ModelForm):
return self.cleaned_data["acct_port"]
else:
raise forms.ValidationError(_('This field is required.'))
def clean_rad_pkt_type(self):
rad_pkt_type = self.cleaned_data['rad_pkt_type']
institution = self.cleaned_data['instid']
......@@ -95,7 +103,7 @@ class InstServerForm(forms.ModelForm):
return self.cleaned_data["rad_pkt_type"]
else:
raise forms.ValidationError(_('This field is required.'))
def clean_host(self):
host = self.cleaned_data['host']
addr_type = self.cleaned_data['addr_type']
......@@ -115,18 +123,19 @@ class InstServerForm(forms.ModelForm):
else:
raise forms.ValidationError(_('This field is required.'))
return self.cleaned_data["host"]
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
class InstRealmForm(forms.ModelForm):
class Meta:
model = InstRealm
def clean_proxyto(self):
proxied_servers = self.cleaned_data['proxyto']
if proxied_servers:
......@@ -138,28 +147,25 @@ class InstRealmForm(forms.ModelForm):
raise forms.ValidationError(_('This field is required.'))
return self.cleaned_data["proxyto"]
class ServiceLocForm(forms.ModelForm):
class Meta:
model = ServiceLoc
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
class NameFormSetFact(BaseGenericInlineFormSet):
def clean(self):
if any(self.errors):
return
langs = []
emptyForms = True
empty_forms = True
for i in range(0, self.total_form_count()):
form = self.forms[i]
if len(form.cleaned_data) != 0:
emptyForms = False
empty_forms = False
langs.append(form.cleaned_data.get('lang', None))
if emptyForms:
if empty_forms:
raise forms.ValidationError, _("Fill in at least one location name in English")
if "en" not in langs:
raise forms.ValidationError, _("Fill in at least one location name in English")
......@@ -174,21 +180,20 @@ class UrlFormSetFact(BaseGenericInlineFormSet):
if len(form.cleaned_data) == 0:
pass
return
class UrlFormSetFactInst(BaseGenericInlineFormSet):
def clean(self):
if any(self.errors):
return
url_types = []
emptyForms = True
empty_forms = True
for i in range(0, self.total_form_count()):
form = self.forms[i]
if len(form.cleaned_data) != 0:
emptyForms = False
url_types.append(form.cleaned_data.get('urltype',None))
if emptyForms:
empty_forms = False
url_types.append(form.cleaned_data.get('urltype', None))
if empty_forms:
raise forms.ValidationError, _("Fill in at least the info url")
if "info" not in url_types:
raise forms.ValidationError, _("Fill in at least the info url")
......@@ -4,10 +4,11 @@ import warnings
warnings.simplefilter("ignore", DeprecationWarning)
warnings.simplefilter("ignore", FutureWarning)
from django.core.management.base import BaseCommand, CommandError
from django.core.management.base import BaseCommand
from django.conf import settings
from utils.cat_helper import *
from edumanage.models import CatEnrollment
from utils.cat_helper import CatQuery
from edumanage.models import CatEnrollment
class Command(BaseCommand):
args = ''
......@@ -21,11 +22,11 @@ class Command(BaseCommand):
cat_api_key = cat_instance['CAT_API_KEY']
cat_api_url = cat_instance['CAT_API_URL']
inst_uid = catentry.cat_inst_id
params = {"INST_IDENTIFIER":inst_uid}
params = {"INST_IDENTIFIER": inst_uid}
c = CatQuery(cat_api_key, cat_api_url)
cq = c.admincount(params)
if cq:
if c.response['number_of_admins'] > 0:
if catentry.url != "ACTIVE":
catentry.url = "ACTIVE"
catentry.save()
\ No newline at end of file
catentry.save()
......@@ -2,63 +2,68 @@
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
import sys, locale, codecs
import sys
import locale
import codecs
# sort greek utf-8 properly
locale.setlocale(locale.LC_COLLATE, ('el_GR', 'UTF8'))
# https://wiki.python.org/moin/PrintFails
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from edumanage.models import *
from accounts.models import *
from registration.models import RegistrationProfile
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--mail-list',
action='store_true',
dest='maillist',
default=False,
help='Return only emails (output suitable for a mailing list)'),
)
make_option(
'--mail-list',
action='store_true',
dest='maillist',
default=False,
help='Return only emails (output suitable for a mailing list)'
),
)
args = ''
help = 'Prints institution contacts in CSV format'
def handle(self, *args, **options):
users = User.objects.all()
users = User.objects.all()
if not options['maillist']:
self.stdout.write(
u'"%s","%s","%s"' % (
u'"%s","%s","%s"' % (
u"Φορέας",
u"Διαχειριστής",
"email"
)
+ "\n")
data = [
(u.get_profile().institution.get_name('el'),
u.first_name + " " + u.last_name,
m)
for u in users if
len(u.registrationprofile_set.all()) > 0 and
u.registrationprofile_set.all()[0].activation_key == "ALREADY_ACTIVATED"
for m in u.email.split(';')
]
data.sort(key=lambda d: unicode(d[0]))
for (foreas, onoma, email) in data:
)
+ "\n"
)
data = [
(
u.get_profile().institution.get_name('el'),
u.first_name + " " + u.last_name,
m
) for u in users if (
len(u.registrationprofile_set.all()) > 0
and u.registrationprofile_set.all()[0].activation_key == "ALREADY_ACTIVATED"
) for m in u.email.split(';')
]
data.sort(key=lambda d: unicode(d[0]))
for (foreas, onoma, email) in data:
if options['maillist']:
self.stdout.write(
u'{email}\t{onoma}'.format(
email=email,
onoma=onoma
)
)
+ "\n")
else:
self.stdout.write(
self.stdout.write(
u'"{foreas}","{onoma}","{email}"'.format(
onoma=onoma,
email=email,
foreas=foreas
)
+ "\n")
)
+ "\n"
)
......@@ -2,13 +2,15 @@
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
from django.core.management.base import BaseCommand, CommandError
from django.core.management.base import BaseCommand
import time
from django.conf import settings
import urllib
from django.core.cache import cache
from xml.etree import ElementTree as ET
import json, bz2
from xml.etree import ElementTree
import json
import bz2