Skip to content
Snippets Groups Projects
learn_config.py 4.94 KiB
Newer Older
  • Learn to ignore specific revisions
  • import pickle
    import diskcache
    import requests
    from diskcache import Cache
    import os
    
    """
    Links
    API: 
    """
    
    def whoami(lc):
        url = "https://testdtu.brightspace.com/d2l/api/lp/1.36/users/whoami"
        payload = {}
        headers = {
            'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjRkZTk0ZWViLTU0NDctNDk4ZC1iMmNhLTU4NDg5MTU3OWI3YSIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE2NjUxNTc5MTYsImV4cCI6MTY2NTE2MTUxNiwiaXNzIjoiaHR0cHM6Ly9hcGkuYnJpZ2h0c3BhY2UuY29tL2F1dGgiLCJhdWQiOiJodHRwczovL2FwaS5icmlnaHRzcGFjZS5jb20vYXV0aC90b2tlbiIsInN1YiI6IjMzOTciLCJ0ZW5hbnRpZCI6ImVmYTdjODJhLWExYzItNGZjOC1hZTgyLTgwOGJhNzhjZDkxYyIsImF6cCI6IjQ4MDFhNDc3LTExYzctNGNmYy04NzMyLTczNmYwNDE1NzhiZSIsInNjb3BlIjoiY29yZToqOioiLCJqdGkiOiJjNGVhOTRhZi0xODdmLTQ3MzEtOGZmMy1lM2RkOWJhN2ZlMTIifQ.ngh5rHtFro4DWf6mcYSPoRV4LyadE7QJfNeeLRbosrPC2rwrW-00kX1oHqnrFLnWeIw9wNpeXfwM8UwYUxWvmwPcSGS6TI8d7I5gAb3Lqq6PEGHUfvho577scU2s_Lubi0RG_VTfaoNxggzFbvDlCzJom9EXWwbxGuLGk49OxtLile1_bX0kit8zOJhFoOGPjiO-GSvH5Qi4tvjYoowrBkTIyYD6Jw81ET_q2uTHaB15kWpMTl2uHeED-aRWivtX_rfTnFq3Wed3SmAPdS5Tb9g46hURKwq11O_ubGjqFbtQCsY9bIJpH5GShUURoQvWsTlqSqEyr7zgzc0wlMXwVQ'
        }
        headers = lc.headers
        response = requests.request("GET", url, headers=headers, data=payload)
        print(response.text)
        return response
        pass
    
    class LearnConfig:
        server = "testdtu.brightspace.com/"
        lp_version = "1.36"
        headers = {
            'Authorization': 'Bearer bla-bla'
                   }
    
        def get_header(self):
            headers = {
                # cc = Cache(directory="cache")
                'Authorization': f"Bearer {self.cc['access_token']}"
            }
            return headers
    
        def isodate(self, date):
            d = date.isoformat()
            return d.split(".")[0] + ".000Z"
    
    
    
        orgunitId = "8407"
        def is_token_valid(self):
            response = whoami(self)
            json = response.json()
            if "FirstName" in json:
                print("Hello there", json['FirstName'])
                return True
            print("Authentication failed")
            print(json)
            return False
    
        def __init__(self):
    
            cc = Cache(directory=      os.path.join( os.path.dirname(__file__), "cache") )
            self.cc = cc
            while True:
                if "access_token" in cc:
                    print("is there")
                    # Try to connect...
                    self.token = cc.get("access_token")
                    self.headers['Authorization'] = f"Bearer {self.token}"
                    if self.is_token_valid():
                        print("Got a new token!")
                        a = 234
                        break
                    else:
                        del cc['access_token']
                        print("The token sucks.")
                        continue
    
                else:
                    if "refresh_token" in cc:
    
                        url = "https://auth.brightspace.com/core/connect/token"
                        refresh_token = cc['refresh_token']
                        # refresh_token = "rt.eu-west-1.SAmtMKD3oe094NV6Yc4F8UuROyRdHMJRz_XwpiYtwfI"
                        self.client_id = "4801a477-11c7-4cfc-8732-736f041578be"
                        self.client_secret = "niLXYwe9f_pQe2RzvZ8LtYE6Ls6DSiZ_0IeTCPhx4_8"
                        payload=f'grant_type=refresh_token&refresh_token={refresh_token}&client_id={self.client_id}&client_secret={self.client_secret}&scope=core%3A*%3A*'
                        headers = {
                          'Content-Type': 'application/x-www-form-urlencoded'
                        }
    
                        response = requests.request("POST", url, headers=headers, data=payload)
                        cc['refresh_token'] = response.json()['refresh_token']
                        cc['access_token'] = response.json()['access_token']
                        print("Authentication success.")
                        break
    
                        # url = "https://auth.brightspace.com/core/connect/token"
                        #
                        # payload = 'grant_type=refresh_token&refresh_token=rt.eu-west-1.QLXytJ-TREfofv9xzbDcBEiEivw-_rogaSmS8XetScg&client_id=4801a477-11c7-4cfc-8732-736f041578be&client_secret=niLXYwe9f_pQe2RzvZ8LtYE6Ls6DSiZ_0IeTCPhx4_8&scope=core%3A*%3A*'
                        # headers = {
                        #     'Content-Type': 'application/x-www-form-urlencoded'
                        # }
                        #
                        # response = requests.request("POST", url, headers=headers, data=payload)
                        #
                        # print(response.text)
                        #
                        #
                        # print(response.text)
    
                    else:
                        s = input("Please give me a refresh token")
                        cc['refresh_token'] = s
                        print("Saved refresh token", s)
                    print("no it is not there")
            a = 234
            print("Phew! Authentication completed.")
            # load refresh token file.
            # test if login possible with current token.
            # pkl.get
            # rt.eu-west-1.tN5byZD8n0KHSowkDC2NnElZx0J0BJgIz57Fmj-ZhKs
            pass
    
    if __name__ == '__main__':
        print("Hello world")
        c = LearnConfig()