Skip to content

Commit

Permalink
wip model to abstract banking apis, add useraccount via cli
Browse files Browse the repository at this point in the history
Signed-off-by: Robert Hirsch <[email protected]>
  • Loading branch information
hirschrobert committed Feb 16, 2021
1 parent b0dd69f commit 9516f83
Show file tree
Hide file tree
Showing 9 changed files with 258 additions and 139 deletions.
2 changes: 1 addition & 1 deletion src/controller/apirequests.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ def getAccessTokenByIban(self, iban):
account = db().getAccountByIban(iban)
access_token = account.getAccessToken()
# TODO: also new token when scope changed
#if not hasattr(access_token , 'expires_in'):
if not 'expires_in' in access_token:
print("getting new token")
access_token = Authorize().getNewAccessToken(account)
Expand All @@ -52,6 +51,7 @@ def getAccessTokenByIban(self, iban):
return access_token

def makeRequest(self, payload, endpoint):
#get api model of bank_name
apirequest = self.api + endpoint
access_token = self.getAccessTokenByIban(payload['iban'])
headers = {
Expand Down
38 changes: 27 additions & 11 deletions src/controller/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,15 @@ def insertTransactions(self, transactions):

def insertAccount(self, accountdata):
# only deutsche bank
# accountdata = json.loads(accountdata)
usernameConcatenated = "/db" + accountdata['input_branch'] + accountdata['input_account'] + accountdata['input_subaccount']
try:
newAccount = Account(username=usernameConcatenated, password=accountdata['password'], access_token={"hello":"world"})
newAccount.bank = self.getBankByName(accountdata['bank'])
newAccount = Account(username=accountdata['username'], password=accountdata['password'], access_token={"hello":"world"})
bankofaccount = self.getBankByBic(accountdata['bic'])
newAccount.setBank(bankofaccount)
newIbans = []
for iban in accountdata['ibans']:
newIbans.append(Iban(iban=iban))
ibanofaccount = Iban(iban=iban)
ibanofaccount.setBank(bankofaccount)
newIbans.append(ibanofaccount)
newAccount.ibans = newIbans
self.session.add(newAccount)
self.session.commit()
Expand All @@ -71,6 +72,7 @@ def insertBank(self, bankdata):
authorize_endpoint=bankdata['authorize_endpoint'],
tokenurl=bankdata['tokenurl'],
apiurl=bankdata['apiurl'],
accountInput=bankdata['accountInput'],
requests=bankdata['requests']
)
self.session.add(newBank)
Expand All @@ -79,12 +81,26 @@ def insertBank(self, bankdata):
self.session.rollback()
raise Exception("Could not insert bank")

def getBankByName(self, name):
bank = self.session.query(Bank) \
.filter(Bank.name == name) \
.first()

return bank
def getBankByIban(self, iban):
try:
bank = self.session.query(Bank) \
.join(Iban, Bank.ibans) \
.filter(Iban.iban == iban) \
.one_or_none()
print(bank)
return bank
except:
raise Exception("Could not find bank by iban")

def getBankByBic(self, bic):
try:
# bic[:6] = only use four letter bank id and two letter country id
bank = self.session.query(Bank) \
.filter(Bank.bic.like(bic[:6] + '%'))\
.one_or_none()
return bank
except:
raise Exception("Could not find bank by bic")

def getAccountByIban(self, iban):
account = self.session.query(Account) \
Expand Down
62 changes: 2 additions & 60 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,71 +18,13 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#

from pybank import Pb
import argparse, sys


def license(args):
if args.warranty:
f = open('WARRANTY.md', 'r')
elif args.copyright:
f = open('LICENSE.md', 'r')
print(f.read())
f.close()

def transactions(args):
if args.iban:
Pb().setTransactionsbyIban(args.iban)


def parse_args():

parser = argparse.ArgumentParser(description="stand up an lxc container")
#parser.print_usage = parser.print_help

parser.add_argument("-c", "--copyright", action='store_true', help="show copyright infos")
parser.add_argument("-w", "--warranty", action='store_true', help="show warranty infos")

parser.set_defaults(func=license)

subparsers = parser.add_subparsers(help="sub command help")
parser_ca = subparsers.add_parser("cash-accounts", help="get list of cash accounts by username and bank")
parser_ca.add_argument("-u", "--username", required=True, action='store_true', help="show copyright infos")
parser_ca.add_argument("-b", "--bank", action='store_true', help="show warranty infos")
#parser_ca.set_defaults(func=Pb.getCashAccounts)
parser_s = subparsers.add_parser("solvency", help="get solvency score of iban owner by iban")
parser_s.add_argument("-i", "--iban", required=True, action='store', help="show copyright infos")
#parser_s.set_defaults(func=Pb.getSolvencybyIban)
parser_t = subparsers.add_parser("transactions", help="get transactions by iban")
parser_t.add_argument("-i", "--iban", required=True, action='store', help="show copyright infos")
parser_t.add_argument("--from", action='store_true', help="show copyright infos")
parser_t.add_argument("--to", action='store_true', help="show copyright infos")
parser_t.set_defaults(func=transactions)

