2022-02-28 20:03:21 +00:00
|
|
|
# Twisted/Klein imports
|
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
|
2022-03-01 20:39:22 +00:00
|
|
|
from time import time
|
2022-03-06 18:51:16 +00:00
|
|
|
from json import dumps, loads
|
2022-03-01 20:39:22 +00:00
|
|
|
import urllib
|
2022-02-28 20:03:21 +00:00
|
|
|
|
|
|
|
# Project imports
|
|
|
|
from settings import settings
|
2022-03-05 21:52:31 +00:00
|
|
|
import util
|
2022-02-28 20:03:21 +00:00
|
|
|
|
|
|
|
|
2022-03-05 21:52:31 +00:00
|
|
|
class TrueLayer(util.Base):
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
|
|
|
Class to manage calls to Open Banking APIs through TrueLayer.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
2022-03-05 21:52:31 +00:00
|
|
|
super().__init__()
|
2022-03-06 18:51:16 +00:00
|
|
|
self.tokens = {}
|
|
|
|
|
|
|
|
# account we are authenticating - where to store the refresh keys
|
|
|
|
self.current_authcode_account = None
|
|
|
|
self.lc = LoopingCall(self.get_new_tokens_all)
|
2022-03-04 21:06:54 +00:00
|
|
|
self.lc.start(int(settings.TrueLayer.RefreshSec))
|
2022-02-28 20:03:21 +00:00
|
|
|
|
2022-03-06 18:51:16 +00:00
|
|
|
def add_refresh_token(self, refresh_token):
|
|
|
|
"""
|
|
|
|
Add an API key to the configuration.
|
|
|
|
Data type: {"monzo": refresh_token,
|
|
|
|
"revolut": refresh_token}
|
|
|
|
"""
|
|
|
|
account = self.current_authcode_account
|
|
|
|
if not account:
|
|
|
|
return False
|
|
|
|
existing_entry = loads(settings.TrueLayer.RefreshKeys)
|
|
|
|
existing_entry[account] = refresh_token
|
|
|
|
settings.TrueLayer.RefreshKeys = dumps(existing_entry)
|
|
|
|
settings.write()
|
|
|
|
|
|
|
|
def get_refresh_tokens(self):
|
|
|
|
existing_entry = loads(settings.TrueLayer.RefreshKeys)
|
|
|
|
return existing_entry
|
|
|
|
|
|
|
|
def get_key(self, account):
|
|
|
|
if account in self.tokens:
|
|
|
|
return self.tokens[account]
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def create_auth_url(self, account):
|
2022-03-01 20:39:22 +00:00
|
|
|
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}"
|
2022-03-06 18:51:16 +00:00
|
|
|
self.current_authcode_account = account
|
2022-03-01 20:39:22 +00:00
|
|
|
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,
|
2022-03-01 20:39:22 +00:00
|
|
|
"code": authcode,
|
|
|
|
"grant_type": "authorization_code",
|
|
|
|
"redirect_uri": settings.TrueLayer.CallbackURL,
|
2022-02-28 20:03:21 +00:00
|
|
|
}
|
2022-03-01 20:39:22 +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
|
2022-03-01 20:39:22 +00:00
|
|
|
if "error" in parsed:
|
2022-03-06 18:51:16 +00:00
|
|
|
self.log.error("Error requesting refresh token: {parsed['error']}")
|
2022-02-28 20:03:21 +00:00
|
|
|
return False
|
|
|
|
|
2022-03-06 18:51:16 +00:00
|
|
|
# Extract the access tokens
|
|
|
|
refresh_token = parsed["refresh_token"]
|
|
|
|
access_token = parsed["access_token"]
|
|
|
|
|
|
|
|
# Add the refresh token
|
|
|
|
self.add_refresh_token(refresh_token)
|
|
|
|
|
|
|
|
# Add the access
|
|
|
|
if self.current_authcode_account:
|
|
|
|
self.tokens[self.current_authcode_account] = access_token
|
|
|
|
else:
|
|
|
|
self.log.error(f"Received an authcode we didn't ask for")
|
|
|
|
return
|
|
|
|
self.log.info(f"Retrieved access/refresh tokens for {self.current_authcode_account}")
|
|
|
|
|
|
|
|
def get_new_tokens_all(self):
|
|
|
|
refresh_list = loads(settings.TrueLayer.RefreshKeys)
|
|
|
|
for account in refresh_list:
|
|
|
|
self.get_new_token(account)
|
|
|
|
|
|
|
|
def get_new_token(self, account):
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
|
|
|
Exchange our refresh token for an access token.
|
2022-03-06 18:51:16 +00:00
|
|
|
:param account: account to refresh the token for
|
|
|
|
:type account:
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
2022-03-06 18:51:16 +00:00
|
|
|
refresh_tokens = self.get_refresh_tokens()
|
|
|
|
if account not in refresh_tokens:
|
2022-03-01 20:39:22 +00:00
|
|
|
return
|
2022-03-06 18:51:16 +00:00
|
|
|
|
2022-02-28 20:09:19 +00:00
|
|
|
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
|
|
data = {
|
|
|
|
"grant_type": "refresh_token",
|
2022-03-06 18:51:16 +00:00
|
|
|
"refresh_token": refresh_tokens[account],
|
2022-02-28 20:09:19 +00:00
|
|
|
"client_id": settings.TrueLayer.ID,
|
|
|
|
"client_secret": settings.TrueLayer.Key,
|
|
|
|
}
|
2022-03-01 20:39:22 +00:00
|
|
|
r = requests.post(f"{settings.TrueLayer.AuthBase}/connect/token", data=data, headers=headers)
|
2022-02-28 20:09:19 +00:00
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
|
|
|
return False
|
|
|
|
if r.status_code == 200:
|
|
|
|
if "access_token" in parsed.keys():
|
2022-03-06 18:51:16 +00:00
|
|
|
self.tokens[account] = parsed["access_token"]
|
|
|
|
self.log.info(f"Refreshed access token for {account}")
|
2022-02-28 20:09:19 +00:00
|
|
|
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
|
|
|
|
2022-03-06 18:51:16 +00:00
|
|
|
def get_accounts(self, account):
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
2022-03-01 20:39:22 +00:00
|
|
|
Get a list of accounts.
|
2022-02-28 20:03:21 +00:00
|
|
|
"""
|
2022-03-06 18:51:16 +00:00
|
|
|
token = self.get_key(account)
|
|
|
|
headers = {"Authorization": f"Bearer {token}"}
|
2022-03-04 21:06:54 +00:00
|
|
|
path = f"{settings.TrueLayer.DataBase}/accounts"
|
2022-03-01 20:39:22 +00:00
|
|
|
r = requests.get(path, headers=headers)
|
2022-02-28 20:03:21 +00:00
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.error("Error parsing accounts response: {content}", content=r.content)
|
2022-02-28 20:03:21 +00:00
|
|
|
return False
|
2022-03-04 21:06:54 +00:00
|
|
|
|
2022-02-28 20:03:21 +00:00
|
|
|
return parsed
|
2022-03-05 21:52:31 +00:00
|
|
|
|
2022-03-06 18:51:16 +00:00
|
|
|
def get_transactions(self, account, account_id):
|
2022-03-05 21:52:31 +00:00
|
|
|
"""
|
|
|
|
Get a list of transactions from an account.
|
|
|
|
:param account_id: account to fetch transactions for
|
|
|
|
:return: list of transactions
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
2022-03-06 18:51:16 +00:00
|
|
|
token = self.get_key(account)
|
|
|
|
headers = {"Authorization": f"Bearer {token}"}
|
2022-03-05 21:52:31 +00:00
|
|
|
path = f"{settings.TrueLayer.DataBase}/accounts/{account_id}/transactions"
|
|
|
|
r = requests.get(path, headers=headers)
|
|
|
|
try:
|
|
|
|
parsed = r.json()
|
|
|
|
except JSONDecodeError:
|
|
|
|
self.log.error("Error parsing transactions response: {content}", content=r.content)
|
|
|
|
return False
|
|
|
|
|
|
|
|
return parsed["results"]
|