-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask_cas.py
38 lines (31 loc) · 1.22 KB
/
flask_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
import urllib
import requests
from lxml import etree
from flask import Blueprint, request, redirect, session, url_for
flask_cas = Blueprint('flask_cas', __name__, template_folder='templates')
CAS_URL = 'https://login.dartmouth.edu/cas/'
def recursive_dict(element):
return element.tag, dict(map(recursive_dict, element)) or element.text
def cas_login(service):
login_url = CAS_URL + 'login?' + urllib.urlencode(locals())
return redirect(login_url)
def cas_validate(ticket, service):
validate_url = CAS_URL + 'serviceValidate?' + urllib.urlencode(locals())
r = requests.get(validate_url)
doc = etree.fromstring(r.text)
if 'authenticationSuccess' in doc[0].tag:
return dict((key.replace('{http://www.yale.edu/tp/cas}', ''), value) for \
key, value in recursive_dict(doc[0])[1].items())
return None
@flask_cas.route("/login/")
def login():
callback_url = request.url.split('?')[0]
if 'ticket' in request.args:
session['user'] = cas_validate(request.args['ticket'], callback_url)
else:
return cas_login(callback_url)
return redirect(url_for('index'))
@flask_cas.route("/logout/")
def logout():
session.pop('user', None)
return redirect(url_for('index'))