Skip to content

Commit

Permalink
fix pep8 violations
Browse files Browse the repository at this point in the history
  • Loading branch information
ranjur committed Feb 14, 2017
1 parent 5141e1d commit 4b70e38
Show file tree
Hide file tree
Showing 5 changed files with 203 additions and 167 deletions.
53 changes: 30 additions & 23 deletions impostor/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,36 @@


class ImpostorAdmin(admin.ModelAdmin):
fields = ('impostor', 'imposted_as', 'logged_in', 'impostor_ip')
list_display = ('impostor', 'imposted_as', 'impostor_ip', 'logged_in')
list_editable = ()
actions_on_top = False
actions_on_bottom = False
ordering = ('-logged_in', 'impostor')
readonly_fields = ('impostor', 'imposted_as', 'impostor_ip', 'logged_in', 'logged_out')
search_fields = ('impostor__username', 'imposted_as__username')

def add_view(self, request, form_url='', extra_context=None):
request.method = 'GET'
return super(ImpostorAdmin, self).add_view(request, form_url, extra_context)

def change_view(self, request, object_id, form_url='', extra_context=None):
request.method = 'GET'
return super(ImpostorAdmin, self).change_view(request, object_id, form_url, extra_context)

def delete_view(self, request, object_id, extra_context=None):
model = self.model
opts = model._meta
app_label = opts.app_label
return render_to_response('delete_nono.html', {'app_label': app_label, 'opts': opts})

fields = ('impostor', 'imposted_as', 'logged_in', 'impostor_ip')
list_display = ('impostor', 'imposted_as', 'impostor_ip', 'logged_in')
list_editable = ()
actions_on_top = False
actions_on_bottom = False
ordering = ('-logged_in', 'impostor')
readonly_fields = (
'impostor',
'imposted_as',
'impostor_ip',
'logged_in',
'logged_out')
search_fields = ('impostor__username', 'imposted_as__username')

def add_view(self, request, form_url='', extra_context=None):
request.method = 'GET'
return super(ImpostorAdmin, self).add_view(
request, form_url, extra_context)

def change_view(self, request, object_id, form_url='', extra_context=None):
request.method = 'GET'
return super(ImpostorAdmin, self).change_view(
request, object_id, form_url, extra_context)

def delete_view(self, request, object_id, extra_context=None):
model = self.model
opts = model._meta
app_label = opts.app_label
return render_to_response(
'delete_nono.html', {'app_label': app_label, 'opts': opts})


admin.site.register(ImpostorLog, ImpostorAdmin)
135 changes: 72 additions & 63 deletions impostor/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,74 +8,83 @@
from django.conf import settings

try:
IMPOSTOR_GROUP = Group.objects.get(name=settings.IMPOSTOR_GROUP)
IMPOSTOR_GROUP = Group.objects.get(name=settings.IMPOSTOR_GROUP)
except:
IMPOSTOR_GROUP = None
IMPOSTOR_GROUP = None


def find_request():
'''
Inspect running environment for request object. There should be one,
but don't rely on it.
'''
frame = inspect.currentframe()
request = None
f = frame
'''
Inspect running environment for request object. There should be one,
but don't rely on it.
'''
frame = inspect.currentframe()
request = None
f = frame

while not request and f:
if 'request' in f.f_locals and isinstance(f.f_locals['request'], HttpRequest):
request = f.f_locals['request']
f = f.f_back
while not request and f:
if 'request' in f.f_locals and isinstance(
f.f_locals['request'], HttpRequest):
request = f.f_locals['request']
f = f.f_back

del frame
return request
del frame
return request


class AuthBackend:
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False

def authenticate(self, username=None, password=None):
auth_user = None
try:
# Admin logging as user?
admin, uuser = [ uname.strip() for uname in username.split(" as ") ]

# Check if admin exists and authenticates
admin_obj = User.objects.get(username=admin)
if (admin_obj.is_superuser or (IMPOSTOR_GROUP and IMPOSTOR_GROUP in admin_obj.groups.all())) and admin_obj.check_password(password):
try:
auth_user = User.objects.get(username=uuser)
except User.DoesNotExist:
auth_user = User.objects.get(email=uuser)

if auth_user:
# Superusers can only be impersonated by other superusers
if auth_user.is_superuser and not admin_obj.is_superuser:
auth_user = None
raise Exception("Superuser can only be impersonated by a superuser.")

