Handle authentication errors better.
[fulbank.git] / fulbank / fsb.py
1 import json, http.cookiejar, binascii, time, datetime, pickle, urllib.error
2 from urllib import request, parse
3 from bs4 import BeautifulSoup as soup
4 from . import currency, auth, data
5 soupify = lambda cont: soup(cont, "html.parser")
6
7 apibase = "https://online.swedbank.se/TDE_DAP_Portal_REST_WEB/api/"
8 loginurl = "https://online.swedbank.se/app/privat/login"
9 serviceid = "B7dZHQcY78VRVz9l"
10
11 class fmterror(Exception):
12     pass
13
14 class autherror(auth.autherror):
15     pass
16
17 class jsonerror(Exception):
18     def __init__(self, code, data, headers):
19         self.code = code
20         self.data = data
21         self.headers = headers
22
23     @classmethod
24     def fromerr(cls, err):
25         cs = err.headers.get_content_charset()
26         if cs is None:
27             cs = "utf-8"
28         data = json.loads(err.read().decode(cs))
29         return cls(err.code, data, err.headers)
30
31 def resolve(d, keys, default=fmterror):
32     def err(key):
33         if default is fmterror:
34             raise fmterror(key)
35         return default
36     def rec(d, keys):
37         if len(keys) == 0:
38             return d
39         if isinstance(d, dict):
40             if keys[0] not in d:
41                 return err(keys[0])
42             return rec(d[keys[0]], keys[1:])
43         elif isinstance(d, list):
44             if not 0 <= keys[0] < len(d):
45                 return err(keys[0])
46             return rec(d[keys[0]], keys[1:])
47         else:
48             return err(keys[0])
49     return rec(d, keys)
50
51 def linkurl(ln):
52     if ln[0] != '/':
53         raise fmterror("unexpected link url: " + ln)
54     return parse.urljoin(apibase, ln[1:])
55
56 def getdsid():
57     with request.urlopen(loginurl) as resp:
58         if resp.code != 200:
59             raise fmterror("Unexpected HTTP status code: " + str(resp.code))
60         doc = soupify(resp.read())
61     dsel = doc.find("div", id="cust-sess-id")
62     if not dsel or not dsel.has_attr("value"):
63         raise fmterror("DSID DIV not on login page")
64     return dsel["value"]
65
66 def base64(data):
67     return binascii.b2a_base64(data).decode("ascii").strip().rstrip("=")
68
69 class transaction(data.transaction):
70     def __init__(self, account, data):
71         self.account = account
72         self._data = data
73
74     _datefmt = "%Y-%m-%d"
75
76     @property
77     def value(self): return currency.currency.get(resolve(self._data, ("currency",))).parse(resolve(self._data, ("amount",)))
78     @property
79     def message(self): return resolve(self._data, ("description",))
80     @property
81     def date(self):
82         p = time.strptime(resolve(self._data, ("accountingDate",)), self._datefmt)
83         return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
84
85 class txnaccount(data.txnaccount):
86     def __init__(self, sess, id, idata):
87         self.sess = sess
88         self.id = id
89         self._data = None
90         self._idata = idata
91
92     @property
93     def data(self):
94         if self._data is None:
95             self._data = self.sess._jreq("v5/engagement/account/" + self.id)
96         return self._data
97
98     @property
99     def number(self): return resolve(self.data, ("accountNumber",))
100     @property
101     def clearing(self): return resolve(self.data, ("clearingNumber",))
102     @property
103     def fullnumber(self): return resolve(self.data, ("fullyFormattedNumber",))
104     @property
105     def balance(self): return currency.currency.get(resolve(self.data, ("balance", "currencyCode"))).parse(resolve(self.data, ("balance", "amount")))
106     @property
107     def name(self): return resolve(self._idata, ("name",))
108
109     def transactions(self):
110         pagesz = 50
111         page = 1
112         while True:
113             data = self.sess._jreq("v5/engagement/transactions/" + self.id, transactionsPerPage=pagesz, page=page)
114             txlist = resolve(data, ("transactions",))
115             if len(txlist) < 1:
116                 break
117             for tx in txlist:
118                 yield transaction(self, tx)
119             page += 1
120
121 class cardtransaction(data.transaction):
122     def __init__(self, account, data):
123         self.account = account
124         self._data = data
125
126     _datefmt = "%Y-%m-%d"
127
128     @property
129     def value(self):
130         am = resolve(self._data, ("localAmount",))
131         return currency.currency.get(resolve(am, ("currencyCode",))).parse(resolve(am, ("amount",)))
132     @property
133     def message(self): return resolve(self._data, ("description",))
134     @property
135     def date(self):
136         p = time.strptime(resolve(self._data, ("date",)), self._datefmt)
137         return datetime.date(p.tm_year, p.tm_mon, p.tm_mday)
138
139 class cardaccount(data.cardaccount):
140     def __init__(self, sess, id, idata):
141         self.sess = sess
142         self.id = id
143         self._data = None
144         self._idata = idata
145
146     @property
147     def data(self):
148         if self._data is None:
149             self._data = self.sess._jreq("v5/engagement/cardaccount/" + self.id)
150         return self._data
151
152     @property
153     def number(self): return resolve(self.data, ("cardAccount", "cardNumber"))
154     @property
155     def balance(self):
156         cc = resolve(self.data, ("transactions", 0, "localAmount", "currencyCode"))
157         return currency.currency.get(cc).parse(resolve(self.data, ("cardAccount", "currentBalance")))
158     @property
159     def name(self): return resolve(self._idata, ("name",))
160
161     def transactions(self):
162         pagesz = 50
163         page = 1
164         while True:
165             data = self.sess._jreq("v5/engagement/cardaccount/" + self.id, transactionsPerPage=pagesz, page=page)
166             txlist = resolve(data, ("transactions",))
167             if len(txlist) < 1:
168                 break
169             for tx in txlist:
170                 yield cardtransaction(self, tx)
171             page += 1
172
173 class session(object):
174     def __init__(self, dsid):
175         self.dsid = dsid
176         self.auth = base64((serviceid + ":" + str(int(time.time() * 1000))).encode("ascii"))
177         self.jar = request.HTTPCookieProcessor()
178         self.jar.cookiejar.set_cookie(http.cookiejar.Cookie(
179             version=0, name="dsid", value=dsid, path="/", path_specified=True,
180             domain=".online.swedbank.se", domain_specified=True, domain_initial_dot=True,
181             port=None, port_specified=False, secure=False, expires=None,
182             discard=True, comment=None, comment_url=None,
183             rest={}, rfc2109=False))
184         self.userid = None
185         self._accounts = None
186
187     def _req(self, url, data=None, ctype=None, headers={}, method=None, **kws):
188         if "dsid" not in kws:
189             kws["dsid"] = self.dsid
190         kws = {k: v for (k, v) in kws.items() if v is not None}
191         url = parse.urljoin(apibase, url + "?" + parse.urlencode(kws))
192         if isinstance(data, dict):
193             data = json.dumps(data).encode("utf-8")
194             ctype = "application/json;charset=UTF-8"
195         req = request.Request(url, data=data, method=method)
196         for hnam, hval in headers.items():
197             req.add_header(hnam, hval)
198         if ctype is not None:
199             req.add_header("Content-Type", ctype)
200         req.add_header("Authorization", self.auth)
201         self.jar.https_request(req)
202         with request.urlopen(req) as resp:
203             if resp.code != 200 and resp.code != 201:
204                 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
205             self.jar.https_response(req, resp)
206             return resp.read()
207
208     def _jreq(self, *args, **kwargs):
209         headers = kwargs.pop("headers", {})
210         headers["Accept"] = "application/json"
211         try:
212             ret = self._req(*args, headers=headers, **kwargs)
213         except urllib.error.HTTPError as e:
214             if e.headers.get_content_type() == "application/json":
215                 raise jsonerror.fromerr(e)
216         return json.loads(ret.decode("utf-8"))
217
218     def _postlogin(self):
219         auth = self._jreq("v5/user/authenticationinfo")
220         uid = auth.get("identifiedUser", "")
221         if uid == "":
222             raise fmterror("no identified user even after successful authentication")
223         self.userid = uid
224         prof = self._jreq("v5/profile/")
225         if len(prof["banks"]) != 1:
226             raise fmterror("do not know the meaning of multiple banks")
227         rolesw = linkurl(resolve(prof["banks"][0], ("privateProfile", "links", "next", "uri")))
228         self._jreq(rolesw, method="POST")
229
230     def auth_bankid(self, user, conv=None):
231         if conv is None:
232             conv = auth.default()
233         try:
234             data = self._jreq("v5/identification/bankid/mobile", data = {
235                 "userId": user,
236                 "useEasyLogin": False,
237                 "generateEasyLoginId": False})
238         except jsonerror as e:
239             if e.code == 400:
240                 flds = resolve(e.data, ("errorMessages", "fields"), False)
241                 if isinstance(flds, list):
242                     for fld in flds:
243                         if resolve(fld, ("field",), None) == "userId":
244                             raise autherror(fld["message"])
245             raise
246         if data.get("status") != "USER_SIGN":
247             raise fmterror("unexpected bankid status: " + str(data.get("status")))
248         vfy = linkurl(resolve(data, ("links", "next", "uri")))
249         fst = None
250         while True:
251             time.sleep(3)
252             vdat = self._jreq(vfy)
253             st = vdat.get("status")
254             if st in {"USER_SIGN", "CLIENT_NOT_STARTED"}:
255                 if st != fst:
256                     conv.message("Status: %s" % (st,), auth.conv.msg_info)
257                     fst = st
258                 continue
259             elif st == "COMPLETE":
260                 self._postlogin()
261                 return
262             elif st == "CANCELLED":
263                 raise autherror("authentication cancelled")
264             else:
265                 raise fmterror("unexpected bankid status: " + str(st))
266
267     def keepalive(self):
268         data = self._jreq("v5/framework/clientsession")
269         return data["timeoutInMillis"] / 1000
270
271     @property
272     def accounts(self):
273         if self._accounts is None:
274             data = self._jreq("v5/engagement/overview")
275             accounts = []
276             for acct in resolve(data, ("transactionAccounts",)):
277                 accounts.append(txnaccount(self, resolve(acct, ("id",)), acct))
278             for acct in resolve(data, ("cardAccounts",)):
279                 accounts.append(cardaccount(self, resolve(acct, ("id",)), acct))
280             self._accounts = accounts
281         return self._accounts
282
283     def logout(self):
284         if self.userid is not None:
285             self._jreq("v5/identification/logout", method="PUT")
286             self.userid = None
287
288     def close(self):
289         self.logout()
290         self._req("v5/framework/clientsession", method="DELETE")
291
292     def __enter__(self):
293         return self
294
295     def __exit__(self, *excinfo):
296         self.close()
297         return False
298
299     def __repr__(self):
300         if self.userid is not None:
301             return "#<fsb.session %s>" % self.userid
302         return "#<fsb.session>"
303
304     @classmethod
305     def create(cls):
306         return cls(getdsid())
307
308     def save(self, filename):
309         with open(filename, "wb") as fp:
310             pickle.dump(self, fp)
311
312     @classmethod
313     def load(cls, filename):
314         with open(filename, "rb") as fp:
315             return pickle.load(fp)