cas_callbacks.py 3.48 KB
Newer Older
1 2
# standard library imports
from __future__ import absolute_import, print_function, unicode_literals
3 4 5
# core django imports
from django.conf import settings
from django.contrib.auth.models import User
6
from django.core.exceptions import ObjectDoesNotExist
7 8 9 10 11 12 13 14 15 16 17
# third-part imports
import requests
# imports from your apps
from django.conf import settings
from .models import Student


def pfinfo(u_name):
    pf_url = settings.PF_URL
    url = str(pf_url) + "basic/all/" + str(u_name)
    try:
18 19
        metadata = requests.get(url, timeout=3)
        print("Retrieving information from the peoplefinder api.")
20 21
        metadata.raise_for_status()
    except requests.exceptions.RequestException as e:
22
        print("Cannot resolve to peoplefinder api:", e)
23
        return ['', '']  # return empty response
24 25 26
    else:
        pf_json = metadata.json()
        try:
27 28 29 30 31 32 33 34 35 36 37
            if len(pf_json['results']) == 1:  # ordinary case
                if pf_json['method'] == 'peoplefinder':
                    name = pf_json['results'][0]['name']
                    return name.split(',')
                elif pf_json['method'] == 'ldap':
                    name = [pf_json['results'][0]['surname'],
                            pf_json['results'][0]['givenname']]
                    return name
            else:  # handles student employees, whose employment info is listed first
                name = pf_json['results'][1]['name']
                return name.split(',')
38 39 40
        # if the name is not in peoplefinder, return empty first and last name
        except IndexError:
            return ['', '']
41 42 43
        except Exception as e:
            print("Unknown peoplefinder error:", e)
            return ['', '']
44 45 46


def create_user(tree):
47 48

    print("Parsing CAS information.")
49 50 51 52 53
    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)
54 55 56

    if user_created:
        user.email = "%s@%s" % (username, settings.ORGANIZATION_EMAIL_DOMAIN)
57 58 59
        irrelevant_password = User.objects.make_random_password()
        user.set_password(irrelevant_password)
        print("Added user email, %s, and created random password." % user.email)
60

61
        print("Start peoplefinder parsing")
62 63
        try:
            name_list = pfinfo(str(username))
64
            print(name_list, "name_list")
65 66 67 68 69 70 71 72
            first_name = name_list[1].lstrip().split(' ')
            if len(first_name) > 1:
                no_mi = first_name[:-1]
                user.first_name = ' '.join(no_mi)
            else:
                user.first_name = ' '.join(first_name)
            last_name = name_list[0]
            user.last_name = name_list[0]
73
            print("Added user's name, %s %s." % (user.first_name, user.last_name))
74
        except Exception as e:
75
            print("Unable to add user's name:", e)
76

77
        user.save()
78 79 80 81 82 83 84 85 86 87 88
        print("Created user %s!" % username)

    else:
        print("User object already exists.")

    # Student Creation Section
    try:
        Student.objects.get(user=user)
        print("Student object already exists")

    except ObjectDoesNotExist:
89
        new_student = Student.objects.create(user=user)
90 91 92
            # save the name off of peoplefinder for later quality assurance purposes
            new_student.pf_first_name = user.first_name
            new_student.pf_last_name = user.last_name
93 94

        new_student.save()
95
        print("Created student object for user %s!" % username)
96

97
    print("CAS callback completed.")