Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,7 @@ repositories {
}

dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'

// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:28.1-jre'

implementation 'com.auth0:java-jwt:3.10.3'
compile 'com.github.kevinsawicki:http-request:6.0'
compile 'net.sf.json-lib:json-lib:2.4:jdk15'
// Use JUnit test framework
Expand All @@ -45,7 +40,7 @@ publishing {

publications {
maven(MavenPublication) {
version '0.1.6'
version '0.2'
group 'org.mushare'
from components.java
}
Expand Down
75 changes: 23 additions & 52 deletions src/main/java/org/mushare/pluto/Pluto.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
package org.mushare.pluto;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.kevinsawicki.http.HttpRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.mushare.pluto.exception.PlutoErrorCode;
import org.mushare.pluto.exception.PlutoException;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.security.interfaces.RSAPublicKey;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

Expand All @@ -33,64 +39,29 @@ public static void setup(String server, String appId) {
}

public static PlutoUser auth(String token) throws PlutoException {
if (token == null) {
throw new PlutoException(PlutoErrorCode.jwtFormatError);
}
String[] parts = token.split("\\.");
if (parts.length != 3) {
throw new PlutoException(PlutoErrorCode.jwtFormatError);
}

String header = null;
JSONObject payload = null;
try {
header = new String(Base64.getDecoder().decode(parts[0]), "utf-8");
payload = JSONObject.fromObject(new String(Base64.getDecoder().decode(parts[1]), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new PlutoException(PlutoErrorCode.other);
}
// Verify the appId of the jwt token.
if (!payload.getString("appId").equals(shared.appId)) {
throw new PlutoException(PlutoErrorCode.appIdError);
}
Long expire = payload.getLong("expire_time") * 1000;
if (expire < System.currentTimeMillis()) {
throw new PlutoException(PlutoErrorCode.expired);
}

boolean verified = false;
try {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(shared.keyManager.getPublicKey());
signature.update((header + payload).getBytes());
verified = signature.verify(Base64.getDecoder().decode(parts[2]));
} catch (Exception e) {
e.printStackTrace();
throw new PlutoException(PlutoErrorCode.other);
}

if (!verified) {
throw new PlutoException(PlutoErrorCode.notVerified);
}
return new PlutoUser(payload);
JWTVerifier verifier = JWT.require(Algorithm.RSA256((RSAPublicKey) shared.keyManager.getPublicKey()))
.withIssuer(shared.appId)
.build();
DecodedJWT jwt = verifier.verify(token);
return new PlutoUser(jwt.getClaims());
}

public static List<PlutoUserInfo> fetUserInfos(List<Long> userIds) {
if (userIds == null || userIds.size() == 0) {
return new ArrayList<>();
}
String ids = userIds.stream()
.map(userId -> userId + "-")
.map(userId -> "ids=" + userId)
.reduce("", (s1, s2) -> {
return s1 + s2;
return s1 + "&" + s2;
});
ids = ids.substring(0, ids.length() - 1);
String response = HttpRequest.get(shared.server + "api/user/info/" + ids).body();
JSONArray body = JSONObject.fromObject(response).getJSONArray("body");
return IntStream.range(0, body.size())
.mapToObj(index -> {
JSONObject object = body.getJSONObject(index);
System.out.println(shared.server + "v1/user/info/public?" + ids);
String response = HttpRequest.get(shared.server + "v1/user/info/public?" + ids).body();
JSONObject body = JSONObject.fromObject(response).getJSONObject("body");

return Arrays.stream(body.keySet().toArray())
.map(key -> {
JSONObject object = body.getJSONObject((String) key);
PlutoUserInfo info = new PlutoUserInfo();
info.setUserId(object.getLong("id"));
if (object.containsKey("err_code") && object.getInt("err_code") == 403) {
Expand Down
27 changes: 6 additions & 21 deletions src/main/java/org/mushare/pluto/PlutoUser.java
Original file line number Diff line number Diff line change
@@ -1,43 +1,28 @@
package org.mushare.pluto;

import com.auth0.jwt.interfaces.Claim;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PlutoUser {
private long userId;
private String deviceId;
private List<String> scopes;
private LoginType loginType;

public long getUserId() {
return userId;
}

public String getDeviceId() {
return deviceId;
}

public List<String> getScopes() {
return scopes;
}

public LoginType getLoginType() {
return loginType;
}

public PlutoUser(JSONObject payload) {
userId = payload.getLong("userId");
deviceId = payload.getString("deviceId");
scopes = new ArrayList<>();
if (payload.containsKey("scopes") && !payload.get("scopes").equals("null")) {
JSONArray scopeArray = payload.getJSONArray("scopes");
for (int i = 0; i < scopeArray.size(); i++) {
scopes.add(scopeArray.getString(i));
}
}
loginType = LoginType.fromIdentifier(payload.getString("login_type"));
public PlutoUser(Map<String, Claim> claims) {
userId = claims.get("sub").asLong();
scopes = claims.get("scopes").asList(String.class);
}
}
2 changes: 1 addition & 1 deletion src/main/java/org/mushare/pluto/PublicKeyManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void setPublicKey(PublicKey publicKey) {

public PublicKey getPublicKey() {
if (publicKey == null) {
String response = HttpRequest.get(server + "api/auth/publickey").body();
String response = HttpRequest.get(server + "v1/token/publickey").body();
String text = JSONObject.fromObject(response).getJSONObject("body").getString("public_key");
text = text.replaceAll("\r|\n", "")
.replace("-----BEGIN PUBLIC KEY-----", "")
Expand Down
12 changes: 6 additions & 6 deletions src/test/java/org/mushare/pluto/PlutoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
public class PlutoTest {

private void setup() {
Pluto.setup("https://staging.easyjapanese-api-gateway.mushare.cn/pluto/", "org.mushare.easyjapanese");
Pluto.setup("https://beta-pluto.kaboocha.com/", "org.mushare.easyjapanese");
}

@Test
public void testAuth() throws PlutoException {
setup();
String scope = "easyjapanese.admin";
String token = "eyJ0eXBlIjoiand0IiwiYWxnIjoicnNhIn0.eyJ0eXBlIjoiYWNjZXNzIiwiY3JlYXRlX3RpbWUiOjE1ODQ4NTQyNjEsImV4cGlyZV90aW1lIjoxNjE2MjE3NDYxLCJ1c2VySWQiOjMsImRldmljZUlkIjoiQ0Y0Mzc5MzMtQ0MyMS00QUFCLTgxNjEtMUU1MTVCNjQxQTU5IiwiYXBwSWQiOiJvcmcubXVzaGFyZS5lYXN5amFwYW5lc2UiLCJzY29wZXMiOlsiZWFzeWphcGFuZXNlLmFkbWluIl0sImxvZ2luX3R5cGUiOiJtYWlsIn0.RlrKt8fy+rXF9h9/H5w8es4Ni9IlCapDkuA8rxqX09Hv3VUFyY3tt+wdGTihNv9zZSm8Sf7m9ILkq0er826V9p1lUHk50pYlwigTvu4lG5g2uU/bAwt7EwPhxfco6XlA4Z0sQUqS49yM+dmVWnl66bhookkipcDZchpFzr3TOdbmPjTgJ8mMUZO46Kx1fSQhzOJdCAjdkMP44oeuTwcfn1NRZBXacF/HzVLpg+R8APv5oXAmvN4A8HSYoVMRaZn7Z1L6mspOyLfkOuNsOYT1iDM6jkAq0Lj/ST/n7fhNw+2+cadGe2aPBkeU8H7qzgQJEqE0iAlTtFQF6O1Qt0duxQ";
String scope = "easyjapanese.user";
String token = "eyJ0eXBlIjoiand0IiwiYWxnIjoicnNhIn0.eyJ0eXBlIjoiYWNjZXNzIiwiY3JlYXRlX3RpbWUiOjE1ODQ3MTA3NzksImV4cGlyZV90aW1lIjoxNTg0NzE0Mzc5LCJ1c2VySWQiOjMsImRldmljZUlkIjoiQ0Y0Mzc5MzMtQ0MyMS00QUFCLTgxNjEtMUU1MTVCNjQxQTU5IiwiYXBwSWQiOiJvcmcubXVzaGFyZS5lYXN5amFwYW5lc2UiLCJzY29wZXMiOlsiZWFzeWphcGFuZXNlLmFkbWluIl0sImxvZ2luX3R5cGUiOiJtYWlsIn0.TR0A/fen5f+kg4APscFQ7JZtp2zNw5KMUeKBzm/GJg4WZp90ihg/OPfU9fcaJhoVNHWqxQ/OIHfAcXaXV+l8EEsTbh/+/Qs0glujX09Vm5z23wITzC36X+a/9bJJj5J1kXDtyx/CVdMmf8vm81T8PJFJuJtnyzA3IMRUGK0KecJ5MQjaOvh7NxZRhJfsCNYQz4V5hxvtI8urs+gi3/QVN04UQ5i0BX+DDdQ1E4MX8+3v2zDPc3ipQ8r9nZl00wmPdcqW5zx9Xooha6X8eTujgQuLiSFDheZGRR6/N+ZYktt/PMI49KIXVseenTTTzpX1Vmg9PAabPLJotdjcRpKtiA";
assertTrue("testAuth should return 'true'", Pluto.auth(token).getScopes().contains(scope));
}

Expand All @@ -40,14 +40,14 @@ public void testAuthExpired() throws PlutoException {

@Test
public void testScopes() throws PlutoException {
Pluto.setup("https://easyjapanese-api-gateway.mushare.cn/pluto/", "org.mushare.easyjapanese");
String token = "eyJ0eXBlIjoiand0IiwiYWxnIjoicnNhIn0.eyJ0eXBlIjoiYWNjZXNzIiwiY3JlYXRlX3RpbWUiOjE1ODU0NDg1MTcsImV4cGlyZV90aW1lIjoxNTg1NDUyMTE3LCJ1c2VySWQiOjQ4LCJkZXZpY2VJZCI6IkM5QTExQTIzLTg1QTMtNEMwRC04RjQxLTE5QURBNEIwOTJFRSIsImFwcElkIjoib3JnLm11c2hhcmUuZWFzeWphcGFuZXNlIiwic2NvcGVzIjpudWxsLCJsb2dpbl90eXBlIjoiZ29vZ2xlIn0.LyYEgEIxc1ghirESmvvpDE/EEd9B0U10BRgbKt3YdfiCb6L3URizHIqJVoc6IhPZOOBNy2x2Dk/sCZ5JV1rtaZ8niMdAb7VL7PwObZiWuWT8TieuV+7DaPxcJrPdzgz46GOOX7o3+fWRr64ucOYZeiY/g0PBCL07dMPRHYyzHK7e8Wrb/59rUjO4GCad5vM5qny9jTXihB+IokBPOYDkhKCinOfMAqOOFOtVRVdxt/mCLhnjkxexwWM/a7vmJQ4qOZYHxAB9mbgDq+mbBfzWafFWhbADdZdSqyKnKUDguBE1fPRODLqTIqB0KL4cttgSHKivlwwiVaaxZUEkwGN4GQ";
setup();
String token = "eyJ0eXBlIjoiand0IiwiYWxnIjoiUlMyNTYifQ.eyJ0eXBlIjoiYWNjZXNzIiwiaWF0IjoxNjAxNTUxMjU1LCJleHAiOjE2MDE1NTQ4NTUsInN1YiI6NTIwMywiaXNzIjoib3JnLm11c2hhcmUuZWFzeWphcGFuZXNlIiwic2NvcGVzIjpbIiJdfQ.S3ZTAFFlwmV3DJCYQrN_N0GDbpAfIPZlwXd1uxlDdMxXw_vkkLDffYjJjEA-nQ2Q1wgImb3YqA-SI3mbv_giiqo83NgiCeLVYTRDqVxj-ZJYJQRllD0o09DeeI_v5_Mll2toWF3cQaF8yEkzPR-AmOph-0eOw7vC5VJoMYy1SiVIf04wOR7wByidhkwbkPnn7X3cjFytOLKA2ZE_ikMpZ02NfRllddxK9IBa-NYVd_1cIleU-a8WSz8xPKCDDrq5He0M2ZCN0DpXdi4p2FI4wCGRSi3YvcSHwszJWV8dQQcgNhVi9T_oPhWSSTG_dZjQB9TTLq4IkJj6XYyQv8kI6Q";
Pluto.auth(token);
}

@Test
public void testFetchUserInfos() {
Pluto.setup("https://staging.easyjapanese-api-gateway.mushare.cn/pluto/", "org.mushare.easyjapanese");
setup();
Pluto.fetUserInfos(Stream.of(1L, 2L, 3L).collect(Collectors.toList())).forEach(plutoUserInfo -> {
System.out.println(plutoUserInfo);
});
Expand Down