Skip to content

Commit 2dbffb6

Browse files
author
Pavel Kardash
committed
Implement whoami method.
Fetch user_id from server if token provided.
1 parent fdcd726 commit 2dbffb6

File tree

4 files changed

+74
-8
lines changed

4 files changed

+74
-8
lines changed

matrix_client/api.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -993,3 +993,13 @@ def _make_txn_id(self):
993993
txn_id = str(self.txn_id) + str(int(time() * 1000))
994994
self.txn_id += 1
995995
return txn_id
996+
997+
def whoami(self):
998+
"""Determine user_id for authentificated user.
999+
"""
1000+
if not self.token:
1001+
raise MatrixError("Authentification required.")
1002+
return self._send(
1003+
"GET",
1004+
"/account/whoami"
1005+
)

matrix_client/client.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
from .api import MatrixHttpApi
16-
from .checks import check_user_id
1716
from .errors import MatrixRequestError, MatrixUnexpectedResponse
1817
from .room import Room
1918
from .user import User
@@ -54,9 +53,7 @@ class MatrixClient(object):
5453
e.g. (ex: https://localhost:8008 )
5554
token (Optional[str]): If you have an access token
5655
supply it here.
57-
user_id (Optional[str]): You must supply the user_id
58-
(as obtained when initially logging in to obtain
59-
the token) if supplying a token; otherwise, ignored.
56+
user_id (Optional[str]): Optional. Obsolete. For backward compatibility.
6057
valid_cert_check (bool): Check the homeservers
6158
certificate on connections?
6259
cache_level (CACHE): One of CACHE.NONE, CACHE.SOME, or
@@ -115,8 +112,12 @@ def global_callback(incoming_event):
115112
def __init__(self, base_url, token=None, user_id=None,
116113
valid_cert_check=True, sync_filter_limit=20,
117114
cache_level=CACHE.ALL, encryption=False, encryption_conf=None):
118-
if token is not None and user_id is None:
119-
raise ValueError("must supply user_id along with token")
115+
if user_id:
116+
warn(
117+
"user_id is deprecated. "
118+
"Now it is requested from the server.", DeprecationWarning
119+
)
120+
120121
if encryption and not ENCRYPTION_SUPPORT:
121122
raise ValueError("Failed to enable encryption. Please make sure the olm "
122123
"library is available.")
@@ -155,8 +156,8 @@ def __init__(self, base_url, token=None, user_id=None,
155156
# user_id: User
156157
}
157158
if token:
158-
check_user_id(user_id)
159-
self.user_id = user_id
159+
response = self.api.whoami()
160+
self.user_id = response["user_id"]
160161
self._sync()
161162

162163
def get_sync_token(self):

test/api_test.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,3 +405,36 @@ def test_create_room_federate_false(self):
405405
assert req.method == 'POST'
406406
j = json.loads(req.body)
407407
assert not j["creation_content"]["m.federate"]
408+
409+
410+
class TestWhoamiQuery:
411+
user_id = "@alice:example.com"
412+
token = "Dp0YKRXwx0iWDhFj7lg3DVjwsWzGcUIgARljgyAip2JD8qd5dSaW" \
413+
"cxowTKEFetPulfLijAhv8eOmUSScyGcWgZyNMRTBmoJ0RFc0HotPvTBZ" \
414+
"U98yKRLtat7V43aCpFmK"
415+
416+
@responses.activate
417+
def test_whoami(self):
418+
mapi = api.MatrixHttpApi("http://example.com", token=self.token)
419+
whoami_url = "http://example.com/_matrix/client/r0/account/whoami"
420+
responses.add(
421+
responses.GET,
422+
whoami_url,
423+
body='{"user_id": "%s"}' % self.user_id
424+
)
425+
mapi.whoami()
426+
req = responses.calls[0].request
427+
assert req.method == 'GET'
428+
assert whoami_url in req.url
429+
430+
@responses.activate
431+
def test_whoami_unauth(self):
432+
mapi = api.MatrixHttpApi("http://example.com")
433+
whoami_url = "http://example.com/_matrix/client/r0/account/whoami"
434+
responses.add(
435+
responses.GET,
436+
whoami_url,
437+
body='{"user_id": "%s"}' % self.user_id
438+
)
439+
with pytest.raises(MatrixError):
440+
mapi.whoami()

test/client_test.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,28 @@ def test_create_client():
1717
MatrixClient("http://example.com")
1818

1919

20+
@responses.activate
21+
def test_create_client_with_token():
22+
user_id = "@alice:example.com"
23+
token = "Dp0YKRXwx0iWDhFj7lg3DVjwsWzGcUIgARljgyAip2JD8qd5dSaW" \
24+
"cxowTKEFetPulfLijAhv8eOmUSScyGcWgZyNMRTBmoJ0RFc0HotPvTBZ" \
25+
"U98yKRLtat7V43aCpFmK"
26+
whoami_url = HOSTNAME+MATRIX_V2_API_PATH+"/account/whoami"
27+
responses.add(
28+
responses.GET,
29+
whoami_url,
30+
body='{"user_id": "%s"}' % user_id
31+
)
32+
sync_response = deepcopy(response_examples.example_sync)
33+
response_body = json.dumps(sync_response)
34+
sync_url = HOSTNAME + MATRIX_V2_API_PATH + "/sync"
35+
responses.add(responses.GET, sync_url, body=response_body)
36+
MatrixClient(HOSTNAME, token=token)
37+
req = responses.calls[0].request
38+
assert req.method == 'GET'
39+
assert whoami_url in req.url
40+
41+
2042
def test_sync_token():
2143
client = MatrixClient("http://example.com")
2244
assert client.get_sync_token() is None

0 commit comments

Comments
 (0)