Commit 2df5a448 authored by David Haynes's avatar David Haynes
Browse files

Comments in views.py

- also a little bit of cleanup as well
parent 36f99ce7
...@@ -16,26 +16,33 @@ from go.forms import URLForm, SignupForm ...@@ -16,26 +16,33 @@ from go.forms import URLForm, SignupForm
# Other Imports # Other Imports
from datetime import timedelta from datetime import timedelta
def index(request): """
"""
This view handles the homepage that the user is presented with when This view handles the homepage that the user is presented with when
they request '/'. If they're not logged in, they're redirected to they request '/'. If they're not logged in, they're redirected to
login. If they're logged in but not registered, they're given the login. If they're logged in but not registered, they're given the
not_registered error page. If they are logged in AND registered, they not_registered error page. If they are logged in AND registered, they
get the URL registration form. get the URL registration form.
""" """
def index(request):
# If the user is not authenticated, show them a public landing page. # If the user is not authenticated, show them a public landing page.
if not request.user.is_authenticated(): if not request.user.is_authenticated():
return render(request, 'public_landing.html') return render(request, 'public_landing.html')
# If the user isn't approved, don't give them any leeway. # If the user isn't approved, then display the you're not approved page.
elif not request.user.registereduser.approved: elif not request.user.registereduser.approved:
return render(request, 'not_registered.html') return render(request, 'not_registered.html')
# Initialize a URL form
url_form = URLForm(host=request.META.get('HTTP_HOST')) # unbound form url_form = URLForm(host=request.META.get('HTTP_HOST')) # unbound form
# If a POST request is received, then the user has submitted a form and it's
# time to parse the form and create a new URL object
if request.method == 'POST': if request.method == 'POST':
url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST')) # bind dat form # Now we initialize the form again but this time we have the POST
# request
url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST'))
# Django will check the form to make sure it's valid
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
...@@ -47,6 +54,8 @@ def index(request): ...@@ -47,6 +54,8 @@ def index(request):
# so accept it. If they did not, however, then generate a # so accept it. If they did not, however, then generate a
# random one and use that instead. # random one and use that instead.
short = url_form.cleaned_data.get('short').strip() short = url_form.cleaned_data.get('short').strip()
# Check if a short URL was entered
if len(short) > 0: if len(short) > 0:
url.short = short url.short = short
else: else:
...@@ -66,6 +75,7 @@ def index(request): ...@@ -66,6 +75,7 @@ def index(request):
# relative to right now. # relative to right now.
expires = url_form.cleaned_data.get('expires') expires = url_form.cleaned_data.get('expires')
# Determine what the expiration date is
if expires == URLForm.DAY: if expires == URLForm.DAY:
url.expires = timezone.now() + timedelta(days=1) url.expires = timezone.now() + timedelta(days=1)
elif expires == URLForm.WEEK: elif expires == URLForm.WEEK:
...@@ -81,45 +91,52 @@ def index(request): ...@@ -81,45 +91,52 @@ def index(request):
# let's redirect to view this baby. # let's redirect to view this baby.
url.full_clean() url.full_clean()
url.save() url.save()
return redirect('view', url.short) return redirect('view', url.short)
# Render index.html passing the form to the template
return render(request, 'core/index.html', { return render(request, 'core/index.html', {
'form': url_form, 'form': url_form,
}, },
) )
"""
def view(request, short):
"""
This view allows the user to view details about a URL. Note that they This view allows the user to view details about a URL. Note that they
do not need to be logged in to view info. do not need to be logged in to view info.
""" """
def view(request, short):
# Get the current domain info
domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/" domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
# Get the URL that is being requested
url = get_object_or_404(URL, short__iexact=short) url = get_object_or_404(URL, short__iexact=short)
# Render view.html passing the specified URL and Domain to the template
return render(request, 'view.html', { return render(request, 'view.html', {
'url': url, 'url': url,
'domain': domain, 'domain': domain,
}, },
) )
"""
@login_required
def my_links(request):
"""
This view displays all the information about all of your URLs. You This view displays all the information about all of your URLs. You
obviously need to be logged in to view your URLs. obviously need to be logged in to view your URLs.
""" """
@login_required
def my_links(request):
# Do not display this page to unapproved users
if not request.user.registereduser.approved: if not request.user.registereduser.approved:
return render(request, 'not_registered.html') return render(request, 'not_registered.html')
urls = URL.objects.filter(owner=request.user.registereduser) # Get the current domain info
domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/" domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
# Grab a list of all the URL's that are currently owned by the user
urls = URL.objects.filter(owner=request.user.registereduser)
# Render my_links.html passing the list of URL's and Domain to the template
return render(request, 'my_links.html', { return render(request, 'my_links.html', {
'urls': urls, 'urls': urls,
'domain': domain, 'domain': domain,
...@@ -127,45 +144,62 @@ def my_links(request): ...@@ -127,45 +144,62 @@ def my_links(request):
) )
@login_required """
def delete(request, short):
"""
This view deletes a URL if you have the permission to. User must be This view deletes a URL if you have the permission to. User must be
logged in and registered, and must also be the owner of the URL. logged in and registered, and must also be the owner of the URL.
""" """
@login_required
def delete(request, short):
# Do not allow unapproved users to delete links
if not request.user.registereduser.approved: if not request.user.registereduser.approved:
return render(request, 'not_registered.html') return render(request, 'not_registered.html')
# Get the URL that is going to be deleted
url = get_object_or_404(URL, short__iexact=short) url = get_object_or_404(URL, short__iexact=short)
# If the RegisteredUser is the owner of the URL
if url.owner == request.user.registereduser: if url.owner == request.user.registereduser:
# remove the URL
url.delete() url.delete()
# rediret to my_links
return redirect('my_links') return redirect('my_links')
else: else:
# do not allow them to delete
raise PermissionDenied() raise PermissionDenied()
"""
This view presents the user with a registration form. You can register yourself.
"""
@login_required @login_required
def signup(request): def signup(request):
"""
This view presents the user with a registration form. You can register yourself.
"""
# Do not display signup page to registered or approved users # Do not display signup page to registered or approved users
if request.user.registereduser.approved: if request.user.registereduser.approved:
return redirect('/') return redirect('/')
elif request.user.registereduser.registered: elif request.user.registereduser.registered:
return redirect('registered') return redirect('registered')
# Initialize our signup form
signup_form = SignupForm(request, signup_form = SignupForm(request,
initial={'full_name': request.user.first_name + " " + request.user.last_name}) initial={'full_name': request.user.first_name + " " + request.user.last_name})
# Set the full_name field to readonly since CAS will fill that in for them
signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly' signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
# If a POST request is received, then the user has submitted a form and it's
# time to parse the form and create a new RegisteredUser
if request.method == 'POST': if request.method == 'POST':
# Now we initialize the form again but this time we have the POST
# request
signup_form = SignupForm(request, request.POST, instance=request.user.registereduser, signup_form = SignupForm(request, request.POST, instance=request.user.registereduser,
initial={'full_name': request.user.first_name + " " + request.user.last_name}) initial={'full_name': request.user.first_name + " " + request.user.last_name})
# set the readonly flag again for good measure
signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly' signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
# Django will check the form to make sure it's valid
if signup_form.is_valid(): if signup_form.is_valid():
# Grab data from the form and store into variables
description = signup_form.cleaned_data.get('description') description = signup_form.cleaned_data.get('description')
full_name = signup_form.cleaned_data.get('full_name') full_name = signup_form.cleaned_data.get('full_name')
organization = signup_form.cleaned_data.get('organization') organization = signup_form.cleaned_data.get('organization')
...@@ -209,81 +243,68 @@ def signup(request): ...@@ -209,81 +243,68 @@ def signup(request):
[user_mail] [user_mail]
) )
# Make sure that our new RegisteredUser object is clean, then save
# it and let's redirect to tell the user they have registered.
signup_form.save() signup_form.save()
return redirect('registered') return redirect('registered')
# render signup.html passing along the form and the current registered
# status
return render(request, 'core/signup.html', { return render(request, 'core/signup.html', {
'form': signup_form, 'form': signup_form,
'registered': False, 'registered': False,
}, },
) )
"""
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.
""" """
def redirection(request, short):
# Get the current domain info
domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
# Get the URL object that relates to the requested Go link
url = get_object_or_404(URL, short__iexact=short) url = get_object_or_404(URL, short__iexact=short)
url.clicks = url.clicks + 1 # Increment our clicks by one
url.clicks += 1
domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/" # If the user is trying to make a Go link to itself, we 404 them
if url.target == domain + short: if url.target == domain + short:
return redirect('admin/404.html') return redirect('admin/404.html')
# If the user is coming from a QR request then increment qrclicks
if 'qr' in request.GET: if 'qr' in request.GET:
url.qrclicks += 1 url.qrclicks += 1
# If the user is coming from a social media request then increment qrclicks
if 'social' in request.GET: if 'social' in request.GET:
url.socialclicks += 1 url.socialclicks += 1
# Save our data and redirect the user towards thier destination
url.save() url.save()
"""
Include server-side tracking because there is no template displayed to
the user which would include javascript tracking.
"""
from piwikapi.tracking import PiwikTracker
from django.conf import settings
# First, if PIWIK variables are undefined, don't try to push
if settings.PIWIK_SITE_ID != "" and settings.PIWIK_URL != "":
try:
piwiktracker = PiwikTracker(settings.PIWIK_SITE_ID, request)
piwiktracker.set_api_url(settings.PIWIK_URL)
piwiktracker.do_track_page_view('Redirect to %s' % url.target)
# Second, if we do get an error, don't let that keep us from redirecting
except:
pass
return redirect(url.target) return redirect(url.target)
"""
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
return user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)(view_func)
@staff_member_required
def useradmin(request):
"""
This view is a simplified admin panel, so that staff don't need to log in This view is a simplified admin panel, so that staff don't need to log in
to approve links to approve links
""" """
@staff_member_required
def useradmin(request):
# If we receive a POST request
if request.POST: if request.POST:
# Get a list of the potential victims (users)
userlist = request.POST.getlist('username') userlist = request.POST.getlist('username')
# If we're approving users
if '_approve' in request.POST: if '_approve' in request.POST:
for name in userlist: for name in userlist:
toapprove = RegisteredUser.objects.get(user__username__exact=name) toapprove = RegisteredUser.objects.get(user__username__exact=name)
toapprove.approved = True toapprove.approved = True
toapprove.save() toapprove.save()
# Send an email letting them know they are approved
if settings.EMAIL_HOST and settings.EMAIL_PORT: if settings.EMAIL_HOST and settings.EMAIL_PORT:
user_mail = toapprove.user.username + settings.EMAIL_DOMAIN user_mail = toapprove.user.username + settings.EMAIL_DOMAIN
send_mail( send_mail(
...@@ -299,11 +320,14 @@ def useradmin(request): ...@@ -299,11 +320,14 @@ def useradmin(request):
settings.EMAIL_FROM, settings.EMAIL_FROM,
[user_mail] [user_mail]
) )
# If we're denying users
elif '_deny' in request.POST: elif '_deny' in request.POST:
for name in userlist: for name in userlist:
todeny = RegisteredUser.objects.get(user__username__exact=name) todeny = RegisteredUser.objects.get(user__username__exact=name)
if settings.EMAIL_HOST and settings.EMAIL_PORT: if settings.EMAIL_HOST and settings.EMAIL_PORT:
user_mail = todeny.user.username + settings.EMAIL_DOMAIN user_mail = todeny.user.username + settings.EMAIL_DOMAIN
# Send an email letting them know they are denied
send_mail( send_mail(
'Your Account has been Denied!', 'Your Account has been Denied!',
###################### ######################
...@@ -318,9 +342,25 @@ def useradmin(request): ...@@ -318,9 +342,25 @@ def useradmin(request):
settings.EMAIL_FROM, settings.EMAIL_FROM,
[user_mail] [user_mail]
) )
# Delete their associated RegisteredUsers
todeny.user.delete() todeny.user.delete()
# Get a list of all RegisteredUsers tthat need to be approved
need_approval = RegisteredUser.objects.filter(registered=True).filter(approved=False) need_approval = RegisteredUser.objects.filter(registered=True).filter(approved=False)
# Pass that list to the template
return render(request, 'admin/useradmin.html', { return render(request, 'admin/useradmin.html', {
'need_approval': need_approval 'need_approval': need_approval
}, },
) )
"""
Decorator function for views that checks that the user is logged in and is
a staff member, displaying the login page if necessary.
"""
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
return user_passes_test(
lambda u: u.is_active and u.is_staff,
login_url=login_url,
redirect_field_name=redirect_field_name
)(view_func)
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