cas_callbacks.py 4.1 KB
Newer Older
1
2
3
4
"""
go/cas_callbacks.py
"""

5
# Future Imports
David Haynes's avatar
David Haynes committed
6
7
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
David Haynes's avatar
David Haynes committed
8
9

# Django Imports
10
from django.conf import settings
David Haynes's avatar
David Haynes committed
11
from django.contrib.auth.models import User
David Haynes's avatar
David Haynes committed
12

David Haynes's avatar
David Haynes committed
13
# Other Imports
14
import requests
15

16
def pfparse(pf_name_result):
David Haynes's avatar
David Haynes committed
17
18
19
20
    """
    Parse what peoplefinder sends back to us and make a list out of it
    """

21
22
23
24
25
26
27
28
29
30
31
    # name comes in format of Anderson, Nicholas J
    name_list = pf_name_result.split(',')
    # there's random whitespace with the first name
    first_name_section = name_list[1].strip()
    # check if there's a middle initial
    mi_q = first_name_section.split(' ')
    # make sure that the additional elements aren't multiple names
    if len(mi_q[-1]) == 1:
        first_name = ' '.join(mi_q[:-1])
    else:
        first_name = first_name_section
David Haynes's avatar
David Haynes committed
32
    # our list containing the name of the person in a usable list
33
34
35
36
    new_name_list = [first_name, name_list[0]]
    return new_name_list

def pfinfo(uname):
David Haynes's avatar
David Haynes committed
37
38
39
40
    """
    Get information from peoplefinder
    """

41
42
43
44
45
46
    base_url = settings.PF_URL
    url = base_url + "basic/all/" + str(uname)
    try:
        metadata = requests.get(url, timeout=5)
        print("Retrieving information from the peoplefinder api.")
        metadata.raise_for_status()
47
48
    except requests.exceptions.RequestException as ex:
        print("Cannot resolve to peoplefinder api:", ex)
49
        print("Returning empty user info tuple.")
50
        return ['', '']
51
52
53
54
    else:
        pfjson = metadata.json()
        try:
            if len(pfjson['results']) == 1:
Nicholas Anderson's avatar
Nicholas Anderson committed
55
56
57
58
59
60
61
                if pfjson['method'] == 'peoplefinder':
                    name_str = pfjson['results'][0]['name']
                    name = pfparse(name_str)
                elif pfjson['method'] == 'ldap':
                    name = [pfjson['results'][0]['givenname'], pfjson['results'][0]['surname']]
                else:
                    name = pfjson['results'][0]['name']
David Haynes's avatar
David Haynes committed
62
                return name
63
            else:
Nicholas Anderson's avatar
Nicholas Anderson committed
64
65
66
67
68
69
70
                if pfjson['method'] == 'peoplefinder':
                    name_str = pfjson['results'][1]['name']
                    name = pfparse(name_str)
                elif pfjson['method'] == 'ldap':
                    name = [pfjson['results'][1]['givenname'], pfjson['results'][1]['surname']]
                else:
                    name = pfjson['results'][0]['name']
David Haynes's avatar
David Haynes committed
71
                return name
72
        # if the name is not in peoplefinder, return empty first and last name
73
        except IndexError as ex:
74
            print("Name not found in peoplefinder.")
David Haynes's avatar
David Haynes committed
75
            return ['', '']
76
77
        except Exception as ex:
            print("Unknown peoplefinder error:", ex)
78
            print("Returning empty user info tuple.")
79
            return ['', '']
80

81
def create_user(tree):
David Haynes's avatar
David Haynes committed
82
83
84
    """
    Create a django user based off of the peoplefinder info we parsed earlier
    """
85

86
87
88
89
    print("Parsing CAS information.")
    try:
        username = tree[0][0].text
        user, user_created = User.objects.get_or_create(username=username)
90
91
    except Exception as ex:
        print("CAS callback unsuccessful:", ex)
92
93
94
95
96
97
98
99
100

    # error handling in pfinfo function
    info_name = pfinfo(username)

    try:
        if user_created:
            print("Created user object %s." % username)

            # set and save the user's email
David Haynes's avatar
David Haynes committed
101
            email_str = "%s%s" % (username, settings.EMAIL_DOMAIN)
102
103
104
105
106
107
108
            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.
            user.set_password('cas_used_instead')
            user.save()
            print("Added user's email, %s." % email_str)

David Haynes's avatar
David Haynes committed
109
110
111
112
            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]))
113
114

            print("User object creation process completed.")
115

116
117
        else:
            print("User object already exists.")
118

119
        print("CAS callback successful.")
120
121
    except Exception as ex:
        print("Unhandled user creation error:", ex)