Commit a1d7f14e authored by Daniel W Bond's avatar Daniel W Bond

ran project through flake8; remaining errors either a couple characters over...

ran project through flake8; remaining errors either a couple characters over the line limit (89) or stylistically intentional or logically significant
parent 9de5b1dd
from django.contrib import admin from django.contrib import admin
from go.models import URL, RegisteredUser from go.models import URL, RegisteredUser
# Register your models here.
admin.site.register(URL) admin.site.register(URL)
admin.site.register(RegisteredUser) admin.site.register(RegisteredUser)
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.conf import settings from django.conf import settings
def create_user(tree): def create_user(tree):
username = tree[0][0].text username = tree[0][0].text
......
from django import forms from django import forms
from go.models import URL, RegisteredUser from go.models import URL, RegisteredUser
from django.core.validators import MinLengthValidator, MinValueValidator, RegexValidator from django.core.validators import RegexValidator # MinLengthValidator, MinValueValidator
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from captcha.fields import CaptchaField from captcha.fields import CaptchaField
class URLForm( forms.ModelForm ):
class URLForm(forms.ModelForm):
DAY = '1 Day' DAY = '1 Day'
WEEK = '1 Week' WEEK = '1 Week'
...@@ -20,11 +21,11 @@ class URLForm( forms.ModelForm ): ...@@ -20,11 +21,11 @@ class URLForm( forms.ModelForm ):
# Add a custom expiration choice field. # Add a custom expiration choice field.
expires = forms.ChoiceField( expires = forms.ChoiceField(
required = True, required=True,
label = 'Expiration', label='Expiration',
choices = EXPIRATION_CHOICES, choices=EXPIRATION_CHOICES,
initial = NEVER, initial=NEVER,
widget = forms.RadioSelect(), widget=forms.RadioSelect(),
) )
# Short field must be only letters. # Short field must be only letters.
...@@ -33,7 +34,7 @@ class URLForm( forms.ModelForm ): ...@@ -33,7 +34,7 @@ class URLForm( forms.ModelForm ):
'Only letters are allowed.' 'Only letters are allowed.'
) )
def unique_short( value ): def unique_short(value):
try: try:
URL.objects.get(short__iexact=value) URL.objects.get(short__iexact=value)
except URL.DoesNotExist: except URL.DoesNotExist:
...@@ -42,12 +43,12 @@ class URLForm( forms.ModelForm ): ...@@ -42,12 +43,12 @@ class URLForm( forms.ModelForm ):
# Custom short-url field with validators. # Custom short-url field with validators.
short = forms.CharField( short = forms.CharField(
required = False, required=False,
label = 'Short URL (Optional)', label='Short URL (Optional)',
widget = forms.TextInput(attrs={}), widget=forms.TextInput(attrs={}),
validators = [alphanumeric,unique_short], validators=[alphanumeric, unique_short],
max_length = 20, max_length=20,
min_length = 3, min_length=3,
) )
class Meta: class Meta:
...@@ -64,7 +65,7 @@ class URLForm( forms.ModelForm ): ...@@ -64,7 +65,7 @@ class URLForm( forms.ModelForm ):
} }
class SignupForm( forms.ModelForm ): class SignupForm(forms.ModelForm):
def validate_username(username): def validate_username(username):
try: try:
...@@ -74,25 +75,25 @@ class SignupForm( forms.ModelForm ): ...@@ -74,25 +75,25 @@ class SignupForm( forms.ModelForm ):
return return
username = forms.CharField( username = forms.CharField(
required = True, required=True,
label = 'Mason NetID', label='Mason NetID',
max_length = 30, max_length=30,
validators=[validate_username], validators=[validate_username],
widget = forms.TextInput(attrs={ widget=forms.TextInput(attrs={
}), }),
) )
full_name = forms.CharField( full_name = forms.CharField(
required = True, required=True,
label = 'Full Name', label='Full Name',
max_length = 100, max_length=100,
widget = forms.TextInput(attrs={ widget=forms.TextInput(attrs={
}), }),
) )
description = forms.CharField( description = forms.CharField(
required = False, required=False,
label = 'Description (Optional)', label='Description (Optional)',
max_length = 200, max_length=200,
widget = forms.Textarea(attrs={ widget=forms.Textarea(attrs={
}), }),
) )
captcha = CaptchaField() captcha = CaptchaField()
......
from django.db import models from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.utils import timezone from django.utils import timezone
from django.conf import settings # from django.conf import settings
import random, string import string # random
from hashids import Hashids from hashids import Hashids
hashids = Hashids(salt="srct.gmu.edu", alphabet=(string.ascii_lowercase + string.digits)) hashids = Hashids(salt="srct.gmu.edu", alphabet=(string.ascii_lowercase + string.digits))
hashids_counter = None hashids_counter = None
class URL( models.Model ):
class URL(models.Model):
""" """
This model represents a stored URL redirection rule. Each URL has an This model represents a stored URL redirection rule. Each URL has an
owner, target url, short identifier, click counter, and expiration owner, target url, short identifier, click counter, and expiration
date. date.
""" """
owner = models.ForeignKey( User ) owner = models.ForeignKey(User)
date_created = models.DateTimeField( default=timezone.now ) date_created = models.DateTimeField(default=timezone.now)
target = models.URLField( max_length = 1000 ) target = models.URLField(max_length=1000)
short = models.CharField( primary_key = True, max_length = 20 ) short = models.CharField(primary_key=True, max_length=20)
clicks = models.IntegerField( default = 0 ) clicks = models.IntegerField(default=0)
qrclicks = models.IntegerField(default=0) qrclicks = models.IntegerField(default=0)
socialclicks = models.IntegerField(default=0) socialclicks = models.IntegerField(default=0)
expires = models.DateTimeField( blank = True, null = True ) expires = models.DateTimeField(blank=True, null=True)
def __unicode__(self): def __unicode__(self):
return '<%s : %s>' % (self.owner.username, self.target) return '<%s : %s>' % (self.owner.username, self.target)
...@@ -41,38 +43,38 @@ class URL( models.Model ): ...@@ -41,38 +43,38 @@ class URL( models.Model ):
tries = 1 tries = 1
while tries < 100: while tries < 100:
try: try:
urls = URL.objects.get( short__iexact = short ) # urls = URL.objects.get(short__iexact=short)
tries += 1 tries += 1
hashids_counter += 1 hashids_counter += 1
except URL.DoesNotExist: except URL.DoesNotExist:
return short return short
return None return None
# this needs to be here instead of at the top because the model's manager must be available before this line # this needs to be here instead of at the top because the model's manager
# must be available before this line
hashids_counter = URL.objects.count() hashids_counter = URL.objects.count()
class RegisteredUser( models.Model ): class RegisteredUser(models.Model):
""" """
This is simply a wrapper model which, if an object exists, indicates This is simply a wrapper model which, if an object exists, indicates
that that user is registered. that that user is registered.
""" """
username = models.CharField( username = models.CharField(
blank = False, blank=False,
max_length = 30, max_length=30,
primary_key = True primary_key=True
) )
full_name = models.CharField( full_name = models.CharField(
blank = False, blank=False,
max_length = 100, max_length=100,
) )
description = models.TextField( blank=True ) description = models.TextField(blank=True)
approved = models.BooleanField() approved = models.BooleanField()
def __unicode__(self): def __unicode__(self):
return '<Registered User: %s - Approval Status: %s>' % (self.username, self.approved) return '<Registered User: %s - Approval Status: %s>' % (self.username, self.approved)
...@@ -2,18 +2,20 @@ from django import template ...@@ -2,18 +2,20 @@ from django import template
from go.models import RegisteredUser from go.models import RegisteredUser
register = template.Library() register = template.Library()
@register.filter @register.filter
def is_registered( user ): def is_registered(user):
try: try:
registered = RegisteredUser.objects.get( username=user.username ) registered = RegisteredUser.objects.get(username=user.username)
return True return True
except RegisteredUser.DoesNotExist: except RegisteredUser.DoesNotExist:
return False return False
@register.filter @register.filter
def is_approved(user): def is_approved(user):
try: try:
registered = RegisteredUser.objects.get( username=user.username ) registered = RegisteredUser.objects.get(username=user.username)
return registered.approved return registered.approved
except RegisteredUser.DoesNotExist: except RegisteredUser.DoesNotExist:
return False return False
...@@ -2,15 +2,15 @@ from go.models import URL, RegisteredUser ...@@ -2,15 +2,15 @@ from go.models import URL, RegisteredUser
from go.forms import URLForm, SignupForm from go.forms import URLForm, SignupForm
from datetime import timedelta from datetime import timedelta
from django.conf import settings from django.conf import settings
from django.http import Http404, HttpResponseServerError from django.http import HttpResponseServerError # Http404
from django.utils import timezone from django.utils import timezone
from django.contrib.auth.models import User # from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied, ValidationError from django.core.exceptions import PermissionDenied # ValidationError
from django.core.mail import send_mail from django.core.mail import send_mail
from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test, login_required from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render, get_object_or_404, redirect from django.shortcuts import render, get_object_or_404, redirect
import os # import os
############################################################################## ##############################################################################
...@@ -19,14 +19,14 @@ Define useful helper methods here. ...@@ -19,14 +19,14 @@ Define useful helper methods here.
""" """
def is_approved( user ): def is_approved(user):
""" """
This function checks if a user account has a corresponding RegisteredUser, This function checks if a user account has a corresponding RegisteredUser,
thus checking if the user is registered. thus checking if the user is registered.
""" """
try: try:
registered = RegisteredUser.objects.get( username=user.username ) registered = RegisteredUser.objects.get(username=user.username)
return registered.approved return registered.approved
except RegisteredUser.DoesNotExist: except RegisteredUser.DoesNotExist:
return False return False
...@@ -39,7 +39,7 @@ def is_registered(user): ...@@ -39,7 +39,7 @@ def is_registered(user):
""" """
try: try:
registered = RegisteredUser.objects.get( username=user.username ) registered = RegisteredUser.objects.get(username=user.username)
return True return True
except RegisteredUser.DoesNotExist: except RegisteredUser.DoesNotExist:
return False return False
...@@ -60,6 +60,7 @@ def error_404(request): ...@@ -60,6 +60,7 @@ def error_404(request):
}, },
) )
def error_500(request): def error_500(request):
""" """
Error 500 view, in case a server error occurs. Error 500 view, in case a server error occurs.
...@@ -92,10 +93,10 @@ def index(request): ...@@ -92,10 +93,10 @@ def index(request):
if not is_approved(request.user): if not is_approved(request.user):
return render(request, 'not_registered.html') return render(request, 'not_registered.html')
url_form = URLForm() # unbound form url_form = URLForm() # unbound form
if request.method == 'POST': if request.method == 'POST':
url_form = URLForm( request.POST ) # bind dat form url_form = URLForm(request.POST) # bind dat form
if url_form.is_valid(): if url_form.is_valid():
# We don't commit the url object yet because we need to add its # We don't commit the url object yet because we need to add its
...@@ -133,7 +134,7 @@ def index(request): ...@@ -133,7 +134,7 @@ def index(request):
elif expires == URLForm.MONTH: elif expires == URLForm.MONTH:
url.expires = timezone.now() + timedelta(weeks=3) url.expires = timezone.now() + timedelta(weeks=3)
else: else:
pass # leave the field NULL pass # leave the field NULL
# Make sure that our new URL object is clean, then save it and # Make sure that our new URL object is clean, then save it and
# let's redirect to view this baby. # let's redirect to view this baby.
...@@ -155,11 +156,11 @@ def view(request, short): ...@@ -155,11 +156,11 @@ def view(request, short):
domain = "//%s" % request.META.get('HTTP_HOST') + "/" domain = "//%s" % request.META.get('HTTP_HOST') + "/"
url = get_object_or_404(URL, short__iexact = short) url = get_object_or_404(URL, short__iexact=short)
return render(request, 'view.html', { return render(request, 'view.html', {
'url': url, 'url': url,
'domain' : domain, 'domain': domain,
}, },
) )
...@@ -174,13 +175,13 @@ def my_links(request): ...@@ -174,13 +175,13 @@ def my_links(request):
if not is_approved(request.user): if not is_approved(request.user):
return render(request, 'not_registered.html') return render(request, 'not_registered.html')
urls = URL.objects.filter( owner = request.user ) urls = URL.objects.filter(owner=request.user)
domain = "//%s" % request.META.get('HTTP_HOST') + "/" domain = "//%s" % request.META.get('HTTP_HOST') + "/"
return render(request, 'my_links.html', { return render(request, 'my_links.html', {
'urls' : urls, 'urls': urls,
'domain' : domain, 'domain': domain,
}, },
) )
...@@ -195,7 +196,7 @@ def delete(request, short): ...@@ -195,7 +196,7 @@ def delete(request, short):
if not is_approved(request.user): if not is_approved(request.user):
return render(request, 'not_registered.html') return render(request, 'not_registered.html')
url = get_object_or_404(URL, short__iexact = short ) url = get_object_or_404(URL, short__iexact=short)
if url.owner == request.user: if url.owner == request.user:
url.delete() url.delete()
return redirect('my_links') return redirect('my_links')
...@@ -226,7 +227,7 @@ def signup(request): ...@@ -226,7 +227,7 @@ def signup(request):
if request.method == 'POST': if request.method == 'POST':
signup_form = SignupForm(request.POST, initial={'approved': False, signup_form = SignupForm(request.POST, initial={'approved': False,
'username': request.user.username}) 'username': request.user.username})
if signup_form.is_valid(): if signup_form.is_valid():
# Prevent hax: if not staff, force the username back to the request username. # Prevent hax: if not staff, force the username back to the request username.
...@@ -240,10 +241,10 @@ def signup(request): ...@@ -240,10 +241,10 @@ def signup(request):
# Only send mail if we've defined the mailserver # Only send mail if we've defined the mailserver
if settings.EMAIL_HOST and settings.EMAIL_PORT: if settings.EMAIL_HOST and settings.EMAIL_PORT:
send_mail('Signup from %s' % (username), '%s signed up at %s\n' send_mail('Signup from %s' % (username), '%s signed up at %s\n'
'Username: %s\nMessage: %s\nPlease attend to this request at ' 'Username: %s\nMessage: %s\nPlease attend to this request at '
'your earliest convenience.' % (str(full_name), 'your earliest convenience.' % (str(full_name),
str(timezone.now()).strip(), str(username), str(description)), str(timezone.now()).strip(), str(username), str(description)),
settings.EMAIL_FROM, [settings.EMAIL_TO]) settings.EMAIL_FROM, [settings.EMAIL_TO])
signup_form.save() signup_form.save()
...@@ -261,7 +262,7 @@ def redirection(request, short): ...@@ -261,7 +262,7 @@ def redirection(request, short):
This view redirects a user based on the short URL they requested. This view redirects a user based on the short URL they requested.
""" """
url = get_object_or_404( URL, short__iexact = short ) url = get_object_or_404(URL, short__iexact=short)
url.clicks = url.clicks + 1 url.clicks = url.clicks + 1
if 'qr' in request.GET: if 'qr' in request.GET:
...@@ -289,7 +290,7 @@ def redirection(request, short): ...@@ -289,7 +290,7 @@ def redirection(request, short):
except: except:
pass pass
return redirect( url.target ) return redirect(url.target)
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='about'): def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='about'):
...@@ -322,7 +323,7 @@ def useradmin(request): ...@@ -322,7 +323,7 @@ def useradmin(request):
todeny = RegisteredUser.objects.get(username=name) todeny = RegisteredUser.objects.get(username=name)
todeny.delete() todeny.delete()
need_approval = RegisteredUser.objects.filter(approved=False) need_approval = RegisteredUser.objects.filter(approved=False)
return render(request, 'useradmin.html',{ return render(request, 'useradmin.html', {
'need_approval': need_approval 'need_approval': need_approval
}, },
) )
...@@ -339,6 +340,7 @@ def about(request): ...@@ -339,6 +340,7 @@ def about(request):
}, },
) )
def registered(request): def registered(request):
return render(request, 'registered.html', { return render(request, 'registered.html', {
}, },
......
import secret import secret
import os import os
AUTH_MODE="CAS" AUTH_MODE = "CAS"
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...@@ -136,8 +136,8 @@ if AUTH_MODE.lower() == 'ldap': ...@@ -136,8 +136,8 @@ if AUTH_MODE.lower() == 'ldap':
AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True # use the user AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True # use the user
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=people,o=gmu.edu" AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=people,o=gmu.edu"
AUTH_LDAP_GLOBAL_OPTIONS = { # ignore UAC cert. AUTH_LDAP_GLOBAL_OPTIONS = { # ignore UAC cert.
ldap.OPT_X_TLS : ldap.OPT_X_TLS_DEMAND, ldap.OPT_X_TLS: ldap.OPT_X_TLS_DEMAND,
ldap.OPT_X_TLS_REQUIRE_CERT : ldap.OPT_X_TLS_NEVER, ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER,
} }
AUTH_LDAP_USER_ATTR_MAP = { AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName", "first_name": "givenName",
......
...@@ -9,25 +9,25 @@ handle500 = "error_500" ...@@ -9,25 +9,25 @@ handle500 = "error_500"
urlpatterns = patterns('go.views', urlpatterns = patterns('go.views',
# / - Homepage url. # / - Homepage url.
url(r'^$', 'index', name = 'index'), url(r'^$', 'index', name='index'),
# /view/<short> - View URL data. # /view/<short> - View URL data.
url(r'^view/(?P<short>\w+)$', 'view', name = 'view'), url(r'^view/(?P<short>\w+)$', 'view', name='view'),
# /about - About page. # /about - About page.
url(r'^about/?$', 'about', name = 'about'), url(r'^about/?$', 'about', name='about'),
# /signup - Signup page for access. # /signup - Signup page for access.
url(r'^signup/?$', 'signup', name = 'signup'), url(r'^signup/?$', 'signup', name='signup'),
# /my - My-Links page, view and review links. # /my - My-Links page, view and review links.
url(r'^my/?$', 'my_links', name = 'my_links'), url(r'^my/?$', 'my_links', name='my_links'),
# /delete/<short> - Delete a link, no content display. # /delete/<short> - Delete a link, no content display.
url(r'^delete/(?P<short>\w+)$', 'delete', name = 'delete'), url(r'^delete/(?P<short>\w+)$', 'delete', name='delete'),
# /registered - registration complete page # /registered - registration complete page
url(r'^registered/?$', 'registered', name = 'registered'), url(r'^registered/?$', 'registered', name='registered'),
# /admin - Administrator interface. # /admin - Administrator interface.
url(r'^admin/?', include(admin.site.urls)),