parsed_args = parser.parse_args()

if len(sys.argv)==1:
parser.print_help(sys.stderr)
sys.exit(1)

parsed_args.func(parsed_args)

return parser.parse_known_args()
from pybanking import Pb


def main():
args, unknown = parse_args()
args, unknown = Pb().parse_args()


if __name__ == "__main__":
print('''
pybanking Copyright (C) 2021 Robert Hirsch
This program comes with ABSOLUTELY NO WARRANTY; for details type \'-w\'.
This is free software, and you are welcome to redistribute it under certain conditions; type \'-c\' for details.
''')

main()



#Pb.setAccount(accountdata)
5 changes: 3 additions & 2 deletions src/model/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

class Account(Base):
__tablename__ = 'accounts'
# __table_args__ = (UniqueConstraint('username', 'bank'),)
__table_args__ = (UniqueConstraint('username', 'bank_id', name='account_uc'),)

id = Column(Integer, primary_key=True)
Expand All @@ -38,13 +37,15 @@ class Account(Base):
ibans = relationship("Iban", back_populates="account")
bank_id = Column(Integer, ForeignKey('banks.id'))
bank = relationship("Bank", back_populates="accounts")
#bank = relationship("Bank")

def __init__(self, username, password, access_token):
self.username = username
self.password = password
self.access_token = access_token

def setBank(self, bank):
self.bank = bank

def getAccessToken(self):
return self.access_token

Expand Down
9 changes: 6 additions & 3 deletions src/model/bank.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,19 @@ class Bank(Base):
authorize_endpoint = Column(String)
tokenurl = Column(String)
apiurl = Column(String)
accountInput = Column(JSON)
requests = Column(JSON)
ibans = relationship("Iban", back_populates="bank")
#ibans = relationship("Iban")
ibans_id = Column(Integer, ForeignKey('ibans.id'))
accounts = relationship("Account", back_populates="bank")

def __init__(self, bic, name, authorize_endpoint, tokenurl, apiurl, requests):
def __init__(self, bic, name, authorize_endpoint, tokenurl, apiurl, accountInput, requests):
self.bic = bic
self.name = name
self.authorize_endpoint = authorize_endpoint
self.tokenurl = tokenurl
self.apiurl = apiurl
self.accountInput = accountInput
self.requests = requests

def getAccountInput(self):
return self.accountInput
58 changes: 58 additions & 0 deletions src/model/bankapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
# -*- Mode:Python; encoding:utf8 -*-
#
# pybanking - a banking backend client at your service
# Copyright (C) 2021 Robert Hirsch <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#

class Model():

def __init__(self, bank):
self.bank = bank

def userArgsToModelParams(self, method, userparams):
if method == 'setTransactionsbyIban':
userparams['limit'] = '200'
endpoint = self.bank.requests['transactions']['endpoint']
bankparams = self.bank.requests['transactions']['params']
print(self.bank.requests['transactions']['params'])
payload = {}
for k, v in bankparams.items():
print(k + ">" + v[0])
if k in userparams:
payload[v[0]] = userparams[k]
userparams.pop(k)
print(userparams)
if userparams:
raise Exception("user input does not match api structure: ", userparams)
pass
print(payload)
return endpoint, payload


def insertUserAccount(self, accountdata):
# usernameConcatenated is only Deutsche Bank, needs to be decoupled
if not 'username' in accountdata:
accountdata['username'] = "/db" + accountdata['input_branch'] + accountdata['input_account'] + accountdata['input_subaccount']
res = {
"username": accountdata['username'],
"password": accountdata['password'],
"ibans": accountdata['ibans'].split(","),
"bic": accountdata['bic']
}

return res

6 changes: 5 additions & 1 deletion src/model/iban.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,13 @@ class Iban(Base):

id = Column(Integer, primary_key=True)
iban = Column(String, unique=True)
bank = relationship("Bank", back_populates="ibans", uselist=False)
bank_id = Column(Integer, ForeignKey('banks.id'))
bank = relationship("Bank", back_populates="ibans")
account_id = Column(Integer, ForeignKey('accounts.id'))
account = relationship("Account", back_populates="ibans")

def __init__(self, iban):
self.iban = iban

def setBank(self, bank):
self.bank = bank
61 changes: 0 additions & 61 deletions src/pybank.py

This file was deleted.

Loading

0 comments on commit 9516f83

Please sign in to comment.