Commit b44b6bb3 authored by Stauros Kroustouris's avatar Stauros Kroustouris

remove lint errors and clean some files

parent db39f53e
......@@ -18,20 +18,21 @@
#
from django.contrib import admin
from accounts.models import *
from django.contrib.auth.models import User
from peers.models import *
from django.conf import settings
class UserPrAdmin(admin.ModelAdmin):
list_display = ('user', 'peer')
admin.site.register(UserProfile, UserPrAdmin)
from django import forms
from django.core.urlresolvers import reverse
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from tinymce.widgets import TinyMCE
from accounts.models import UserProfile
class UserPrAdmin(admin.ModelAdmin):
list_display = ('user', 'peer')
admin.site.register(UserProfile, UserPrAdmin)
class TinyMCEFlatPageAdmin(FlatPageAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
......@@ -43,4 +44,4 @@ class TinyMCEFlatPageAdmin(FlatPageAdmin):
return super(TinyMCEFlatPageAdmin, self).formfield_for_dbfield(db_field, **kwargs)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, TinyMCEFlatPageAdmin)
\ No newline at end of file
admin.site.register(FlatPage, TinyMCEFlatPageAdmin)
......@@ -19,24 +19,23 @@
from django.db import models
from django.contrib.auth.models import User
from peers.models import *
from peers.models import Peer
class UserProfile(models.Model):
user = models.OneToOneField(User)
peer = models.ForeignKey(Peer)
class Meta:
permissions = (
("overview", "Can see registered users and rules"),
)
("overview", "Can see registered users and rules"),
)
def __unicode__(self):
return "%s:%s" %(self.user.username, self.peer.peer_name)
return "%s:%s" % (self.user.username, self.peer.peer_name)
def get_address_space(self):
networks = self.domain.networks.all()
if not networks:
return False
return networks
\ No newline at end of file
return networks
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
......@@ -16,84 +16,110 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django import forms
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.contrib.auth.models import User
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from accounts.models import *
from peers.models import *
from flowspec.forms import *
from registration.models import RegistrationProfile
from registration.views import activate as registration_activate
from django.views.decorators.cache import never_cache
from accounts.models import UserProfile
from peers.models import Peer
from flowspec.forms import UserProfileForm
from registration.models import RegistrationProfile
@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)
activation_key = activation_key.lower() # Normalize before trying anything with it.
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()
except UserProfile.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
}
)
form = UserProfileForm(instance=userProfile)
form.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(pk=rp.user.pk), empty_label=None)
form.fields['peer'] = forms.ModelChoiceField(queryset=Peer.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_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.peer = Peer.objects.get(pk=request_data['peer'])
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
},
)
activation_key = activation_key.lower() # Normalize before trying anything with it.
try:
rp = RegistrationProfile.objects.get(activation_key=activation_key)
account = RegistrationProfile.objects.activate_user(activation_key)
except Exception as e:
except Exception:
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])
context = RequestContext(request)
return render_to_response("registration/activate.html",
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
\ No newline at end of file
email = render_to_string(
request,
'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]
)
return render(
request,
'registration/activate.html',
{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
},
)
from rest_framework import viewsets
from django.contrib.auth.models import User
from accounts.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
......@@ -17,9 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django.contrib.auth.models import User
from django.contrib.auth.models import User, UserManager, Permission, Group
from django.conf import settings
class shibauthBackend:
def authenticate(self, **kwargs):
......@@ -43,7 +42,7 @@ class shibauthBackend:
try:
user = User.objects.get(username__exact=username)
# The user did not exist. Create one with no privileges
except:
except:
user = User.objects.create_user(username, mail, None)
user.first_name = firstname
user.last_name = lastname
......
......@@ -18,23 +18,21 @@
#
from django.contrib import admin
from flowspec.models import *
from accounts.models import *
from flowspec.models import MatchPort, MatchDscp, MatchProtocol, FragmentType, ThenAction, Route
from accounts.models import UserProfile
from utils import proxy as PR
from tasks import *
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from peers.models import *
from flowspec.forms import *
import datetime
from django.conf import settings
from longerusername.forms import UserCreationForm, UserChangeForm
class RouteAdmin(admin.ModelAdmin):
form = RouteForm
actions = ['deactivate']
def deactivate(self, request, queryset):
queryset = queryset.filter(status='ACTIVE')
response = batch_delete.delay(queryset, reason="ADMININACTIVE")
......@@ -52,23 +50,23 @@ class RouteAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
return False
list_display = ('name', 'status', 'applier' , 'applier_peer', 'get_match', 'get_then', 'response', "expires", "comments")
list_display = ('name', 'status', 'applier', 'applier_peer', 'get_match', 'get_then', 'response', "expires", "comments")
fieldsets = [
(None, {'fields': ['name','applier']}),
("Match", {'fields': ['source', 'sourceport', 'destination', 'destinationport', 'port']}),
(None, {'fields': ['name', 'applier']}),
("Match", {'fields': ['source', 'sourceport', 'destination', 'destinationport', 'port']}),
('Advanced Match Statements', {'fields': ['dscp', 'fragmenttype', 'icmpcode', 'icmptype', 'packetlength', 'protocol', 'tcpflag'], 'classes': ['collapse']}),
("Then", {'fields': ['then' ]}),
("Expires", {'fields': ['expires' ]}),
(None, {'fields': ['comments',]}),
("Then", {'fields': ['then']}),
("Expires", {'fields': ['expires']}),
(None, {'fields': ['comments', ]}),
]
class UserProfileInline(admin.StackedInline):
model = UserProfile
class UserProfileAdmin(UserAdmin):
add_form = UserCreationForm
form = UserChangeForm
......
......@@ -140,7 +140,7 @@ class RouteForm(forms.ModelForm):
if broadcast_error:
error_text = _('Malformed address format. Cannot be ...0/32')
raise forms.ValidationError(error_text)
def clean_expires(self):
date = self.cleaned_data['expires']
if date:
......@@ -152,22 +152,17 @@ class RouteForm(forms.ModelForm):
def clean(self):
if self.errors:
raise forms.ValidationError(_('Errors in form. Please review and fix them: %s'%", ".join(self.errors)))
raise forms.ValidationError(_('Errors in form. Please review and fix them: %s'%", ".join(self.errors)))
name = self.cleaned_data.get('name', None)
source = self.cleaned_data.get('source', None)
sourceports = self.cleaned_data.get('sourceport', None)
ports = self.cleaned_data.get('port', None)
fragmenttypes = self.cleaned_data.get('fragmenttype', None)
then = self.cleaned_data.get('then', None)
destination = self.cleaned_data.get('destination', None)
destinationports = self.cleaned_data.get('destinationport', None)
protocols = self.cleaned_data.get('protocol', None)
user = self.cleaned_data.get('applier', None)
try:
issuperuser = self.data['issuperuser']
su = User.objects.get(username=issuperuser)
except:
issuperuser = None
issuperuser = self.data.get('issuperuser')
peer = user.get_profile().peer
networks = peer.networks.all()
if issuperuser:
......@@ -223,7 +218,7 @@ class RouteForm(forms.ModelForm):
if ports:
route_pk_list=get_matchingport_route_pks(ports, existing_routes)
if route_pk_list:
existing_routes = existing_routes.filter(pk__in=route_pk_list)
existing_routes = existing_routes.filter(pk__in=route_pk_list)
else:
existing_routes = existing_routes.filter(port=None)
for route in existing_routes:
......@@ -233,11 +228,12 @@ class RouteForm(forms.ModelForm):
raise forms.ValidationError('Found an exact %s rule, %s with destination prefix %s<br>To avoid overlapping try editing rule <a href=\'%s\'>%s</a>' %(route.status, route.name, route.destination, existing_url, route.name))
return self.cleaned_data
class ThenPlainForm(forms.ModelForm):
# action = forms.CharField(initial='rate-limit')
class Meta:
model = ThenAction
def clean_action_value(self):
action_value = self.cleaned_data['action_value']
if action_value:
......@@ -257,18 +253,17 @@ class ThenPlainForm(forms.ModelForm):
raise forms.ValidationError(_('Cannot select something other than rate-limit'))
else:
return self.cleaned_data["action"]
class PortPlainForm(forms.ModelForm):
# action = forms.CharField(initial='rate-limit')
class Meta:
model = MatchPort
def clean_port(self):
port = self.cleaned_data['port']
if port:
try:
p = int(port)
if int(port) > 65535 or int(port) < 0:
raise forms.ValidationError(_('Port should be < 65535 and >= 0'))
return "%s" %self.cleaned_data["port"]
......@@ -279,12 +274,14 @@ class PortPlainForm(forms.ModelForm):
else:
raise forms.ValidationError(_('Cannot be empty'))
def value_list_to_list(valuelist):
vl = []
for val in valuelist:
vl.append(val[0])
return vl
def get_matchingport_route_pks(portlist, routes):
route_pk_list = []
ports_value_list = value_list_to_list(portlist.values_list('port').order_by('port'))
......@@ -294,6 +291,7 @@ def get_matchingport_route_pks(portlist, routes):
route_pk_list.append(route.pk)
return route_pk_list
def get_matchingprotocol_route_pks(protocolist, routes):
route_pk_list = []
protocols_value_list = value_list_to_list(protocolist.values_list('protocol').order_by('protocol'))
......@@ -301,4 +299,4 @@ def get_matchingprotocol_route_pks(protocolist, routes):
rsp = value_list_to_list(route.protocol.all().values_list('protocol').order_by('protocol'))
if rsp and rsp == protocols_value_list:
route_pk_list.append(route.pk)
return route_pk_list
\ No newline at end of file
return route_pk_list
......@@ -28,16 +28,14 @@ from django.conf import settings
import datetime
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
import os
from celery.exceptions import TimeLimitExceeded, SoftTimeLimitExceeded
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
#FORMAT = '%(asctime)s %(levelname)s: %(message)s'
#logging.basicConfig(format=FORMAT)
# FORMAT = '%(asctime)s %(levelname)s: %(message)s'
# logging.basicConfig(format=FORMAT)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
logger = logging.getLogger(__name__)
......@@ -74,7 +72,8 @@ def add(route, callback=None):
route.status = "ERROR"
route.response = "Error"
route.save()
announce("[%s] Rule add: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule add: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
@task(ignore_result=True)
def edit(route, callback=None):
......@@ -103,7 +102,7 @@ def edit(route, callback=None):
route.status = "ERROR"
route.response = "Error"
route.save()
announce("[%s] Rule edit: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule edit: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
@task(ignore_result=True)
......@@ -137,7 +136,8 @@ def delete(route, **kwargs):
route.status = "ERROR"
route.response = "Error"
route.save()
announce("[%s] Suspending rule : %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Suspending rule : %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
# May not work in the first place... proxy is not aware of Route models
@task
......@@ -164,22 +164,24 @@ def batch_delete(routes, **kwargs):
route.response = response
route.expires = datetime.date.today()
route.save()
announce("[%s] Rule removal: %s%s- Result %s" %(route.applier, route.name, reason_text, response), route.applier)
announce("[%s] Rule removal: %s%s- Result %s" % (route.applier, route.name, reason_text, response), route.applier)
else:
return False
#@task(ignore_result=True)
def announce(messg, user):
messg = str(messg)
username = user.get_profile().peer.peer_tag
b = beanstalkc.Connection()
b.use(settings.POLLS_TUBE)
tube_message = json.dumps({'message': messg, 'username':username})
tube_message = json.dumps({'message': messg, 'username': username})
b.put(tube_message)
b.close()
@task
def check_sync(route_name=None, selected_routes = []):
def check_sync(route_name=None, selected_routes=[]):
from flowspec.models import Route, MatchPort, MatchDscp, ThenAction
if not selected_routes:
routes = Route.objects.all()
......@@ -196,6 +198,7 @@ def check_sync(route_name=None, selected_routes = []):
if route.status != 'EXPIRED':
route.check_sync()
@task(ignore_result=True)
def notify_expired():
from flowspec.models import *
......@@ -229,25 +232,3 @@ def notify_expired():
logger.info("Exception: %s"%e)
pass
logger.info('Expiration notification process finished')
#def delete(route):
#
# applier = PR.Applier(route_object=route)
# commit, response = applier.apply(configuration=applier.delete_routes())
# if commit:
# rows = queryset.update(is_online=False, is_active=False)
# queryset.update(response="Successfully removed route from network")
# self.message_user(request, "Successfully removed %s routes from network" % rows)
# else:
# self.message_user(request, "Could not remove routes from network")
# if commit:
# is_online = False
# is_active = False
# response = "Successfully removed route from network"
# else:
# is_online = False
# is_active = True
# route.is_online = is_online
# route.is_active = is_active
# route.response = response
# route.save()
\ No newline at end of file
from django import template
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
import socket
register = template.Library()
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment