pluto/handler/sinks/truelayer.py

107 lines
3.6 KiB
Python
Raw Normal View History

2022-02-28 20:03:21 +00:00
# Twisted/Klein imports
from twisted.logger import Logger
2022-03-04 21:06:54 +00:00
from twisted.internet.task import LoopingCall
2022-02-28 20:03:21 +00:00
# Other library imports
import requests
from simplejson.errors import JSONDecodeError
from time import time
import urllib
2022-02-28 20:03:21 +00:00
# Project imports
from settings import settings
class TrueLayer(object):
"""
Class to manage calls to Open Banking APIs through TrueLayer.
"""
def __init__(self):
self.log = Logger("truelayer")
self.token = None
2022-03-04 21:06:54 +00:00
self.lc = LoopingCall(self.get_new_token)
self.lc.start(int(settings.TrueLayer.RefreshSec))
2022-02-28 20:03:21 +00:00
def create_auth_url(self):
query = urllib.parse.urlencode(
{
"response_type": "code",
"response_mode": "form_post",
"client_id": settings.TrueLayer.ID,
"scope": "info accounts balance transactions offline_access",
"nonce": int(time()),
"redirect_uri": settings.TrueLayer.CallbackURL,
"enable_mock": "true",
}
)
auth_uri = f"{settings.TrueLayer.AuthBase}/?{query}&redirect_uri={settings.TrueLayer.CallbackURL}"
return auth_uri
def handle_authcode_received(self, authcode):
2022-02-28 20:03:21 +00:00
data = {
"client_id": settings.TrueLayer.ID,
"client_secret": settings.TrueLayer.Key,
"code": authcode,
"grant_type": "authorization_code",
"redirect_uri": settings.TrueLayer.CallbackURL,
2022-02-28 20:03:21 +00:00
}
r = requests.post(f"{settings.TrueLayer.AuthBase}/connect/token", data=data)
2022-02-28 20:03:21 +00:00
try:
parsed = r.json()
except JSONDecodeError:
return False
if "error" in parsed:
self.log.error("Error requesting refresh token: {error}", error=parsed["error"])
2022-02-28 20:03:21 +00:00
return False
settings.TrueLayer.RefreshToken = parsed["refresh_token"]
settings.TrueLayer.AuthCode = authcode
settings.write()
self.token = parsed["access_token"]
self.log.info("Retrieved access/refresh tokens - TrueLayer")
2022-02-28 20:03:21 +00:00
2022-03-04 23:04:43 +00:00
def get_new_token(self):
2022-02-28 20:03:21 +00:00
"""
Exchange our refresh token for an access token.
"""
if not settings.TrueLayer.RefreshToken:
return
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = {
"grant_type": "refresh_token",
"refresh_token": settings.TrueLayer.RefreshToken,
"client_id": settings.TrueLayer.ID,
"client_secret": settings.TrueLayer.Key,
}
r = requests.post(f"{settings.TrueLayer.AuthBase}/connect/token", data=data, headers=headers)
try:
parsed = r.json()
except JSONDecodeError:
return False
if r.status_code == 200:
if "access_token" in parsed.keys():
self.token = parsed["access_token"]
self.log.info("Refreshed access token - TrueLayer")
return True
else:
self.log.error(f"Token refresh didn't contain access token: {parsed}", parsed=parsed)
return False
else:
self.log.error(f"Cannot refresh token: {parsed}", parsed=parsed)
return False
2022-02-28 20:03:21 +00:00
def get_accounts(self):
2022-02-28 20:03:21 +00:00
"""
Get a list of accounts.
2022-02-28 20:03:21 +00:00
"""
headers = {"Authorization": f"Bearer {self.token}"}
2022-03-04 21:06:54 +00:00
path = f"{settings.TrueLayer.DataBase}/accounts"
r = requests.get(path, headers=headers)
2022-02-28 20:03:21 +00:00
try:
parsed = r.json()
except JSONDecodeError:
self.log.error("Error parsing institutions response: {content}", content=r.content)
return False
2022-03-04 21:06:54 +00:00
2022-02-28 20:03:21 +00:00
return parsed