Merge pull request #2182 from famedly/krille/allow-init-with-access-token

feat: Allow init with access token
This commit is contained in:
Krille-chan 2025-11-10 10:50:18 +01:00 committed by GitHub
commit 3d1aa6607e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 28 additions and 13 deletions

View File

@ -1352,7 +1352,7 @@ class FakeMatrixApi extends BaseClient {
},
},
'/client/v3/account/whoami': (var req) =>
{'user_id': 'alice@example.com'},
{'user_id': 'alice@example.com', 'device_id': 'ABCDEFGH'},
'/client/v3/capabilities': (var req) => {
'capabilities': {
'm.change_password': {'enabled': false},

View File

@ -1982,9 +1982,9 @@ class Client extends MatrixApi {
///
/// Sends [LoginState.loggedIn] to [onLoginStateChanged].
///
/// If one of [newToken], [newUserID], [newDeviceID], [newDeviceName] is set then
/// all of them must be set! If you don't set them, this method will try to
/// get them from the database.
/// If one of [newToken] is set, but one of [newUserID], [newDeviceID] is
/// null, then this method calls `/whoami` to fetch user ID and device ID
/// and rethrows if this request fails.
///
/// Set [waitForFirstSync] and [waitUntilLoadCompletedLoaded] to false to speed this
/// up. You can then wait for `roomsLoading`, `_accountDataLoading` and
@ -2008,16 +2008,9 @@ class Client extends MatrixApi {
/// To track what actually happens you can set a callback here.
void Function(InitState)? onInitStateChanged,
}) async {
if ((newToken != null ||
newUserID != null ||
newDeviceID != null ||
newDeviceName != null) &&
(newToken == null ||
newUserID == null ||
newDeviceID == null ||
newDeviceName == null)) {
if (newToken != null && homeserver == null && newHomeserver == null) {
throw ClientInitPreconditionError(
'If one of [newToken, newUserID, newDeviceID, newDeviceName] is set then all of them must be set!',
'init() can not be performed with an access token when no homeserver was specified.',
);
}
@ -2109,6 +2102,12 @@ class Client extends MatrixApi {
return;
}
if (accessToken != null && (userID == null || deviceID == null)) {
final userInfo = await getTokenOwner();
_userID = userID = userInfo.userId;
_deviceID = userInfo.deviceId;
}
if (accessToken == null || homeserver == null || userID == null) {
if (legacyDatabaseBuilder != null) {
await _migrateFromLegacyDatabase(

View File

@ -524,6 +524,22 @@ void main() {
FakeMatrixApi.currentApi?.api = oldapi!;
});
test('init() with access token', () async {
final client = Client(
'testclient',
httpClient: FakeMatrixApi(),
database: await getDatabase(),
);
await client.init(
newToken: 'abcd1234',
newHomeserver: Uri.parse('https://fakeserver.notexisting'),
);
expect(client.isLogged(), true);
expect(client.userID, 'alice@example.com');
expect(client.deviceID, 'ABCDEFGH');
await client.dispose();
});
test('Login', () async {
matrix = Client(
'testclient',