Skip to content
This repository was archived by the owner on Jun 21, 2019. It is now read-only.

Commit faa050a

Browse files
MrCustomizerMax Dor
MrCustomizer
authored and
Max Dor
committed
Login with password (#10)
1 parent 14c1e36 commit faa050a

14 files changed

+385
-34
lines changed

src/main/java/io/kamax/matrix/client/AMatrixHttpClient.java

+22-7
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,17 @@ public _MatrixHomeserver getHomeserver() {
7474
}
7575

7676
@Override
77-
public String getAccessToken() {
78-
return context.getToken();
77+
public Optional<String> getAccessToken() {
78+
return Optional.ofNullable(context.getToken());
79+
}
80+
81+
public String getAccessTokenOrThrow() {
82+
return getAccessToken()
83+
.orElseThrow(() -> new IllegalStateException("This method can only be used with a valid token."));
7984
}
8085

8186
@Override
82-
public _MatrixID getUser() {
87+
public Optional<_MatrixID> getUser() {
8388
return context.getUser();
8489
}
8590

@@ -233,10 +238,8 @@ private void log(HttpRequestBase req) {
233238
protected URIBuilder getPathBuilder(String module, String version, String action) {
234239
URIBuilder builder = context.getHs().getClientEndpoint();
235240
builder.setPath(builder.getPath() + "/_matrix/" + module + "/" + version + action);
236-
builder.setParameter("access_token", context.getToken());
237-
builder.setPath(builder.getPath().replace("{userId}", context.getUser().getId()));
238241
if (context.isVirtualUser()) {
239-
builder.setParameter("user_id", context.getUser().getId());
242+
context.getUser().ifPresent(user -> builder.setParameter("user_id", user.getId()));
240243
}
241244

242245
return builder;
@@ -250,6 +253,16 @@ protected URIBuilder getMediaPathBuilder(String action) {
250253
return getPathBuilder("media", "v1", action);
251254
}
252255

256+
protected URI getClientPathWithAccessToken(String action) {
257+
try {
258+
URIBuilder builder = getClientPathBuilder(action);
259+
builder.setParameter("access_token", getAccessTokenOrThrow());
260+
return builder.build();
261+
} catch (URISyntaxException e) {
262+
throw new IllegalArgumentException(e);
263+
}
264+
}
265+
253266
protected URI getClientPath(String action) {
254267
try {
255268
return getClientPathBuilder(action).build();
@@ -260,7 +273,9 @@ protected URI getClientPath(String action) {
260273

261274
protected URI getMediaPath(String action) {
262275
try {
263-
return getMediaPathBuilder(action).build();
276+
URIBuilder builder = getMediaPathBuilder(action);
277+
builder.setParameter("access_token", getAccessTokenOrThrow());
278+
return builder.build();
264279
} catch (URISyntaxException e) {
265280
throw new IllegalArgumentException(e);
266281
}

src/main/java/io/kamax/matrix/client/MatrixClientContext.java

+39-4
Original file line numberDiff line numberDiff line change
@@ -23,38 +23,73 @@
2323
import io.kamax.matrix._MatrixID;
2424
import io.kamax.matrix.hs._MatrixHomeserver;
2525

26+
import java.util.Optional;
27+
2628
public class MatrixClientContext {
2729

2830
private _MatrixHomeserver hs;
2931
private _MatrixID user;
3032
private String token;
3133
private boolean isVirtualUser;
34+
private String deviceId;
3235

3336
public MatrixClientContext(_MatrixHomeserver hs, _MatrixID user, String token) {
3437
this(hs, user, token, false);
3538
}
3639

3740
public MatrixClientContext(_MatrixHomeserver hs, _MatrixID user, String token, boolean isVirtualUser) {
38-
this.hs = hs;
39-
this.user = user;
41+
this(hs, user, isVirtualUser);
4042
this.token = token;
43+
}
44+
45+
public MatrixClientContext(_MatrixHomeserver hs) {
46+
this(hs, false);
47+
}
48+
49+
public MatrixClientContext(_MatrixHomeserver hs, String deviceId) {
50+
this(hs, false);
51+
this.deviceId = deviceId;
52+
}
53+
54+
private MatrixClientContext(_MatrixHomeserver hs, _MatrixID user, boolean isVirtualUser) {
55+
this(hs, isVirtualUser);
56+
this.user = user;
57+
}
58+
59+
private MatrixClientContext(_MatrixHomeserver hs, boolean isVirtualUser) {
60+
this.hs = hs;
4161
this.isVirtualUser = isVirtualUser;
4262
}
4363

4464
public _MatrixHomeserver getHs() {
4565
return hs;
4666
}
4767

48-
public _MatrixID getUser() {
49-
return user;
68+
public Optional<_MatrixID> getUser() {
69+
return Optional.ofNullable(user);
70+
}
71+
72+
public void setUser(_MatrixID user) {
73+
this.user = user;
5074
}
5175

5276
public String getToken() {
5377
return token;
5478
}
5579

80+
public void setToken(String token) {
81+
this.token = token;
82+
}
83+
5684
public boolean isVirtualUser() {
5785
return isVirtualUser;
5886
}
5987

88+
public Optional<String> getDeviceId() {
89+
return Optional.ofNullable(deviceId);
90+
}
91+
92+
public void setDeviceId(String deviceId) {
93+
this.deviceId = deviceId;
94+
}
6095
}

src/main/java/io/kamax/matrix/client/MatrixHttpRoom.java

+7-7
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ public class MatrixHttpRoom extends AMatrixHttpClient implements _MatrixRoom {
5151

5252
public MatrixHttpRoom(MatrixClientContext context, String roomId) {
5353
super(context);
54-
5554
this.roomId = roomId;
5655
}
5756

57+
@Override
5858
protected URIBuilder getClientPathBuilder(String action) {
5959
URIBuilder builder = super.getClientPathBuilder(action);
6060
builder.setPath(builder.getPath().replace("{roomId}", roomId));
@@ -69,7 +69,7 @@ public String getAddress() {
6969

7070
@Override
7171
public Optional<String> getName() {
72-
URI path = getClientPath("/rooms/{roomId}/state/m.room.name");
72+
URI path = getClientPathWithAccessToken("/rooms/{roomId}/state/m.room.name");
7373

7474
MatrixHttpRequest request = new MatrixHttpRequest(new HttpGet(path));
7575
request.addIgnoredErrorCode(404);
@@ -79,7 +79,7 @@ public Optional<String> getName() {
7979

8080
@Override
8181
public Optional<String> getTopic() {
82-
URI path = getClientPath("/rooms/{roomId}/state/m.room.topic");
82+
URI path = getClientPathWithAccessToken("/rooms/{roomId}/state/m.room.topic");
8383
MatrixHttpRequest matrixRequest = new MatrixHttpRequest(new HttpGet(path));
8484
matrixRequest.addIgnoredErrorCode(404);
8585
String body = execute(matrixRequest);
@@ -88,13 +88,13 @@ public Optional<String> getTopic() {
8888

8989
@Override
9090
public void join() {
91-
URI path = getClientPath("/rooms/{roomId}/join");
91+
URI path = getClientPathWithAccessToken("/rooms/{roomId}/join");
9292
execute(new HttpPost(path));
9393
}
9494

9595
@Override
9696
public void leave() {
97-
URI path = getClientPath("/rooms/{roomId}/leave");
97+
URI path = getClientPathWithAccessToken("/rooms/{roomId}/leave");
9898
MatrixHttpRequest request = new MatrixHttpRequest(new HttpPost(path));
9999

100100
// TODO Find a better way to handle room objects for unknown rooms
@@ -109,7 +109,7 @@ public void leave() {
109109
}
110110

111111
private void sendMessage(RoomMessageTextPutBody content) {
112-
URI path = getClientPath("/rooms/{roomId}/send/m.room.message/" + System.currentTimeMillis());
112+
URI path = getClientPathWithAccessToken("/rooms/{roomId}/send/m.room.message/" + System.currentTimeMillis());
113113
HttpPut httpPut = new HttpPut(path);
114114
httpPut.setEntity(getJsonEntity(content));
115115
execute(httpPut);
@@ -145,7 +145,7 @@ public void invite(_MatrixID mxId) {
145145

146146
@Override
147147
public List<_MatrixID> getJoinedUsers() {
148-
URI path = getClientPath("/rooms/{roomId}/joined_members");
148+
URI path = getClientPathWithAccessToken("/rooms/{roomId}/joined_members");
149149
String body = execute(new HttpGet(path));
150150

151151
List<_MatrixID> ids = new ArrayList<>();

src/main/java/io/kamax/matrix/client/MatrixHttpUser.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public _MatrixID getId() {
5151

5252
@Override
5353
public Optional<String> getName() {
54-
URI path = getClientPath("/profile/" + mxId.getId() + "/displayname");
54+
URI path = getClientPathWithAccessToken("/profile/" + mxId.getId() + "/displayname");
5555

5656
MatrixHttpRequest request = new MatrixHttpRequest(new HttpGet(path));
5757
request.addIgnoredErrorCode(404);
@@ -61,7 +61,7 @@ public Optional<String> getName() {
6161

6262
@Override
6363
public Optional<_MatrixContent> getAvatar() {
64-
URI path = getClientPath("/profile/" + mxId.getId() + "/avatar_url");
64+
URI path = getClientPathWithAccessToken("/profile/" + mxId.getId() + "/avatar_url");
6565

6666
MatrixHttpRequest request = new MatrixHttpRequest(new HttpGet(path));
6767
request.addIgnoredErrorCode(404);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* matrix-java-sdk - Matrix Client SDK for Java
3+
* Copyright (C) 2017 Arne Augenstein
4+
*
5+
* https://max.kamax.io/
6+
*
7+
* This program is free software: you can redistribute it and/or modify
8+
* it under the terms of the GNU Affero General Public License as
9+
* published by the Free Software Foundation, either version 3 of the
10+
* License, or (at your option) any later version.
11+
*
12+
* This program is distributed in the hope that it will be useful,
13+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
* GNU Affero General Public License for more details.
16+
*
17+
* You should have received a copy of the GNU Affero General Public License
18+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
19+
*/
20+
21+
package io.kamax.matrix.client;
22+
23+
public class MatrixPasswordLoginCredentials {
24+
private final String localPart;
25+
private final String password;
26+
27+
public MatrixPasswordLoginCredentials(String localPart, String password) {
28+
this.localPart = localPart;
29+
this.password = password;
30+
}
31+
32+
public String getLocalPart() {
33+
return localPart;
34+
}
35+
36+
public String getPassword() {
37+
return password;
38+
}
39+
}

src/main/java/io/kamax/matrix/client/_MatrixClient.java

+8
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
import io.kamax.matrix._MatrixUser;
2525
import io.kamax.matrix.hs._MatrixRoom;
2626

27+
import java.util.Optional;
28+
2729
public interface _MatrixClient extends _MatrixClientRaw {
2830

2931
void setDisplayName(String name);
@@ -32,4 +34,10 @@ public interface _MatrixClient extends _MatrixClientRaw {
3234

3335
_MatrixUser getUser(_MatrixID mxId);
3436

37+
Optional<String> getDeviceId();
38+
39+
void login(MatrixPasswordLoginCredentials credentials);
40+
41+
void logout();
42+
3543
}

src/main/java/io/kamax/matrix/client/_MatrixClientRaw.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,15 @@
2323
import io.kamax.matrix._MatrixID;
2424
import io.kamax.matrix.hs._MatrixHomeserver;
2525

26+
import java.util.Optional;
27+
2628
public interface _MatrixClientRaw {
2729

2830
MatrixClientContext getContext();
2931

3032
_MatrixHomeserver getHomeserver();
3133

32-
String getAccessToken();
33-
34-
_MatrixID getUser();
34+
Optional<String> getAccessToken();
3535

36+
Optional<_MatrixID> getUser();
3637
}

src/main/java/io/kamax/matrix/client/as/MatrixApplicationServiceClient.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,13 @@ public MatrixApplicationServiceClient(_MatrixHomeserver hs, String token, String
4343

4444
private MatrixHttpClient createClient(String localpart) {
4545
return new MatrixHttpClient(
46-
new MatrixClientContext(getHomeserver(), getMatrixId(localpart), getAccessToken(), true));
46+
new MatrixClientContext(getHomeserver(), getMatrixId(localpart), getAccessTokenOrThrow(), true));
4747
}
4848

4949
@Override
5050
public _MatrixClient createUser(String localpart) {
5151
log.debug("Creating new user {}", localpart);
52-
URI path = getClientPath("/register");
52+
URI path = getClientPathWithAccessToken("/register");
5353
HttpPost req = new HttpPost(path);
5454
req.setEntity(getJsonEntity(new VirtualUserRegistrationBody(localpart)));
5555
execute(req);

src/main/java/io/kamax/matrix/client/regular/MatrixHttpClient.java

+48-5
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,19 @@
2525
import io.kamax.matrix._MatrixUser;
2626
import io.kamax.matrix.client.*;
2727
import io.kamax.matrix.hs._MatrixRoom;
28+
import io.kamax.matrix.json.LoginPostBody;
29+
import io.kamax.matrix.json.LoginResponse;
2830
import io.kamax.matrix.json.UserDisplaynameSetBody;
2931

32+
import org.apache.http.client.methods.HttpPost;
3033
import org.apache.http.client.methods.HttpPut;
31-
import org.slf4j.Logger;
32-
import org.slf4j.LoggerFactory;
34+
import org.apache.http.client.utils.URIBuilder;
3335

3436
import java.net.URI;
37+
import java.util.Optional;
3538

3639
public class MatrixHttpClient extends AMatrixHttpClient implements _MatrixClient {
3740

38-
private Logger log = LoggerFactory.getLogger(MatrixHttpClient.class);
39-
4041
public MatrixHttpClient(MatrixClientContext context) {
4142
super(context);
4243
}
@@ -45,9 +46,16 @@ protected _MatrixID getMatrixId(String localpart) {
4546
return new MatrixID(localpart, getHomeserver().getDomain());
4647
}
4748

49+
@Override
50+
protected URIBuilder getClientPathBuilder(String action) {
51+
URIBuilder builder = super.getClientPathBuilder(action);
52+
context.getUser().ifPresent(user -> builder.setPath(builder.getPath().replace("{userId}", user.getId())));
53+
return builder;
54+
}
55+
4856
@Override
4957
public void setDisplayName(String name) {
50-
URI path = getClientPath("/profile/{userId}/displayname");
58+
URI path = getClientPathWithAccessToken("/profile/{userId}/displayname");
5159
HttpPut req = new HttpPut(path);
5260
req.setEntity(getJsonEntity(new UserDisplaynameSetBody(name)));
5361
execute(req);
@@ -63,4 +71,39 @@ public _MatrixUser getUser(_MatrixID mxId) {
6371
return new MatrixHttpUser(getContext(), mxId);
6472
}
6573

74+
@Override
75+
public Optional<String> getDeviceId() {
76+
return context.getDeviceId();
77+
}
78+
79+
@Override
80+
public void login(MatrixPasswordLoginCredentials credentials) {
81+
HttpPost request = new HttpPost(getClientPath("/login"));
82+
if (context.getDeviceId().isPresent()) {
83+
request.setEntity(getJsonEntity(new LoginPostBody(credentials.getLocalPart(), credentials.getPassword(),
84+
context.getDeviceId().get())));
85+
} else {
86+
request.setEntity(getJsonEntity(new LoginPostBody(credentials.getLocalPart(), credentials.getPassword())));
87+
}
88+
89+
String body = execute(request);
90+
LoginResponse response = gson.fromJson(body, LoginResponse.class);
91+
context.setToken(response.getAccessToken());
92+
context.setDeviceId(response.getDeviceId());
93+
context.setUser(new MatrixID(response.getUserId()));
94+
95+
// FIXME spec returns hostname which we might not be the same as what has been used in baseUrl to login. Must
96+
// update internals accordingly
97+
}
98+
99+
@Override
100+
public void logout() {
101+
URI path = getClientPathWithAccessToken("/logout");
102+
HttpPost req = new HttpPost(path);
103+
execute(req);
104+
context.setToken(null);
105+
context.setUser(null);
106+
context.setDeviceId(null);
107+
}
108+
66109
}

0 commit comments

Comments
 (0)