Skip to content

Instantly share code, notes, and snippets.

@an-empty-string
Created May 29, 2015 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save an-empty-string/cb54e7ef20a085ec620c to your computer and use it in GitHub Desktop.
Save an-empty-string/cb54e7ef20a085ec620c to your computer and use it in GitHub Desktop.
Intranet2 SSO
"""
A wrapper for Intranet2's single sign-on system.
Here's a brief overview of how Iodine SSO works:
- you make a request token (with generate_token)
- you redirect the user to a URL containing that request token
- when the user allows access, they are redirected back to your application
with an access token in the "sso" parameter
- you verify the access token (with check_access_token_validity)
- if you need to, you can start a session to access the API and such
(with start_intranet_session)
Based on Tim Cyrus' documentation and James Woglom's intranet work.
"""
import base64
import collections
import json
import requests
import time
import urllib
ROOT = "https://iodine.tjhsst.edu/"
def generate_token(service, callback, exp=120, method="get"):
"""
Generate a single sign-on request URL. You can redirect the user to this in
order to get an access token.
Parameters:
- service: a name for your application, shown to the user
- callback: a callback URL, the user's browser will redirect here with a
parameter containing an access token
- exp: your request's expiration time in seconds (default 2 minutes)
- method: callback request method, GET recommended
Returns: a URL to redirect the user of your app to
"""
data = {
"title": service,
"return": callback,
"time": int(time.time()),
"exp": int(time.time() + exp),
"method": method.upper()
}
print(data)
token = base64.b64encode(urllib.parse.urlencode(data).encode()).decode()
return "{}sso?req={}".format(ROOT, token)
def check_access_token_validity(token):
"""
Check the validity of a returned access token.
Parameters:
- token: the access token
Returns: the validity of the access token, a boolean
"""
return sso_info(token)["valid_key"]
def sso_info(token):
"""
Get some information about an access token.
Parameters:
- token: the access token
Returns: a dict with keys including but not limited to "username"
"""
data = requests.get("{}/ajax/sso/valid_key".format(ROOT),
params=dict(sso=token)).text
data = json.loads(data)
return data["sso"]
def start_intranet_session(token):
"""
Start a logged-in Intranet session using an access token.
Parameters:
- token: the access token
Returns: a requests.Session object, or False if the access token is invalid
"""
if not check_access_token_validity(token):
return False
session = requests.Session()
session.get("https://iodine.tjhsst.edu/?&login_sso={}".format(token))
return session
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment