1 import json, http.cookiejar, binascii, time
2 from urllib import request, parse
3 from bs4 import BeautifulSoup as soup
4 soupify = lambda cont: soup(cont, "html.parser")
6 apibase = "https://online.swedbank.se/TDE_DAP_Portal_REST_WEB/api/"
7 loginurl = "https://online.swedbank.se/app/privat/login"
8 serviceid = "B7dZHQcY78VRVz9l"
10 class fmterror(Exception):
13 class autherror(Exception):
16 def resolve(d, keys, default=fmterror):
18 if default is fmterror:
24 if isinstance(d, dict):
27 return rec(d[keys[0]], keys[1:])
34 raise fmterror("unexpected link url: " + ln)
35 return parse.urljoin(apibase, ln[1:])
38 with request.urlopen(loginurl) as resp:
40 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
41 doc = soupify(resp.read())
42 dsel = doc.find("div", id="cust-sess-id")
43 if not dsel or not dsel.has_attr("value"):
44 raise fmterror("DSID DIV not on login page")
48 return binascii.b2a_base64(data).decode("ascii").strip().rstrip("=")
50 class session(object):
51 def __init__(self, dsid):
53 self.auth = base64((serviceid + ":" + str(int(time.time() * 1000))).encode("ascii"))
54 self.jar = request.HTTPCookieProcessor()
55 self.jar.cookiejar.set_cookie(http.cookiejar.Cookie(
56 version=0, name="dsid", value=dsid, path="/", path_specified=True,
57 domain=".online.swedbank.se", domain_specified=True, domain_initial_dot=True,
58 port=None, port_specified=False, secure=False, expires=None,
59 discard=True, comment=None, comment_url=None,
60 rest={}, rfc2109=False))
63 def _req(self, url, data=None, ctype=None, headers={}, method=None, **kws):
65 kws["dsid"] = self.dsid
66 kws = {k: v for (k, v) in kws.items() if v is not None}
67 url = parse.urljoin(apibase, url + "?" + parse.urlencode(kws))
68 if isinstance(data, dict):
69 data = json.dumps(data).encode("utf-8")
70 ctype = "application/json;charset=UTF-8"
71 req = request.Request(url, data=data, method=method)
72 for hnam, hval in headers.items():
73 req.add_header(hnam, hval)
75 req.add_header("Content-Type", ctype)
76 req.add_header("Authorization", self.auth)
77 self.jar.https_request(req)
78 with request.urlopen(req) as resp:
80 raise fmterror("Unexpected HTTP status code: " + str(resp.code))
81 self.jar.https_response(req, resp)
84 def _jreq(self, *args, **kwargs):
85 headers = kwargs.pop("headers", {})
86 headers["Accept"] = "application/json"
87 ret = self._req(*args, headers=headers, **kwargs)
88 return json.loads(ret.decode("utf-8"))
90 def auth_bankid(self, user):
91 data = self._jreq("v5/identification/bankid/mobile", data = {
93 "useEasyLogin": False,
94 "generateEasyLoginId": False})
95 if data.get("status") != "USER_SIGN":
96 raise fmterror("unexpected bankid status: " + str(data.get("status")))
97 vfy = linkurl(resolve(data, ("links", "next", "uri")))
100 vdat = self._jreq(vfy)
101 st = vdat.get("status")
102 if st == "USER_SIGN":
104 elif st == "COMPLETE":
105 auth = self._jreq("v5/user/authenticationinfo")
106 uid = auth.get("identifiedUser", "")
108 raise fmterror("no identified user even after successful authentication")
111 elif st == "CANCELLED":
112 raise autherror("authentication cancelled")
113 elif st == "CLIENT_NOT_STARTED":
114 raise autherror("authentication client not started")
116 raise fmterror("unexpected bankid status: " + str(st))
119 if self.userid is not None:
120 self._jreq("v5/identification/logout", method="PUT")
125 self._req("v5/framework/clientsession", method="DELETE")
130 def __exit__(self, *excinfo):
136 return cls(getdsid())