# Try to find request object and maybe be lucky enough to find IP address there
request = find_request()
ip_addr = ''
if request:
ip_addr = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('HTTP_X_REAL_IP', request.META.get('REMOTE_ADDR', '')))
# if there are several ip addresses separated by comma
# like HTTP_X_FORWARDED_FOR returns,
# take only the first one, which is the client's address
if ',' in ip_addr:
ip_addr = ip_addr.split(',', 1)[0].strip()
log_entry = ImpostorLog.objects.create(impostor=admin_obj, imposted_as=auth_user, impostor_ip=ip_addr)

if log_entry.token and request:
request.session['impostor_token'] = log_entry.token

except: # Nope. Do nothing and let other backends handle it.
pass
return auth_user

def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
supports_anonymous_user = False
supports_object_permissions = False
supports_inactive_user = False

def authenticate(self, username=None, password=None):
auth_user = None
try:
# Admin logging as user?
admin, uuser = [uname.strip() for uname in username.split(" as ")]

# Check if admin exists and authenticates
admin_obj = User.objects.get(username=admin)
if (admin_obj.is_superuser or (IMPOSTOR_GROUP and IMPOSTOR_GROUP in admin_obj.groups.all(
))) and admin_obj.check_password(password):
try:
auth_user = User.objects.get(username=uuser)
except User.DoesNotExist:
auth_user = User.objects.get(email=uuser)

if auth_user:
# Superusers can only be impersonated by other superusers
if auth_user.is_superuser and not admin_obj.is_superuser:
auth_user = None
raise Exception(
"Superuser can only be impersonated by a superuser.")

# Try to find request object and maybe be lucky enough to find
# IP address there
request = find_request()
ip_addr = ''
if request:
ip_addr = request.META.get(
'HTTP_X_FORWARDED_FOR', request.META.get(
'HTTP_X_REAL_IP', request.META.get(
'REMOTE_ADDR', '')))
# if there are several ip addresses separated by comma
# like HTTP_X_FORWARDED_FOR returns,
# take only the first one, which is the client's address
if ',' in ip_addr:
ip_addr = ip_addr.split(',', 1)[0].strip()
log_entry = ImpostorLog.objects.create(
impostor=admin_obj, imposted_as=auth_user, impostor_ip=ip_addr)

if log_entry.token and request:
request.session['impostor_token'] = log_entry.token

except: # Nope. Do nothing and let other backends handle it.
pass
return auth_user

def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
3 changes: 2 additions & 1 deletion impostor/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
from django import forms
from django.utils.translation import ugettext_lazy as _


class BigAuthenticationForm(AuthenticationForm):
username = forms.CharField(label=_("Username"), max_length=70)
username = forms.CharField(label=_("Username"), max_length=70)
34 changes: 22 additions & 12 deletions impostor/models.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
from django.db import models
from django.contrib.auth.models import User
#from django.contrib.auth.signals import user_logged_in, user_logged_outs
import hashlib, time
import hashlib
import time

# Create your models here.


class ImpostorLog(models.Model):
impostor = models.ForeignKey(User, related_name='impostor', db_index=True)
imposted_as = models.ForeignKey(User, related_name='imposted_as', verbose_name='Logged in as', db_index=True)
impostor_ip = models.GenericIPAddressField(verbose_name="Impostor's IP address", null=True, blank=True)
logged_in = models.DateTimeField(auto_now_add=True, verbose_name='Logged on')
# These last two will come into play with Django 1.3+, but are here now for easier migration
logged_out = models.DateTimeField(null=True, blank=True)
token = models.CharField(max_length=32, blank=True, db_index=True)
impostor = models.ForeignKey(User, related_name='impostor', db_index=True)
imposted_as = models.ForeignKey(
User,
related_name='imposted_as',
verbose_name='Logged in as',
db_index=True)
impostor_ip = models.GenericIPAddressField(
verbose_name="Impostor's IP address", null=True, blank=True)
logged_in = models.DateTimeField(
auto_now_add=True, verbose_name='Logged on')
# These last two will come into play with Django 1.3+, but are here now
# for easier migration
logged_out = models.DateTimeField(null=True, blank=True)
token = models.CharField(max_length=32, blank=True, db_index=True)

def save(self, *args, **kwargs):
if not self.token and self.impostor:
self.token = hashlib.sha1(self.impostor.username+str(time.time())).hexdigest()[:32]
super(ImpostorLog, self).save(*args, **kwargs)
def save(self, *args, **kwargs):
if not self.token and self.impostor:
self.token = hashlib.sha1(
self.impostor.username + str(time.time())).hexdigest()[:32]
super(ImpostorLog, self).save(*args, **kwargs)
Loading

0 comments on commit 4b70e38

Please sign in to comment.