Commit 02560ef1 authored by David Haynes's avatar David Haynes 🙆
Browse files

Merge branch '182-API-Init' into 'go-three'

Resolve "Initialize the API"

See merge request !122
parents 45be3a4f effeb834
Pipeline #2627 passed with stage
in 52 seconds
......@@ -6,7 +6,6 @@
......@@ -36,9 +36,8 @@ before_script:
- python migrate
- echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('root', '', 'root') " | python shell
image: library/python:3.6
image: library/python:3.7
stage: test
- coverage run --source=go --omit=*migrations/*,*,*,*,*,*,*,*.pyc,*templates/*,*static/* test
- coverage html -i && grep pc_cov htmlcov/index.html | egrep -o "[0-9]+\%" | awk '{ print "covered " $1;}'
- echo "done :)"
# Build on top of the python image and install any external packages
FROM python:3.6
FROM python:3.7
RUN apt-get update
RUN apt-get install netcat -y
......@@ -14,9 +14,10 @@ django-crispy-forms = "==1.7.0"
django-ratelimit = "==1.0.1"
django-redis-cache = "==1.7.1"
hashids = "==1.2.0"
mysqlclient = "*"
django-cas-client = "*"
requests = "*"
mysqlclient = "*"
djangorestframework = "*"
python_version = "3.6"
python_version = "3.7"
"_meta": {
"hash": {
"sha256": "c8aecf58c565d1e2d106d545721922331eb702b7014ecbaf035747291dd94d94"
"sha256": "bdea5532bb3583afe0508086a4acd7186b5c21fad2de7f9bcd73dd0381ee51e7"
"pipfile-spec": 6,
"requires": {
"python_version": "3.6"
"python_version": "3.7"
"sources": [
......@@ -32,11 +32,11 @@
"django": {
"hashes": [
"index": "pypi",
"version": "==2.0.6"
"version": "==2.0.7"
"django-cas-client": {
"hashes": [
......@@ -69,6 +69,14 @@
"index": "pypi",
"version": "==1.7.1"
"djangorestframework": {
"hashes": [
"index": "pypi",
"version": "==3.8.2"
"hashids": {
"hashes": [
......@@ -78,28 +86,24 @@
"idna": {
"hashes": [
"version": "==2.6"
"version": "==2.7"
"mysqlclient": {
"hashes": [
"index": "pypi",
"version": "==1.3.12"
"version": "==1.3.13"
"pytz": {
"hashes": [
"version": "==2018.4"
"version": "==2018.5"
"redis": {
"hashes": [
......@@ -110,37 +114,38 @@
"requests": {
"hashes": [
"index": "pypi",
"version": "==2.18.4"
"version": "==2.19.1"
"urllib3": {
"hashes": [
"version": "==1.22"
"markers": "python_version != '3.0.*' and python_version != '3.3.*' and python_version != '3.2.*' and python_version < '4' and python_version >= '2.6' and python_version != '3.1.*'",
"version": "==1.23"
"develop": {
"astroid": {
"hashes": [
"version": "==1.6.5"
"version": "==2.0.1"
"coverage": {
"hashes": [
......@@ -160,16 +165,11 @@
"index": "pypi",
"version": "==4.5.1"
......@@ -180,6 +180,7 @@
"markers": "python_version != '3.2.*' and python_version != '3.1.*' and python_version != '3.0.*' and python_version != '3.3.*' and python_version >= '2.7'",
"version": "==4.3.4"
"lazy-object-proxy": {
......@@ -225,11 +226,11 @@
"pylint": {
"hashes": [
"index": "pypi",
"version": "==1.9.2"
"version": "==2.0.0"
"pylint-django": {
"hashes": [
......@@ -241,9 +242,9 @@
"pylint-plugin-utils": {
"hashes": [
"version": "==0.2.6"
"version": "==0.4"
"six": {
"hashes": [
# Go 3
[![build status](](
[![coverage report](](
[![python version](]()
[![Django version](]()
A project of [GMU SRCT](
Go is a drop-in URL shortening service. This project aims to provide an easy to
use URL branding service for institutions that wish to widely disseminate
information without unnecessarily outsourcing branding.
Go is currently a `Python 3` project written in the `Django` web framework,
with `MySQL` as our backend database.
## Setup instructions for local development
Go currently supports developers on Linux, macOS and Windows platforms through
the Docker container platform. We have included instructions for manual setup
as well. Here's our walk-through of steps we will take:
1. Install `git` on your system.
1. Clone the Go codebase.
1. Get Go up and running with the method of your choice.
### 1) Install `git` on your system
`git` is the version control system used for SRCT projects.
#### On Linux Based Systems
**with apt:**
Open a terminal and run the following command:
sudo apt update
This retrieves links to the most up-to-date and secure versions of your
Next, with:
sudo apt install git
you install `git` onto your system.
#### On macOS
We recommend that you use the third party Homebrew package manager for macOS,
which allows you to install packages from your terminal just as easily as you
could on a Linux based system. You could use another package manager (or not
use one at all), but Homebrew is highly reccomended.
To get homebrew, run the following command in a terminal:
/usr/bin/ruby -e "$(curl -fsSL
**Note**: You do NOT need to use `sudo` when running any Homebrew commands, and
it likely won't work if you do.
Next, to make sure Homebrew is up to date, run:
brew update
Finally we can install git with:
brew install git
#### On Windows
We recommend that if you are on Windows 10 to make use of the Windows Subsystem
for Linux (WSL). The following link should get you up and running:
#### Contributing with Windows
After that is setup, you should be able to follow the Linux instructions for
_manual setup_ to contribute to the project.
If you are not on Windows 10 or would rather prefer to not use the WSL you may
download Git for Windows here:
I have successfully ran the project with Docker, though you need access to
Hyper-V which is only available on "Professional" versions of Windows.
### 2) Clone the Go codebase
Now, we're going to clone down a copy of the Go codebase from
[](, the SRCT code respository with SSH.
**a)** Configure your ssh keys by following the directions at:
**b)** Now, on your computer, navigate to the directory in which you want to
download the project (ie. perhaps one called `development/SRCT`), and run
git clone
### 3) Get Go up and running with the method of your choice
Now that we have `git` setup and cloned down the code you can
cd go/
and get to working on setting up a development environment!
#### Docker
Docker is an emerging containerization platform written in Google's Go
language. Instead of running a full VM that runs Go, we package up all the
various bits that make up Go and run that as a container (two containers: one
for Go and the other for mysql) that act as normal processes to the OS.
Check out []( for more details.
* Lightweight
* Can be run on most machines without needing significant resources.
* SRCT members report minimal battery impact on laptops.
* Fast
* Compared to other methods, Docker is comparatively faster to setup than
manual setup.
* Minimal setup
* You run one command. Really easy to get up and running once you install
* Good cross platform support
* Runs smoothly on macOS, Linux, and Windows
* Great docs to help if you get stuck.
* Can easily destroy and rebuild the docker images
* Loads in changes to code on the fly
There are instructions on how to setup/develop with Docker at the
[docker-configuration page in the Go project wiki](
#### Manual Setup
Manual setup (or: the old fashioned way) is where you install all dependecies
on your system and run Go as a local server with Django. Granted you are
technically doing that with Docker except it automates the steps that are laid
out in this section.
* Experience setting up a Django project for local development
* Greater potential for things to go wrong
* Way more steps
Head to:
## Some words about contributing to Go
### Testing
You are _very strongly_ encouraged to write test cases where applicible for
code that you contribute to the repo. This is not a rule at the moment but
rather a strong suggestion. It's good practice for corporate land and will also
ensure your code works. Additionally, there are quite a few example ones to
look at in the repo and on Google.
### Running Unit Tests
Unit tests are run on every commit sent to gitlab though that can be a pain to
rely on. Here's how to run them locally:
### Docker
Docker is not supported currently for running unit tests. If you're able to get
it set up, open a merge request and I'll merge it in.
### Manual Setup
Assuming you are within your virtualenv:
python test
This document goes into detail about how to contribute to the repo, plus some
opinions about using `git`.
### Opening issues
There is a template for issue descriptions located on the new issue page. I
will close issues with poor descriptions or who do not follow the standard.
### Authentication
The authentication service used for Go is CAS. In local development however we
utilize a test server. You can log in with just your CAS username to simulate
logging in. By default, the Django superuser is set to `dhaynes3`.
Go 3 is a major refactor of the project with an emphasis on extensibility.
In order to approve yourself to be an 'approved user' you must navigate to and log in. Once in the admin page go to "registered
users", and create a new registered user in the top right. Be sure to use the
same username and Full Name as your main account and select "approved" in the
bottom row.
Things might not work quite right.
### Coding style
Docs may not exist.
I wouldn't go so far as to say we are hitting the reset button.
### Getting Help
But it's close.
I encourage you to join the
[#go channel]( in SRCT's
[Slack Group]( if you have any questions on setup or
would like to contribute.
pipenv install
pipenv shell
code .
docker-compose up
......@@ -3,12 +3,12 @@ go/
Parse the CAS/PF responses and create users in the database.
# Other Imports
import requests
# Django Imports
from django.conf import settings
from django.contrib.auth.models import User
# Other Imports
import requests
def pfparse(pf_name_result: str) -> list:
......@@ -14,10 +14,14 @@ from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
# Other Imports
from hashids import Hashids
from .validators import regex_short_validator, unique_short_validator
from rest_framework.authtoken.models import Token
# Generate the salt and initialize Hashids
# Note: the Hashids library already implements several restrictions oncharacter
......@@ -88,6 +92,12 @@ def handle_reguser_creation(sender, instance, created, **kwargs):
if created:
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
token = Token.objects.create(user=instance)
class URL(models.Model):
The representation of a stored URL redirection rule. Each URL has
Define how data is translated from the database to json/API representation.
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
......@@ -17,15 +17,33 @@ from django.http import HttpResponseServerError # Http404
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
# Other imports
from ratelimit.decorators import ratelimit
# App Imports
from .forms import SignupForm, URLForm, EditForm
from .forms import EditForm, SignupForm, URLForm
from .models import URL, RegisteredUser
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
API endpoint that allows users to be viewed or edited.
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
API endpoint that allows groups to be viewed or edited.
queryset = Group.objects.all()
serializer_class = GroupSerializer
def index(request):
If a user is logged in, this view displays all the information about all
......@@ -2,13 +2,8 @@
import os
import sys
if os.environ['GO_ENV'] == 'production':
settings = "settings.production"
settings = "settings.local"
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings")
from import execute_from_command_line
Local development settings and globals.
from .base import *
# DEBUG mode is used to view more details when errors occur
# Do not have set True in production
DEBUG = True
# dummy cache for development-- doesn't actually cache things
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
Production settings and globals.
from .base import *
# DEBUG mode is used to view more details when errors occur
# Do not have set True in production
DEBUG = False
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'localhost:6379',
Base Settings.
Settings that are applied project wide.
# Python stdlib Imports
import os
import sys
if os.environ['GO_ENV'] != 'production':
DEBUG = True
# dummy cache for development-- doesn't actually cache things
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
DEBUG = False
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'localhost:6379',