Commit 58f8286d authored by David Haynes's avatar David Haynes 🙆

Add basic redirection back in

parent b9c6baba
Pipeline #3550 passed with stage
in 1 minute and 49 seconds
...@@ -17,20 +17,21 @@ def pfparse(pf_name_result: str) -> list: ...@@ -17,20 +17,21 @@ def pfparse(pf_name_result: str) -> list:
Parse what peoplefinder sends back to us and make a list out of it. Parse what peoplefinder sends back to us and make a list out of it.
""" """
# name comes in format of Anderson, Nicholas J # name comes in format of Anderson, Nicholas J
name_list = pf_name_result.split(',') name_list = pf_name_result.split(",")
# there's random whitespace with the first name # there's random whitespace with the first name
first_name_section = name_list[1].strip() first_name_section = name_list[1].strip()
# check if there's a middle initial # check if there's a middle initial
mi_q = first_name_section.split(' ') mi_q = first_name_section.split(" ")
# make sure that the additional elements aren't multiple names # make sure that the additional elements aren't multiple names
if len(mi_q[-1]) == 1: if len(mi_q[-1]) == 1:
first_name = ' '.join(mi_q[:-1]) first_name = " ".join(mi_q[:-1])
else: else:
first_name = first_name_section first_name = first_name_section
# our list containing the name of the person in a usable list # our list containing the name of the person in a usable list
new_name_list = [first_name, name_list[0]] new_name_list = [first_name, name_list[0]]
return new_name_list return new_name_list
def pfinfo(uname: str) -> list: def pfinfo(uname: str) -> list:
""" """
Get information from peoplefinder. Get information from peoplefinder.
...@@ -43,36 +44,43 @@ def pfinfo(uname: str) -> list: ...@@ -43,36 +44,43 @@ def pfinfo(uname: str) -> list:
except requests.exceptions.RequestException as ex: except requests.exceptions.RequestException as ex:
print("Cannot resolve to peoplefinder api:", ex) print("Cannot resolve to peoplefinder api:", ex)
print("Returning empty user info tuple.") print("Returning empty user info tuple.")
return ['', ''] return ["", ""]
else: else:
pfjson = metadata.json() pfjson = metadata.json()
try: try:
if len(pfjson['results']) == 1: if len(pfjson["results"]) == 1:
if pfjson['method'] == 'peoplefinder': if pfjson["method"] == "peoplefinder":
name_str = pfjson['results'][0]['name'] name_str = pfjson["results"][0]["name"]
name = pfparse(name_str) name = pfparse(name_str)
elif pfjson['method'] == 'ldap': elif pfjson["method"] == "ldap":
name = [pfjson['results'][0]['givenname'], pfjson['results'][0]['surname']] name = [
pfjson["results"][0]["givenname"],
pfjson["results"][0]["surname"],
]
else: else:
name = pfjson['results'][0]['name'] name = pfjson["results"][0]["name"]
return name return name
else: else:
if pfjson['method'] == 'peoplefinder': if pfjson["method"] == "peoplefinder":
name_str = pfjson['results'][1]['name'] name_str = pfjson["results"][1]["name"]
name = pfparse(name_str) name = pfparse(name_str)
elif pfjson['method'] == 'ldap': elif pfjson["method"] == "ldap":
name = [pfjson['results'][1]['givenname'], pfjson['results'][1]['surname']] name = [
pfjson["results"][1]["givenname"],
pfjson["results"][1]["surname"],
]
else: else:
name = pfjson['results'][0]['name'] name = pfjson["results"][0]["name"]
return name return name
# if the name is not in peoplefinder, return empty first and last name # if the name is not in peoplefinder, return empty first and last name
except IndexError as ex: except IndexError as ex:
print("Name not found in peoplefinder.") print("Name not found in peoplefinder.")
return ['', ''] return ["", ""]
except Exception as ex: except Exception as ex:
print("Unknown peoplefinder error:", ex) print("Unknown peoplefinder error:", ex)
print("Returning empty user info tuple.") print("Returning empty user info tuple.")
return ['', ''] return ["", ""]
def create_user(tree: list): def create_user(tree: list):
""" """
...@@ -83,7 +91,8 @@ def create_user(tree: list): ...@@ -83,7 +91,8 @@ def create_user(tree: list):
try: try:
username = tree[0][0].text username = tree[0][0].text
# error handling in pfinfo function # error handling in pfinfo function
info_name = pfinfo(username) # info_name = pfinfo(username)
info_name = ["", ""]
# set and save the user's email # set and save the user's email
email_str = "%s%s" % (username, settings.EMAIL_DOMAIN) email_str = "%s%s" % (username, settings.EMAIL_DOMAIN)
...@@ -91,12 +100,12 @@ def create_user(tree: list): ...@@ -91,12 +100,12 @@ def create_user(tree: list):
username=username, username=username,
email=email_str, email=email_str,
first_name=info_name[0], first_name=info_name[0],
last_name=info_name[1] last_name=info_name[1],
) )
# Password is a required User object field, though doesn't matter for our # 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. # purposes because all user auth is handled through CAS, not Django's login.
user.set_password('cas_used_instead') user.set_password("cas_used_instead")
if os.environ['GO_ENV'] != 'production': if os.environ["GO_ENV"] != "production":
user.is_staff = True user.is_staff = True
user.is_superuser = True user.is_superuser = True
user.save() user.save()
...@@ -105,6 +114,5 @@ def create_user(tree: list): ...@@ -105,6 +114,5 @@ def create_user(tree: list):
print("Created user object %s." % username) print("Created user object %s." % username)
else: else:
print("User object already exists.") print("User object already exists.")
except Exception as ex: except Exception as ex:
print("CAS callback unsuccessful:", ex) print("CAS callback unsuccessful:", ex)
...@@ -4,7 +4,7 @@ settings/urls.py ...@@ -4,7 +4,7 @@ settings/urls.py
The URLs of the project and their associated view that requests are routed to. The URLs of the project and their associated view that requests are routed to.
""" """
# Django Imports # Django Imports
from django.urls import path, include from django.urls import path, include, re_path
from django.contrib import admin from django.contrib import admin
# Third Party # Third Party
...@@ -31,15 +31,17 @@ urlpatterns = [ ...@@ -31,15 +31,17 @@ urlpatterns = [
path("admin/", admin.site.urls, name="go_admin"), path("admin/", admin.site.urls, name="go_admin"),
path("auth/", include("rest_framework.urls")), path("auth/", include("rest_framework.urls")),
path("auth/token/", views.CustomAuthToken.as_view()), path("auth/token/", views.CustomAuthToken.as_view()),
path("auth/status/", views.GetSessionInfo.as_view()) path("auth/status/", views.GetSessionInfo.as_view()),
# # /view/<short> - View URL data. Cached for 15 minutes # /view/<short> - View URL data. Cached for 15 minutes
# re_path(r'^view/(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$', # re_path(r'^view/(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$',
# cache_page(60 * 15)(go.views.view), name='view'), # cache_page(60 * 15)(go.views.view), name='view'),
# re_path(r'^view/(?P<short>[-\w]+)$', # re_path(r'^view/(?P<short>[-\w]+)$',
# cache_page(60 * 15)(go.views.view), name='view'), # cache_page(60 * 15)(go.views.view), name='view'),
# # Redirection regex. # Redirection regex.
# re_path(r'^(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$', re_path(
# go.views.redirection, name='redirection'), r"^(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$",
# re_path(r'^(?P<short>[-\w]+)$', views.redirection,
# go.views.redirection, name='redirection'), name="redirection",
),
re_path(r"^(?P<short>[-\w]+)$", views.redirection, name="redirection"),
] ]
...@@ -4,6 +4,7 @@ go/views.py ...@@ -4,6 +4,7 @@ go/views.py
The functions that handle a request to a given URL. Get some data, manipulate The functions that handle a request to a given URL. Get some data, manipulate
it, and return a rendered template. it, and return a rendered template.
""" """
from django.shortcuts import get_object_or_404, redirect
from rest_framework import viewsets, permissions from rest_framework import viewsets, permissions
from rest_framework.authentication import TokenAuthentication, SessionAuthentication from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.views import APIView from rest_framework.views import APIView
...@@ -72,3 +73,13 @@ class GetSessionInfo(APIView): ...@@ -72,3 +73,13 @@ class GetSessionInfo(APIView):
"token": token.key, "token": token.key,
} }
return Response(session_info) return Response(session_info)
def redirection(request, short):
"""
This view redirects a user based on the short URL they requested.
"""
# Get the URL object that relates to the requested Go link
url = get_object_or_404(URL, short__iexact=short)
return redirect(url.destination)
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