Unverified Commit ef15de60 authored by David Haynes's avatar David Haynes
Browse files

Merge branch '2.2-dev' into 109-my-links-to-index

parents 2b95a071 da9d9ec7
Pipeline #1101 passed with stage
in 57 seconds
...@@ -15,3 +15,4 @@ venv ...@@ -15,3 +15,4 @@ venv
htmlcov/ htmlcov/
.idea .idea
__pycache__/ __pycache__/
.vscode
\ No newline at end of file
Copyright 2016 George Mason Student-Run Computing and Technology Copyright 2017 George Mason Student-Run Computing and Technology
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
......
...@@ -9,26 +9,29 @@ from django.contrib.auth.models import User ...@@ -9,26 +9,29 @@ from django.contrib.auth.models import User
# App Imports # App Imports
from go.models import URL, RegisteredUser from go.models import URL, RegisteredUser
"""
Define what attributes display in the URL Admin
"""
class URLAdmin(admin.ModelAdmin): class URLAdmin(admin.ModelAdmin):
"""
Define what attributes display in the URL Admin
"""
list_display = ("target", "short", "owner", "clicks", "date_created", "expires") list_display = ("target", "short", "owner", "clicks", "date_created", "expires")
# Register URLAdmin # Register URLAdmin
admin.site.register(URL, URLAdmin) admin.site.register(URL, URLAdmin)
"""
Define an inline admin descriptor for User model
"""
class RegisteredUserInline(admin.StackedInline): class RegisteredUserInline(admin.StackedInline):
"""
Define an inline admin descriptor for User model
"""
model = RegisteredUser model = RegisteredUser
can_delete = False can_delete = False
"""
Define a new User admin
"""
class UserAdmin(UserAdmin): class UserAdmin(UserAdmin):
"""
Define a new User admin
"""
# see above class that we defined # see above class that we defined
inlines = (RegisteredUserInline, ) inlines = (RegisteredUserInline, )
......
# Future Imports # Future Imports
from __future__ import unicode_literals, absolute_import, print_function, division from __future__ import unicode_literals, absolute_import, print_function, division
# Python stdlib Imports
from datetime import date, datetime, timedelta
from six.moves import urllib
# Django Imports # Django Imports
from django import forms from django import forms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
...@@ -15,19 +19,30 @@ from crispy_forms.helper import FormHelper ...@@ -15,19 +19,30 @@ from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div, Field from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div, Field
from crispy_forms.bootstrap import StrictButton, PrependedText, Accordion, AccordionGroup from crispy_forms.bootstrap import StrictButton, PrependedText, Accordion, AccordionGroup
from bootstrap3_datetime.widgets import DateTimePicker from bootstrap3_datetime.widgets import DateTimePicker
from datetime import date, datetime, timedelta
"""
The form that is used in URL creation.
"""
class URLForm(forms.ModelForm): class URLForm(forms.ModelForm):
"""
The form that is used in URL creation.
"""
# Prevent redirect loop links # Prevent redirect loop links
def clean_target(self): def clean_target(self):
# get the entered target link # get the entered target link
target = self.cleaned_data.get('target') target = self.cleaned_data.get('target')
# if the host (go.gmu.edu) is in the entered target link try:
if self.host in target: final_url = urllib.request.urlopen(target).geturl()
# if visiting the provided url results in an HTTP error, or redirects
# to a page that results in an HTTP error
except urllib.error.URLError as e:
# to permit users to enter sites that return most errors, but
# prevent them from entering sites that result in an HTTP 300 error
if any(int(str(e)[11:14]) == errorNum for errorNum in range(300, 308)):
raise ValidationError("Link results in a 300 error")
else:
final_url = ""
# if the host (go.gmu.edu) is in the entered target link or where it
# redirects
if self.host in final_url or self.host in target:
raise ValidationError("You can't make a Go link to Go silly!") raise ValidationError("You can't make a Go link to Go silly!")
else: else:
return target return target
...@@ -54,12 +69,12 @@ class URLForm(forms.ModelForm): ...@@ -54,12 +69,12 @@ class URLForm(forms.ModelForm):
# Custom short-url field with validators. # Custom short-url field with validators.
short = forms.SlugField( short = forms.SlugField(
required = False, required=False,
label = 'Short URL (Optional)', label='Short URL (Optional)',
widget = forms.TextInput(), widget=forms.TextInput(),
validators = [unique_short], validators=[unique_short],
max_length = 20, max_length=20,
min_length = 3, min_length=3,
) )
# define some string date standards # define some string date standards
...@@ -80,11 +95,11 @@ class URLForm(forms.ModelForm): ...@@ -80,11 +95,11 @@ class URLForm(forms.ModelForm):
# Add preset expiration choices. # Add preset expiration choices.
expires = forms.ChoiceField( expires = forms.ChoiceField(
required = True, required=True,
label = 'Expiration (Required)', label='Expiration (Required)',
choices = EXPIRATION_CHOICES, choices=EXPIRATION_CHOICES,
initial = NEVER, initial=NEVER,
widget = forms.RadioSelect(), widget=forms.RadioSelect(),
) )
# Check if the selected date is a valid date # Check if the selected date is a valid date
...@@ -99,12 +114,12 @@ class URLForm(forms.ModelForm): ...@@ -99,12 +114,12 @@ class URLForm(forms.ModelForm):
# Add a custom expiration choice. # Add a custom expiration choice.
expires_custom = forms.DateTimeField( expires_custom = forms.DateTimeField(
required = False, required=False,
label = 'Custom Date', label='Custom Date',
input_formats = ['%m-%d-%Y'], input_formats=['%m-%d-%Y'],
validators = [valid_date], validators=[valid_date],
initial = lambda: datetime.now() + timedelta(days=1), initial=lambda: datetime.now() + timedelta(days=1),
widget = DateTimePicker( widget=DateTimePicker(
options={ options={
"format": "MM-DD-YYYY", "format": "MM-DD-YYYY",
"pickTime": False, "pickTime": False,
...@@ -141,9 +156,9 @@ class URLForm(forms.ModelForm): ...@@ -141,9 +156,9 @@ class URLForm(forms.ModelForm):
<h4>Paste the URL you would like to shorten:</h4> <h4>Paste the URL you would like to shorten:</h4>
<br />"""), <br />"""),
'target', 'target',
style="background: rgb(#F6F6F6);"), style="background: rgb(#F6F6F6);"),
active=True, active=True,
template='crispy/accordian-group.html'), template='crispy/accordian-group.html'),
# Step 2: Short URL # Step 2: Short URL
AccordionGroup('Step 2: Short URL', AccordionGroup('Step 2: Short URL',
...@@ -153,9 +168,9 @@ class URLForm(forms.ModelForm): ...@@ -153,9 +168,9 @@ class URLForm(forms.ModelForm):
<br />"""), <br />"""),
PrependedText( PrependedText(
'short', 'https://go.gmu.edu/', template='crispy/customPrepended.html'), 'short', 'https://go.gmu.edu/', template='crispy/customPrepended.html'),
style="background: rgb(#F6F6F6);"), style="background: rgb(#F6F6F6);"),
active=True, active=True,
template='crispy/accordian-group.html',), template='crispy/accordian-group.html',),
# Step 3: Expiration # Step 3: Expiration
AccordionGroup('Step 3: URL Expiration', AccordionGroup('Step 3: URL Expiration',
...@@ -165,12 +180,12 @@ class URLForm(forms.ModelForm): ...@@ -165,12 +180,12 @@ class URLForm(forms.ModelForm):
<br />"""), <br />"""),
'expires', 'expires',
Field('expires_custom', template="crispy/customDateField.html"), Field('expires_custom', template="crispy/customDateField.html"),
style="background: rgb(#F6F6F6);"), style="background: rgb(#F6F6F6);"),
active=True, active=True,
template='crispy/accordian-group.html'), template='crispy/accordian-group.html'),
# FIN # FIN
template='crispy/accordian.html'), template='crispy/accordian.html'),
####################### #######################
HTML(""" HTML("""
<br />"""), <br />"""),
...@@ -181,42 +196,44 @@ class URLForm(forms.ModelForm): ...@@ -181,42 +196,44 @@ class URLForm(forms.ModelForm):
# what model this form is for # what model this form is for
model = URL model = URL
# what attributes are included # what attributes are included
fields = ['target',] fields = ['target']
"""
The form that is used when a user is signing up to be a RegisteredUser
"""
class SignupForm(forms.ModelForm): class SignupForm(forms.ModelForm):
"""
The form that is used when a user is signing up to be a RegisteredUser
"""
# The full name of the RegisteredUser # The full name of the RegisteredUser
full_name = forms.CharField( full_name = forms.CharField(
required = True, required=True,
label = 'Full Name (Required)', label='Full Name (Required)',
max_length = 100, max_length=100,
widget = forms.TextInput(), widget=forms.TextInput(),
) )
# The RegisteredUser's chosen organization # The RegisteredUser's chosen organization
organization = forms.CharField( organization = forms.CharField(
required = True, required=True,
label = 'Organization (Required)', label='Organization (Required)',
max_length = 100, max_length=100,
widget = forms.TextInput(), widget=forms.TextInput(),
) )
# The RegisteredUser's reason for signing up to us Go # The RegisteredUser's reason for signing up to us Go
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(), widget=forms.Textarea(),
) )
# A user becomes registered when they agree to the TOS # A user becomes registered when they agree to the TOS
registered = forms.BooleanField( registered = forms.BooleanField(
required=True, required=True,
# ***Need to replace lower url with production URL*** ie. go.gmu.edu/about#terms # ***Need to replace lower url with production URL*** ie. go.gmu.edu/about#terms
label = mark_safe('Do you accept the <a href="http://127.0.0.1:8000/about#terms">Terms of Service</a>?'), label=mark_safe(
'Do you accept the <a href="http://127.0.0.1:8000/about#terms">Terms of Service</a>?'
),
) )
# on initialization of the form, crispy forms renders this layout # on initialization of the form, crispy forms renders this layout
...@@ -249,4 +266,4 @@ class SignupForm(forms.ModelForm): ...@@ -249,4 +266,4 @@ class SignupForm(forms.ModelForm):
# what model this form is for # what model this form is for
model = RegisteredUser model = RegisteredUser
# what attributes are included # what attributes are included
fields = ['full_name', 'organization', 'description', 'registered',] fields = ['full_name', 'organization', 'description', 'registered']
...@@ -10,6 +10,10 @@ from go.models import URL ...@@ -10,6 +10,10 @@ from go.models import URL
# Define a new custom django-admin command # Define a new custom django-admin command
class Command(BaseCommand): class Command(BaseCommand):
"""
Remove expired links from the database
"""
# Define help text for this command # Define help text for this command
help = 'Removes expired links from the database' help = 'Removes expired links from the database'
......
...@@ -7,14 +7,15 @@ from django.test import TestCase ...@@ -7,14 +7,15 @@ from django.test import TestCase
# App Imports # App Imports
from .expirelinks import * from .expirelinks import *
"""
Test cases for the functions in expirelinks
"""
class ExpireLinksTest(TestCase): class ExpireLinksTest(TestCase):
""" """
Default test case, does not actually test anything Test cases for the functions in expirelinks
""" """
def test_Django_Test(self): def test_Django_Test(self):
"""
Default test case, does not actually test anything
"""
self.assertEqual("Hello World!", "Hello World!") self.assertEqual("Hello World!", "Hello World!")
# Future Imports # Future Imports
from __future__ import unicode_literals, absolute_import, print_function, division from __future__ import unicode_literals, absolute_import, print_function, division
# Python stdlib Imports
import string
# Django Imports # Django Imports
from django.db import models from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
...@@ -12,46 +15,45 @@ from django.utils.encoding import python_2_unicode_compatible ...@@ -12,46 +15,45 @@ from django.utils.encoding import python_2_unicode_compatible
# Other Imports # Other Imports
from hashids import Hashids # http://hashids.org/python/ from hashids import Hashids # http://hashids.org/python/
import string
# generate the salt and initialize Hashids # generate the salt and initialize 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))
"""
This is simply a wrapper model for the user object which, if an object
exists, indicates that that user is registered.
"""
@python_2_unicode_compatible @python_2_unicode_compatible
class RegisteredUser(models.Model): class RegisteredUser(models.Model):
"""
# Is this User Blocked? This is simply a wrapper model for the user object which, if an object
blocked = models.BooleanField(default = False) exists, indicates that that user is registered.
"""
# Let's associate a User to this RegisteredUser # Let's associate a User to this RegisteredUser
user = models.OneToOneField(User) user = models.OneToOneField(User)
# What is your name? # What is your name?
full_name = models.CharField( full_name = models.CharField(
blank = False, blank=False,
max_length = 100, max_length=100,
) )
# What organization are you associated with? # What organization are you associated with?
organization = models.CharField( organization = models.CharField(
blank = False, blank=False,
max_length = 100, max_length=100,
) )
# Why do you want to use Go? # Why do you want to use Go?
description = models.TextField(blank = True) description = models.TextField(blank=True)
# Have you filled out the registration form? # Have you filled out the registration form?
registered = models.BooleanField(default = False) registered = models.BooleanField(default=False)
# Are you approved to use Go? # Are you approved to use Go?
approved = models.BooleanField(default = False) approved = models.BooleanField(default=False)
# Is this User Blocked?
blocked = models.BooleanField(default=False)
# print(RegisteredUser) # str(RegisteredUser)
def __str__(self): def __str__(self):
return '<Registered User: %s - Approval Status: %s>' % (self.user, self.approved) return '<Registered User: %s - Approval Status: %s>' % (self.user, self.approved)
...@@ -64,37 +66,37 @@ def handle_regUser_creation(sender, instance, created, **kwargs): ...@@ -64,37 +66,37 @@ def handle_regUser_creation(sender, instance, created, **kwargs):
RegisteredUser.objects.create(user=instance) RegisteredUser.objects.create(user=instance)
"""
This model represents a stored URL redirection rule. Each URL has an
owner, target url, short identifier, click counter, and expiration
date.
"""
@python_2_unicode_compatible @python_2_unicode_compatible
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.
"""
# Who is the owner of this Go link # Who is the owner of this Go link
owner = models.ForeignKey(RegisteredUser) owner = models.ForeignKey(RegisteredUser)
# When was this link created? # When was this link created?
date_created = models.DateTimeField(default = timezone.now) date_created = models.DateTimeField(default=timezone.now)
# What is the target URL for this Go link # What is the target URL for this Go link
target = models.URLField(max_length = 1000) target = models.URLField(max_length=1000)
# What is the actual go link (short url) for this URL # What is the actual go link (short url) for this URL
short = models.SlugField(max_length = 20, primary_key = True) short = models.SlugField(max_length=20, primary_key=True)
# how many people have visited this Go link # how many people have visited this Go link
clicks = models.IntegerField(default = 0) clicks = models.IntegerField(default=0)
# how many people have visited this Go link through the qr code # how many people have visited this Go link through the qr code
qrclicks = models.IntegerField(default = 0) qrclicks = models.IntegerField(default=0)
# how many people have visited the go link through social media # how many people have visited the go link through social media
socialclicks = models.IntegerField(default = 0) socialclicks = models.IntegerField(default=0)
# does this Go link expire on a certain date # does this Go link expire on a certain date
expires = models.DateTimeField(blank = True, null = True) expires = models.DateTimeField(blank=True, null=True)
# print(URL) # print(URL)
def __str__(self): def __str__(self):
return '<%s : %s>' % (self.owner.user, self.target) return '<Owner: %s - Target URL: %s>' % (self.owner.user, self.target)
# metadata for URL's # metadata for URL's
class Meta: class Meta:
......
This diff is collapsed.
...@@ -12,17 +12,18 @@ from go.models import RegisteredUser ...@@ -12,17 +12,18 @@ from go.models import RegisteredUser
# filters are registered. # filters are registered.
register = template.Library() register = template.Library()
"""
Helper template function to check if a user is registered.
givenUser: The User object that we are checking to see if they are registered
or not.
"""
@register.filter @register.filter
def is_registered(givenUser): def is_registered(given_user):
"""
Helper template function to check if a user is registered.
given_user: The User object that we are checking to see if they are registered
or not.
"""
# try getting the RegisteredUser of the current user # try getting the RegisteredUser of the current user
try: try:
getRegisteredUser = RegisteredUser.objects.get(user=givenUser) getRegisteredUser = RegisteredUser.objects.get(user=given_user)
# if it works then the user is registered # if it works then the user is registered
return getRegisteredUser.registered return getRegisteredUser.registered
# This should never happen # This should never happen
...@@ -31,19 +32,20 @@ def is_registered(givenUser): ...@@ -31,19 +32,20 @@ def is_registered(givenUser):
# if they don't exist then they are not registered # if they don't exist then they are not registered
return False return False
"""
Helper template function to check if a user is approved.
givenUser: The User object that we are checking to see if they are approved
or not.
"""
@register.filter @register.filter
def is_approved(givenUser): def is_approved(given_user):
"""
Helper template function to check if a user is approved.
given_user: The User object that we are checking to see if they are approved
or not.
"""
# try getting the RegisteredUser of the current user # try getting the RegisteredUser of the current user
try: try:
getRegisteredUser = RegisteredUser.objects.get(user=givenUser) get_registered_user = RegisteredUser.objects.get(user=given_user)
# if they exist, return whether or not they are approved (boolean) # if they exist, return whether or not they are approved (boolean)
return getRegisteredUser.approved return get_registered_user.approved
# This should never happen # This should never happen
except RegisteredUser.DoesNotExist as ex: except RegisteredUser.DoesNotExist as ex: