a b/Authentication.py
1
#!/usr/bin/python
2
# 5/19/2016 - update to allow for authentication based on api-key, rather than username/pw
3
# See https://documentation.uts.nlm.nih.gov/rest/authentication.html for full explanation
4
5
import requests
6
from pyquery import PyQuery as pq
7
8
uri = "https://utslogin.nlm.nih.gov"
9
auth_endpoint = "/cas/v1/api-key"
10
11
12
class Authentication:
13
14
    def __init__(self, apikey):
15
        # self.username=username
16
        # self.password=password
17
        self.apikey = apikey
18
        self.service = "http://umlsks.nlm.nih.gov"
19
20
    def gettgt(self):
21
        # params = {'username': self.username,'password': self.password}
22
        params = {'apikey': self.apikey}
23
        h = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-Agent": "python" }
24
        r = requests.post(uri+auth_endpoint, data=params, headers=h, timeout=120)
25
        d = pq(r.text)
26
        # extract the entire URL needed from the HTML form (action attribute) returned 
27
        # looks similar to https://utslogin.nlm.nih.gov/cas/v1/tickets/TGT-36471-aYqNLN2rFIJPXKzxwdTNC5ZT7z3B3cTAKfSc5ndHQcUxeaDOLN-cas
28
        # we make a POST call to this URL in the getst method
29
        tgt = d.find('form').attr('action')
30
        return tgt
31
32
    def getst(self, tgt):
33
34
        params = {'service': self.service}
35
        h = {"Content-type": "application/x-www-form-urlencoded", 
36
             "Accept": "text/plain", "User-Agent": "python"}
37
        r = requests.post(tgt, data=params, headers=h)
38
        st = r.text
39
        return st