Commit a563516e authored by David Haynes's avatar David Haynes

Merge branch 'issue7'

parents 3f77c5c4 3b7eb4cb
# Django Imports
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# App Imports
from go.models import URL, RegisteredUser
# Define what attributes display in the URL Admin
class URLAdmin(admin.ModelAdmin):
list_display = ("target", "short", "owner", "clicks", "date_created", "expires")
# Define an inline admin descriptor for User model
class RegisteredUserInline(admin.StackedInline):
model = RegisteredUser
can_delete = False
class RegisteredUserAdmin(admin.ModelAdmin):
list_display = ("username", "full_name", "organization", "approved")
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (RegisteredUserInline, )
# Register URLAdmin and modify User to use new UserAdmin
admin.site.register(URL, URLAdmin)
admin.site.register(RegisteredUser, RegisteredUserAdmin)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
from __future__ import absolute_import, print_function
# Django Imports
# core django imports
from django.contrib.auth.models import User
from django.conf import settings
# Other Imports
from django.contrib import messages
# third party imports
import requests
def pfparse(pf_name_result):
# name comes in format of Anderson, Nicholas J
print(pf_name_result)
name_list = pf_name_result.split(',')
# there's random whitespace with the first name
first_name_section = name_list[1].strip()
......@@ -22,10 +22,10 @@ def pfparse(pf_name_result):
new_name_list = [first_name, name_list[0]]
return new_name_list
def pfinfo(uname):
base_url = settings.PF_URL
url = base_url + "basic/all/" + str(uname)
print("Using url %s", url)
try:
metadata = requests.get(url, timeout=5)
print("Retrieving information from the peoplefinder api.")
......@@ -38,50 +38,22 @@ def pfinfo(uname):
pfjson = metadata.json()
try:
if len(pfjson['results']) == 1:
return pfparse(pfjson['results'][0]['name'])
name_str = pfjson['results'][0]['name']
name = pfparse(name_str)
return name
else:
return pfparse(pfjson['results'][1]['name'])
name_str = pfjson['results'][1]['name']
name = pfparse(name_str)
return name
# if the name is not in peoplefinder, return empty first and last name
except IndexError:
print("Name not found in peoplefinder.")
return [u'', u'']
return [u'',u'']
except Exception as e:
print("Unknown peoplefinder error:", e)
print("Returning empty user info tuple.")
return [u'', u'']
def create_user_dud(tree):
print("Parsing CAS information.")
try:
username = tree[0][0].text
user, user_created = User.objects.get_or_create(username=username)
except Exception as e:
print("CAS callback unsuccessful:", e)
info_name = pfinfo(username)
try:
if user_created:
print("Created user object %s!" % username)
user.email = "%s@%s" % (username, settings.ORGANIZATION_EMAIL_DOMAIN)
# Password is a required User object field, though doesn't matter for our
# purposes because all user auth is handled through CAS, not Django's login.
user.set_password("cas_used_instead")
# a list of empty strings is False
if not info_name:
user.first_name = info_name[0]
user.last_name = info_name[1]
print("Added user's name, %s %s." % (info_name[0], info_name[1]))
else:
print("Unable to add user %s's name." % username)
user.save()
else:
print("User %s already exists" % username)
except Exception as e:
print("Unhandled user creation error:", e)
def create_user(tree):
......@@ -100,7 +72,7 @@ def create_user(tree):
print("Created user object %s." % username)
# set and save the user's email
email_str = "%s@%s" % (username, settings.ORGANIZATION_EMAIL_DOMAIN)
email_str = "%s%s" % (username, settings.EMAIL_DOMAIN)
user.email = email_str
# Password is a required User object field, though doesn't matter for our
# purposes because all user auth is handled through CAS, not Django's login.
......@@ -108,13 +80,10 @@ def create_user(tree):
user.save()
print("Added user's email, %s." % email_str)
if len(info_name[0]) > 0:
user.first_name = info_name[0]
user.last_name = info_name[1]
user.save()
print("Added user's name, %s %s." % (info_name[0], info_name[1]))
else:
print("Unable to add user's name.")
user.first_name = info_name[0]
user.last_name = info_name[1]
user.save()
print("Added user's name, %s %s." % (info_name[0], info_name[1]))
print("User object creation process completed.")
......@@ -124,4 +93,3 @@ def create_user(tree):
print("CAS callback successful.")
except Exception as e:
print("Unhandled user creation error:", e)
# mail the administrators
......@@ -168,30 +168,6 @@ class URLForm(forms.ModelForm):
class SignupForm(forms.ModelForm):
def validate_username(username):
try:
registered = RegisteredUser.objects.get(username=username)
raise ValidationError('Username "%s" is already in use.' % username)
except RegisteredUser.DoesNotExist:
return
def clean_username(self):
# Prevent hax: (non-staff) Users cannot signup for other users
data_username = self.cleaned_data.get("username")
if not self.request.user.is_staff:
if self.request.user.username not in data_username:
raise ValidationError('username', "This is not your NetID!")
return data_username
username = forms.CharField(
required=True,
label='Mason NetID (Required)',
max_length=30,
validators=[validate_username],
widget=forms.TextInput(attrs={
}),
)
full_name = forms.CharField(
required=True,
label='Full Name (Required)',
......@@ -213,7 +189,8 @@ class SignupForm(forms.ModelForm):
widget=forms.Textarea(attrs={
}),
)
tos_box = forms.BooleanField(
# A user becomes registered when they agree to the TOS
registered = forms.BooleanField(
required=True,
# Need to add a Terms of Service Page and replace the href below
label = mark_safe('Do you accept the <a href="#" target="_blank">Terms of Service</a>?'),
......@@ -233,11 +210,10 @@ class SignupForm(forms.ModelForm):
Div(
# Place in form fields
Div(
'username',
'full_name',
'organization',
'description',
'tos_box',
'registered',
css_class='well'),
# Extras at bottom
......@@ -245,4 +221,5 @@ class SignupForm(forms.ModelForm):
css_class='col-md-6')))
class Meta:
model = RegisteredUser
fields = '__all__'
fields = ('full_name', 'organization', 'description', 'registered',)
exclude = ('user',)
......@@ -3,14 +3,55 @@ from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.cache import cache
from django.db.models.signals import post_save
from django.dispatch import receiver
# Other Imports
import string
from hashids import Hashids
hashids = Hashids(salt="srct.gmu.edu", alphabet=(string.ascii_lowercase + string.digits))
class RegisteredUser(models.Model):
"""
This is simply a wrapper model which, if an object exists, indicates
that that user is registered.
"""
# Let's associate a User to this RegisteredUser
user = models.OneToOneField(User)
# What is your name?
full_name = models.CharField(
blank=False,
max_length=100,
)
# What organization are you associated with?
organization = models.CharField(
blank=False,
max_length=100,
)
# Why do you want to use Go?
description = models.TextField(blank=True)
# Have you filled out the registration form?
registered = models.BooleanField(default=False)
# Are you approved to use Go?
approved = models.BooleanField(default=False)
# print(RegisteredUser)
def __unicode__(self):
return '<Registered User: %s - Approval Status: %s>' % (self.user, self.approved)
# When a post_save is called on a User object (and it is newly created), this is
# called to create an associated RegisteredUser
@receiver(post_save, sender=User)
def handle_regUser_creation(sender, instance, created, **kwargs):
if created:
RegisteredUser.objects.create(user=instance)
class URL(models.Model):
"""
......@@ -19,7 +60,7 @@ class URL(models.Model):
date.
"""
owner = models.ForeignKey(User)
owner = models.ForeignKey(RegisteredUser)
date_created = models.DateTimeField(default=timezone.now)
target = models.URLField(max_length=1000)
......@@ -32,7 +73,7 @@ class URL(models.Model):
expires = models.DateTimeField(blank=True, null=True)
def __unicode__(self):
return '<%s : %s>' % (self.owner.username, self.target)
return '<%s : %s>' % (self.owner.user, self.target)
class Meta:
ordering = ['short']
......@@ -52,32 +93,3 @@ class URL(models.Model):
except URL.DoesNotExist:
return short
return None
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
)
full_name = models.CharField(
blank=False,
max_length=100,
)
organization = models.CharField(
blank=False,
max_length=100,
)
description = models.TextField(blank=True)
approved = models.BooleanField()
def __unicode__(self):
return '<Registered User: %s - Approval Status: %s>' % (self.username, self.approved)
......@@ -44,8 +44,8 @@ SRCT Go - Administration Panel
{% for unapproved in need_approval %}
<tr>
<td><input type="checkbox" name="username" value={{ unapproved.username }}></td>
<td>{{ unapproved.username }}</td>
<td><input type="checkbox" name="username" value={{ unapproved.user }}></td>
<td>{{ unapproved.user }}</td>
<td>{{ unapproved.full_name }}</td>
<td>{{ unapproved.description|default:"No description provided" }}</td>
</tr>
......
......@@ -2,7 +2,7 @@
{% load crispy_forms_tags %}
{% block title %}
SCT Go - A University Branded URL Shortener
SRCT Go - A University Branded URL Shortener
{% endblock %}
{% block content %}
......
......@@ -12,8 +12,10 @@
<ul class="nav navbar-nav navbar-left">
<li><a href="{% url 'about' %}">About</a></li>
{% if user.is_authenticated %}
{% if user.registereduser.approved %}
<li><a href="{% url 'my_links' %}">My Links</a></li>
{% if not user|is_registered %}
{% endif %}
{% if not user.registereduser.registered %}
<li><a href="{% url 'signup' %}">Register</a></li>
{% endif %}
{% endif %}
......@@ -24,12 +26,11 @@
{% else %}
<li><a href="{% url 'go_login' %}">Log In <i class="fa fa-sign-in fa-fw"></i></a></li>
{% endif %}
{% if user.is_staff and user|is_approved %}
{% if user.is_staff %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Administration <i class="fa fa-caret-down fa-fw"></i></a>
<ul class="dropdown-menu dropdown-menu-left">
<li><a href="{% url 'useradmin' %}">User Moderation <i class="fa fa-users fa-fw"></i></a></li>
<li><a href="{% url 'signup' %}">Signup New Users <i class="fa fa-user-plus fa-fw"></i></a></li>
</ul>
</li>
{% endif %}
......
......@@ -31,7 +31,7 @@
<a href="{{url.target}}">{{url.target}}</a>
<br />
{% if url.owner == request.user and request.user|is_registered %}
{% if url.owner == request.user.registereduser and request.user.registereduser.approved == True %}
<strong>Clicks:</strong>
{{url.clicks}}
<br />
......
......@@ -6,6 +6,9 @@ banner,.page-header,#banner {
border-bottom: none;
margin-bottom: 0;
}
.fix a:link{
color: #FFFFFF;
}
</style>
{% extends 'layouts/base.html' %}
......@@ -83,8 +86,8 @@ SRCT Go - Welcome
</div>
<br />
<hr />
<div class="row">
<br />
<div class="fix" "row">
<div class="col-md-offset-1 col-md-4" "col-md-offset-2 col-md-4">
<a href="{% url 'go_login' %}" class="btn btn-primary btn-block">Log In</a>
</div>
......
......@@ -31,4 +31,5 @@ SRCT Go - Link View
<p>Nothing here.</p>
</div>
{% endif %}
</div>
{% endblock %}
This diff is collapsed.
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