-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathcas.py
256 lines (200 loc) · 7.6 KB
/
cas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""
CAS (Princeton) Authentication
Some code borrowed from
https://sp.princeton.edu/oit/sdp/CAS/Wiki%20Pages/Python.aspx
"""
import datetime
import re
import urllib.parse
import urllib.request
import uuid
from xml.etree import ElementTree
from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
CAS_EMAIL_DOMAIN = "princeton.edu"
CAS_URL= 'https://fed.princeton.edu/cas/'
CAS_LOGOUT_URL = 'https://fed.princeton.edu/cas/logout?service=%s'
CAS_SAML_VALIDATE_URL = 'https://fed.princeton.edu/cas/samlValidate?TARGET=%s'
# eligibility checking
if hasattr(settings, 'CAS_USERNAME'):
CAS_USERNAME = settings.CAS_USERNAME
CAS_PASSWORD = settings.CAS_PASSWORD
CAS_ELIGIBILITY_URL = settings.CAS_ELIGIBILITY_URL
CAS_ELIGIBILITY_REALM = settings.CAS_ELIGIBILITY_REALM
# display tweaks
LOGIN_MESSAGE = "Log in with my NetID"
STATUS_UPDATES = False
def _get_service_url():
# FIXME current URL
from helios_auth import url_names
from django.conf import settings
from django.urls import reverse
return settings.SECURE_URL_HOST + reverse(url_names.AUTH_AFTER)
def get_auth_url(request, redirect_url):
request.session['cas_redirect_url'] = redirect_url
return CAS_URL + 'login?service=' + urllib.parse.quote(_get_service_url())
def get_user_category(user_id):
theurl = CAS_ELIGIBILITY_URL % user_id
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm=CAS_ELIGIBILITY_REALM, uri= theurl, user= CAS_USERNAME, passwd = CAS_PASSWORD)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
result = urllib.request.urlopen(CAS_ELIGIBILITY_URL % user_id).read().strip()
parsed_result = ElementTree.fromstring(result)
return parsed_result.text
def get_saml_info(ticket):
"""
Using SAML, get all of the information needed
"""
import logging
saml_request = """<?xml version='1.0' encoding='UTF-8'?>
<soap-env:Envelope
xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>
<soap-env:Header />
<soap-env:Body>
<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"
MajorVersion="1" MinorVersion="1"
RequestID="%s"
IssueInstant="%sZ">
<samlp:AssertionArtifact>%s</samlp:AssertionArtifact>
</samlp:Request>
</soap-env:Body>
</soap-env:Envelope>
""" % (uuid.uuid1(), datetime.datetime.utcnow().isoformat(), ticket)
url = CAS_SAML_VALIDATE_URL % urllib.parse.quote(_get_service_url())
# by virtue of having a body, this is a POST
req = urllib.request.Request(url, saml_request)
raw_response = urllib.request.urlopen(req).read()
logging.info("RESP:\n%s\n\n" % raw_response)
response = ElementTree.fromstring(raw_response)
# ugly path down the tree of attributes
attributes = response.findall('{http://schemas.xmlsoap.org/soap/envelope/}Body/{urn:oasis:names:tc:SAML:1.0:protocol}Response/{urn:oasis:names:tc:SAML:1.0:assertion}Assertion/{urn:oasis:names:tc:SAML:1.0:assertion}AttributeStatement/{urn:oasis:names:tc:SAML:1.0:assertion}Attribute')
values = {}
for attribute in attributes:
values[str(attribute.attrib['AttributeName'])] = attribute.findtext('{urn:oasis:names:tc:SAML:1.0:assertion}AttributeValue')
# parse response for netid, display name, and employee type (category)
return {'user_id': values.get('mail',None), 'name': values.get('displayName', None), 'category': values.get('employeeType',None)}
def get_user_info(user_id):
url = 'http://dsml.princeton.edu/'
headers = {'SOAPAction': "#searchRequest", 'Content-Type': 'text/xml'}
request_body = """<?xml version='1.0' encoding='UTF-8'?>
<soap-env:Envelope
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>
<soap-env:Body>
<batchRequest xmlns='urn:oasis:names:tc:DSML:2:0:core'
requestID='searching'>
<searchRequest
dn='o=Princeton University, c=US'
scope='wholeSubtree'
derefAliases='neverDerefAliases'
sizeLimit='200'>
<filter>
<equalityMatch name='uid'>
<value>%s</value>
</equalityMatch>
</filter>
<attributes>
<attribute name="displayName"/>
<attribute name="pustatus"/>
</attributes>
</searchRequest>
</batchRequest>
</soap-env:Body>
</soap-env:Envelope>
""" % user_id
req = urllib.request.Request(url, request_body, headers)
response = urllib.request.urlopen(req).read()
# parse the result
from xml.dom.minidom import parseString
response_doc = parseString(response)
# get the value elements (a bit of a hack but no big deal)
values = response_doc.getElementsByTagName('value')
if len(values)>0:
return {'name' : values[0].firstChild.wholeText, 'category' : values[1].firstChild.wholeText}
else:
return None
def get_user_info_special(ticket):
# fetch the information from the CAS server
val_url = CAS_URL + "validate" + \
'?service=' + urllib.parse.quote(_get_service_url()) + \
'&ticket=' + urllib.parse.quote(ticket)
r = urllib.request.urlopen(val_url).readlines() # returns 2 lines
# success
if len(r) == 2 and re.match("yes", r[0]) is not None:
netid = r[1].strip()
category = get_user_category(netid)
#try:
# user_info = get_user_info(netid)
#except:
# user_info = None
# for now, no need to wait for this request to finish
user_info = None
if user_info:
info = {'name': user_info['name'], 'category': category}
else:
info = {'name': netid, 'category': category}
return {'user_id': netid, 'name': info['name'], 'info': info, 'token': None}
else:
return None
def get_user_info_after_auth(request):
ticket = request.GET.get('ticket', None)
# if no ticket, this is a logout
if not ticket:
return None
#user_info = get_saml_info(ticket)
user_info = get_user_info_special(ticket)
user_info['type'] = 'cas'
return user_info
def do_logout(user):
"""
Perform logout of CAS by redirecting to the CAS logout URL
"""
return HttpResponseRedirect(CAS_LOGOUT_URL % _get_service_url())
def update_status(token, message):
"""
simple update
"""
pass
def send_message(user_id, name, user_info, subject, body):
"""
send email, for now just to Princeton
"""
# if the user_id contains an @ sign already
if "@" in user_id:
email = user_id
else:
email = "%s@%s" % (user_id, CAS_EMAIL_DOMAIN)
if 'name' in user_info:
name = user_info["name"]
else:
name = email
send_mail(subject, body, settings.SERVER_EMAIL, ["%s <%s>" % (name, email)], fail_silently=False)
#
# eligibility
#
def check_constraint(constraint, user):
if 'category' not in user.info:
return False
return constraint['year'] == user.info['category']
def generate_constraint(category_id, user):
"""
generate the proper basic data structure to express a constraint
based on the category string
"""
return {'year': category_id}
def list_categories(user):
current_year = datetime.datetime.now().year
return [{'id': str(y), 'name': 'Class of %s' % y} for y
in range(current_year, current_year+5)]
def eligibility_category_id(constraint):
return constraint['year']
def pretty_eligibility(constraint):
return "Members of the Class of %s" % constraint['year']
#
# Election Creation
#
def can_create_election(user_id, user_info):
return True