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