1 import json, http.cookiejar, binascii, time, datetime, pickle, hashlib
2 from urllib import request, parse
3 from bs4 import BeautifulSoup as soup
5 soupify = lambda cont: soup(cont, "html.parser")
7 apibase = "https://online.swedbank.se/TDE_DAP_Portal_REST_WEB/api/"
8 loginurl = "https://online.swedbank.se/app/privat/login"
9 serviceid = "B7dZHQcY78VRVz9l"
11 class fmterror(Exception):
14 class autherror(Exception):
17 def resolve(d, keys, default=fmterror):
19 if default is fmterror:
25 if isinstance(d, dict):
28 return rec(d[keys[0]], keys[1:])
35 raise fmterror("unexpected link url: " + ln)
36 return parse.urljoin(apibase, ln[1:])
39 with request.urlopen(loginurl) as resp:
41 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
42 doc = soupify(resp.read())
43 dsel = doc.find("div", id="cust-sess-id")
44 if not dsel or not dsel.has_attr("value"):
45 raise fmterror("DSID DIV not on login page")
49 return binascii.b2a_base64(data).decode("ascii").strip().rstrip("=")
51 class transaction(object):
52 def __init__(self, account, data):
53 self.account = account
59 def value(self): return currency.currency.get(resolve(self._data, ("currency",))).parse(resolve(self._data, ("amount",)))
61 def message(self): return resolve(self._data, ("description",))
64 p = time.strptime(resolve(self._data, ("accountingDate",)), self._datefmt)
65 return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
69 dig = hashlib.sha256()
70 dig.update(str(self.date.toordinal()).encode("ascii") + b"\0")
71 dig.update(self.message.encode("utf-8") + b"\0")
72 dig.update(str(self.value.amount).encode("ascii") + b"\0")
73 dig.update(self.value.currency.symbol.encode("ascii") + b"\0")
74 return dig.hexdigest()
77 return "#<fsb.transaction %s: %r>" % (self.value, self.message)
79 class account(object):
80 def __init__(self, sess, id, idata):
88 if self._data is None:
89 self._data = self.sess._jreq("v5/engagement/account/" + self.id)
93 def number(self): return resolve(self.data, ("accountNumber",))
95 def clearing(self): return resolve(self.data, ("clearingNumber",))
97 def fullnumber(self): return resolve(self.data, ("fullyFormattedNumber",))
99 def name(self): return resolve(self._idata, ("name",))
101 def transactions(self):
105 data = self.sess._jreq("v5/engagement/transactions/" + self.id, transactionsPerPage=pagesz, page=page)
106 txlist = resolve(data, ("transactions",))
110 yield transaction(self, tx)
114 return "#<fsb.account %s: %r>" % (self.fullnumber, self.name)
116 class session(object):
117 def __init__(self, dsid):
119 self.auth = base64((serviceid + ":" + str(int(time.time() * 1000))).encode("ascii"))
120 self.jar = request.HTTPCookieProcessor()
121 self.jar.cookiejar.set_cookie(http.cookiejar.Cookie(
122 version=0, name="dsid", value=dsid, path="/", path_specified=True,
123 domain=".online.swedbank.se", domain_specified=True, domain_initial_dot=True,
124 port=None, port_specified=False, secure=False, expires=None,
125 discard=True, comment=None, comment_url=None,
126 rest={}, rfc2109=False))
128 self._accounts = None
130 def _req(self, url, data=None, ctype=None, headers={}, method=None, **kws):
131 if "dsid" not in kws:
132 kws["dsid"] = self.dsid
133 kws = {k: v for (k, v) in kws.items() if v is not None}
134 url = parse.urljoin(apibase, url + "?" + parse.urlencode(kws))
135 if isinstance(data, dict):
136 data = json.dumps(data).encode("utf-8")
137 ctype = "application/json;charset=UTF-8"
138 req = request.Request(url, data=data, method=method)
139 for hnam, hval in headers.items():
140 req.add_header(hnam, hval)
141 if ctype is not None:
142 req.add_header("Content-Type", ctype)
143 req.add_header("Authorization", self.auth)
144 self.jar.https_request(req)
145 with request.urlopen(req) as resp:
146 if resp.code != 200 and resp.code != 201:
147 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
148 self.jar.https_response(req, resp)
151 def _jreq(self, *args, **kwargs):
152 headers = kwargs.pop("headers", {})
153 headers["Accept"] = "application/json"
154 ret = self._req(*args, headers=headers, **kwargs)
155 return json.loads(ret.decode("utf-8"))
157 def _postlogin(self):
158 auth = self._jreq("v5/user/authenticationinfo")
159 uid = auth.get("identifiedUser", "")
161 raise fmterror("no identified user even after successful authentication")
163 prof = self._jreq("v5/profile/")
164 if len(prof["banks"]) != 1:
165 raise fmterror("do not know the meaning of multiple banks")
166 rolesw = linkurl(resolve(prof["banks"][0], ("privateProfile", "links", "next", "uri")))
167 self._jreq(rolesw, method="POST")
169 def auth_bankid(self, user):
170 data = self._jreq("v5/identification/bankid/mobile", data = {
172 "useEasyLogin": False,
173 "generateEasyLoginId": False})
174 if data.get("status") != "USER_SIGN":
175 raise fmterror("unexpected bankid status: " + str(data.get("status")))
176 vfy = linkurl(resolve(data, ("links", "next", "uri")))
179 vdat = self._jreq(vfy)
180 st = vdat.get("status")
181 if st == "USER_SIGN":
183 elif st == "CLIENT_NOT_STARTED":
185 elif st == "COMPLETE":
188 elif st == "CANCELLED":
189 raise autherror("authentication cancelled")
191 raise fmterror("unexpected bankid status: " + str(st))
194 data = self._jreq("v5/framework/clientsession")
195 return data["timeoutInMillis"] / 1000
199 if self._accounts is None:
200 data = self._jreq("v5/engagement/overview")
202 for acct in resolve(data, ("transactionAccounts",)):
203 accounts.append(account(self, resolve(acct, ("id",)), acct))
204 self._accounts = accounts
205 return self._accounts
208 if self.userid is not None:
209 self._jreq("v5/identification/logout", method="PUT")
214 self._req("v5/framework/clientsession", method="DELETE")
219 def __exit__(self, *excinfo):
224 if self.userid is not None:
225 return "#<fsb.session %s>" % self.userid
226 return "#<fsb.session>"
230 return cls(getdsid())
232 def save(self, filename):
233 with open(filename, "wb") as fp:
234 pickle.dump(self, fp)
237 def load(cls, filename):
238 with open(filename, "rb") as fp:
239 return picke.load(fp)